docs: 仓库链接指向本镜像仓库
Dev Build / cleanup (push) Waiting to run
Dev Build / typecheck (push) Waiting to run

This commit is contained in:
TanTan committed 2026-11-13 09:27:07 +08:00
1 parent fa9c73363d
commit 2a69b23b47
18210 files changed
+5101211 -16

No files matched your search

@@ -0,0 +1,22 @@
var hy=Object.defineProperty;var Sd=(e,t)=>{for(var a in t)hy(e,a,{get:t[a],enumerable:!0})};var Y0={};Sd(Y0,{parsers:()=>yd});var yd={};Sd(yd,{typescript:()=>y3});var yy=()=>()=>{},La=yy;var ja=(e,t)=>(a,s,...f)=>a|1&&s==null?void 0:(t.call(s)??s[e]).apply(s,f);var gy=String.prototype.replaceAll??function(e,t){return e.global?this.replace(e,t):this.split(e).join(t)},by=ja("replaceAll",function(){if(typeof this=="string")return gy}),yr=by;var km="6.0";var Tt=[],vy=new Map;function s_(e){return e!==void 0?e.length:0}function Bn(e,t){if(e!==void 0)for(let a=0;a<e.length;a++){let s=t(e[a],a);if(s)return s}}function xy(e,t){if(e!==void 0)for(let a=0;a<e.length;a++){let s=t(e[a],a);if(s!==void 0)return s}}function wd(e,t,a){let s=[];q.assertEqual(e.length,t.length);for(let f=0;f<e.length;f++)s.push(a(e[f],t[f],f));return s}function Qp(e,t){if(e!==void 0){for(let a=0;a<e.length;a++)if(!t(e[a],a))return!1}return!0}function Em(e,t,a){if(e!==void 0)for(let s=a??0;s<e.length;s++){let f=e[s];if(t(f,s))return f}}function Sp(e,t,a){if(e===void 0)return-1;for(let s=a??0;s<e.length;s++)if(t(e[s],s))return s;return-1}function Ty(e,t,a=ef){if(e!==void 0){for(let s=0;s<e.length;s++)if(a(e[s],t))return!0}return!1}function $r(e,t){if(e!==void 0){let a=e.length,s=0;for(;s<a&&t(e[s]);)s++;if(s<a){let f=e.slice(0,s);for(s++;s<a;){let h=e[s];t(h)&&f.push(h),s++}return f}}return e}function Lp(e,t){let a;if(e!==void 0){a=[];for(let s=0;s<e.length;s++)a.push(t(e[s],s))}return a}function Am(e){let t=[];for(let a=0;a<e.length;a++){let s=e[a];s&&(Kr(s)?Dn(t,s):t.push(s))}return t}function Cm(e,t){let a;if(e!==void 0)for(let s=0;s<e.length;s++){let f=t(e[s],s);f&&(Kr(f)?a=Dn(a,f):a=An(a,f))}return a??Tt}function Sy(e,t){let a;if(e!==void 0)for(let s=0;s<e.length;s++){let f=e[s],h=t(f,s);(a||f!==h||Kr(h))&&(a||(a=e.slice(0,s)),Kr(h)?Dn(a,h):a.push(h))}return a??e}function wy(e,t){let a=[];if(e!==void 0)for(let s=0;s<e.length;s++){let f=t(e[s],s);f!==void 0&&a.push(f)}return a}function nn(e,t){if(e!==void 0)if(t!==void 0){for(let a=0;a<e.length;a++)if(t(e[a]))return!0}else return e.length>0;return!1}function Kp(e,t){return t===void 0||t.length===0?e:e===void 0||e.length===0?t:[...e,...t]}function ky(e,t,a=ef){if(e===void 0||t===void 0)return e===t;if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!a(e[s],t[s],s))return!1;return!0}function An(e,t){return t===void 0?e:e===void 0?[t]:(e.push(t),e)}function jp(e,t){return t<0?e.length+t:t}function Dn(e,t,a,s){if(t===void 0||t.length===0)return e;if(e===void 0)return t.slice(a,s);a=a===void 0?0:jp(t,a),s=s===void 0?t.length:jp(t,s);for(let f=a;f<s&&f<t.length;f++)t[f]!==void 0&&e.push(t[f]);return e}function Ey(e,t,a){return Ty(e,t,a)?!1:(e.push(t),!0)}function Ay(e,t,a){return e!==void 0?(Ey(e,t,a),e):[t]}function Cy(e,t){return e.length===0?Tt:e.slice().sort(t)}var S3=Array.prototype.at?(e,t)=>e?.at(t):(e,t)=>{if(e!==void 0&&(t=jp(e,t),t<e.length))return e[t]};function Zp(e){return e===void 0||e.length===0?void 0:e[0]}function Va(e){return e===void 0||e.length===0?void 0:e[e.length-1]}function Dy(e){return q.assert(e.length!==0),e[e.length-1]}function Py(e){return e!==void 0&&e.length===1?e[0]:void 0}function Ny(e,t,a,s,f){return Iy(e,a(t),a,s,f)}function Iy(e,t,a,s,f){if(!nn(e))return-1;let h=f??0,b=e.length-1;for(;h<=b;){let v=h+(b-h>>1),l=a(e[v],v);switch(Math.sign(s(l,t))){case-1:h=v+1;break;case 0:return v;case 1:b=v-1;break}}return~h}function Oy(e,t,a,s,f){if(e&&e.length>0){let h=e.length;if(h>0){let b=s===void 0||s<0?0:s,v=f===void 0||b+f>h-1?h-1:b+f,l;for(arguments.length<=2?(l=e[b],b++):l=a;b<=v;)l=t(l,e[b],b),b++;return l}}return a}var Dm=Object.prototype.hasOwnProperty;function Or(e,t){return Dm.call(e,t)}function My(e){let t=[];for(let a in e)Dm.call(e,a)&&t.push(a);return t}function Ly(){let e=new Map;return e.add=jy,e.remove=Jy,e}function jy(e,t){let a=this.get(e);return a!==void 0?a.push(t):this.set(e,a=[t]),a}function Jy(e,t){let a=this.get(e);a!==void 0&&(Gy(a,t),a.length||this.delete(e))}function Kr(e){return Array.isArray(e)}function wp(e){return Kr(e)?e:[e]}function Ry(e,t){return e!==void 0&&t(e)?e:void 0}function Pr(e,t){return e!==void 0&&t(e)?e:q.fail(`Invalid cast. The supplied value ${e} did not pass the test '${q.getFunctionName(t)}'.`)}function Ha(e){}function Uy(){return!0}function xt(e){return e}function kd(e){let t;return()=>(e&&(t=e(),e=void 0),t)}function er(e){let t=new Map;return a=>{let s=`${typeof a}:${a}`,f=t.get(s);return f===void 0&&!t.has(s)&&(f=e(a),t.set(s,f)),f}}function ef(e,t){return e===t}function tf(e,t){return e===t||e!==void 0&&t!==void 0&&e.toUpperCase()===t.toUpperCase()}function By(e,t){return ef(e,t)}function qy(e,t){return e===t?0:e===void 0?-1:t===void 0?1:e<t?-1:1}function Pm(e,t){return qy(e,t)}function Fy(e,t,a){for(let s=0;s<e.length;s++)t=Math.max(t,a(e[s]));return t}function __(e,t,a){let s=Math.max(2,Math.floor(e.length*.34)),f=Math.floor(e.length*.4)+1,h;for(let b of t){let v=a(b);if(v!==void 0&&Math.abs(v.length-e.lLine truncated
Node ${Lt(L.kind)} was unexpected.`,de||W)}e.failBadSyntaxKind=W;function k(L,se,de,Se){L||(se=se?`False expression: ${se}`:"False expression.",de&&(se+=`\r
Verbose Debug Information: `+(typeof de=="string"?de:de())),y(se,Se||k))}e.assert=k;function C(L,se,de,Se,$e){if(L!==se){let Ze=de?Se?`${de} ${Se}`:de:"";y(`Expected ${L} === ${se}. ${Ze}`,$e||C)}}e.assertEqual=C;function R(L,se,de,Se){L>=se&&y(`Expected ${L} < ${se}. ${de||""}`,Se||R)}e.assertLessThan=R;function pe(L,se,de){L>se&&y(`Expected ${L} <= ${se}`,de||pe)}e.assertLessThanOrEqual=pe;function xe(L,se,de){L<se&&y(`Expected ${L} >= ${se}`,de||xe)}e.assertGreaterThanOrEqual=xe;function ge(L,se,de){L==null&&y(se,de||ge)}e.assertIsDefined=ge;function me(L,se,de){return ge(L,se,de||me),L}e.checkDefined=me;function I(L,se,de){for(let Se of L)ge(Se,se,de||I)}e.assertEachIsDefined=I;function ae(L,se,de){return I(L,se,de||ae),L}e.checkEachDefined=ae;function Le(L,se="Illegal value:",de){let Se=typeof L=="object"&&Or(L,"kind")&&Or(L,"pos")?"SyntaxKind: "+Lt(L.kind):JSON.stringify(L);return y(`${se} ${Se}`,de||Le)}e.assertNever=Le;function V(L,se,de,Se){G(1,"assertEachNode")&&k(se===void 0||Qp(L,se),de||"Unexpected node.",()=>`Node array did not pass test '${bn(se)}'.`,Se||V)}e.assertEachNode=V;function oe(L,se,de,Se){G(1,"assertNode")&&k(L!==void 0&&(se===void 0||se(L)),de||"Unexpected node.",()=>`Node ${Lt(L?.kind)} did not pass test '${bn(se)}'.`,Se||oe)}e.assertNode=oe;function Y(L,se,de,Se){G(1,"assertNotNode")&&k(L===void 0||se===void 0||!se(L),de||"Unexpected node.",()=>`Node ${Lt(L.kind)} should not have passed test '${bn(se)}'.`,Se||Y)}e.assertNotNode=Y;function mt(L,se,de,Se){G(1,"assertOptionalNode")&&k(se===void 0||L===void 0||se(L),de||"Unexpected node.",()=>`Node ${Lt(L?.kind)} did not pass test '${bn(se)}'.`,Se||mt)}e.assertOptionalNode=mt;function ar(L,se,de,Se){G(1,"assertOptionalToken")&&k(se===void 0||L===void 0||L.kind===se,de||"Unexpected node.",()=>`Node ${Lt(L?.kind)} was not a '${Lt(se)}' token.`,Se||ar)}e.assertOptionalToken=ar;function gn(L,se,de){G(1,"assertMissingNode")&&k(L===void 0,se||"Unexpected node.",()=>`Node ${Lt(L.kind)} was unexpected'.`,de||gn)}e.assertMissingNode=gn;function sr(L){}e.type=sr;function bn(L){if(typeof L!="function")return"";if(Or(L,"name"))return L.name;{let se=Function.prototype.toString.call(L),de=/^function\s+([\w$]+)\s*\(/.exec(se);return de?de[1]:""}}e.getFunctionName=bn;function In(L){return`{ name: ${h_(L.escapedName)}; flags: ${ct(L.flags)}; declarations: ${Lp(L.declarations,se=>Lt(se.kind))} }`}e.formatSymbol=In;function He(L=0,se,de){let Se=jr(se);if(L===0)return Se.length>0&&Se[0][0]===0?Se[0][1]:"0";if(de){let $e=[],Ze=L;for(let[_t,Pt]of Se){if(_t>L)break;_t!==0&&_t&L&&($e.push(Pt),Ze&=~_t)}if(Ze===0)return $e.join("|")}else for(let[$e,Ze]of Se)if($e===L)return Ze;return L.toString()}e.formatEnum=He;let _r=new Map;function jr(L){let se=_r.get(L);if(se)return se;let de=[];for(let $e in L){let Ze=L[$e];typeof Ze=="number"&&de.push([Ze,$e])}let Se=Cy(de,($e,Ze)=>Pm($e[0],Ze[0]));return _r.set(L,Se),Se}function Lt(L){return He(L,Ae,!1)}e.formatSyntaxKind=Lt;function Fn(L){return He(L,Lm,!1)}e.formatSnippetKind=Fn;function On(L){return He(L,Mr,!1)}e.formatScriptKind=On;function jt(L){return He(L,rn,!0)}e.formatNodeFlags=jt;function gt(L){return He(L,Im,!0)}e.formatNodeCheckFlags=gt;function Ke(L){return He(L,nf,!0)}e.formatModifierFlags=Ke;function zn(L){return He(L,Mm,!0)}e.formatTransformFlags=zn;function Zt(L){return He(L,jm,!0)}e.formatEmitFlags=Zt;function ct(L){return He(L,rf,!0)}e.formatSymbolFlags=ct;function st(L){return He(L,an,!0)}e.formatTypeFlags=st;function qt(L){return He(L,Om,!0)}e.formatSignatureFlags=qt;function Jt(L){return He(L,af,!0)}e.formatObjectFlags=Jt;function lt(L){return He(L,Rp,!0)}e.formatFlowFlags=lt;function or(L){return He(L,Nm,!0)}e.formatRelationComparisonResult=or;function ht(L){return He(L,CheckMode,!0)}e.formatCheckMode=ht;function vn(L){return He(L,SignatureCheckMode,!0)}e.formatSignatureCheckMode=vn;function bt(L){return He(L,TypeFacts,!0)}e.formatTypeFacts=bt;let ln=!1,it;function Ft(L){"__debugFlowFlags"in L||Object.defineProperties(L,{__tsDebuggerDisplay:{value(){let se=this.flags&2?"FlowStart":this.flags&4?"FlowBranchLabel":this.flags&8?"FlowLoopLabel":this.flags&16?"FlowAssignment":this.flags&32?"FlowTrueCondition":this.flags&64?"FlowFalseCondition":this.flags&128?"FlowSwitchClause":this.flags&256?"FlowArrayMutation":this.flags&512?"FlowCall":this.flags&1024?"FlowReduceLabel":this.flags&1?"FlowUnreachable":"UnknownFlow",de=this.flags&-2048;return`${se}${de?` (${lt(de)})`:""}`}},__debugFlowFlags:{get(){return He(this.flags,Rp,!0)}},__debugToString:{value(){return xr(this)}}})}function sn(L){return ln&&(typeof Object.setPrototypeOf=="function"?(it||(it=Object.create(Object.prototype),Ft(it)),Object.setPrototypeOf(L,it)):Ft(L)),L}e.attachFlowNodeDebugInfo=sn;let cr;function br(L){"__tsDebuggerDisplay"in L||Object.defineProperties(L,{__tsDebuggerDisplay:{value(se){return se=String(se).replace(/(?:,[\s\w]+:[^,]+)+\]$/,"]"),`NodeArray ${se}`}}})}function vr(L){ln&&(typeof Object.setPrototypeOf=="function"?(cr||Line truncated
`).join(`
`)}
m2: ${this.mapper2.__debugToString().split(`
`).join(`
`)}`;default:return Le(this)}}}e.DebugTypeMapper=Jr;function Gn(L){return e.isDebugging?Object.setPrototypeOf(L,Jr.prototype):L}e.attachDebugPrototypeIfDebug=Gn;function Pe(L){return console.log(xr(L))}e.printControlFlowGraph=Pe;function xr(L){let se=-1;function de(u){return u.id||(u.id=se,se--),u.id}let Se;(u=>{u.lr="\u2500",u.ud="\u2502",u.dr="\u256D",u.dl="\u256E",u.ul="\u256F",u.ur="\u2570",u.udr="\u251C",u.udl="\u2524",u.dlr="\u252C",u.ulr="\u2534",u.udlr="\u256B"})(Se||(Se={}));let $e;(u=>{u[u.None=0]="None",u[u.Up=1]="Up",u[u.Down=2]="Down",u[u.Left=4]="Left",u[u.Right=8]="Right",u[u.UpDown=3]="UpDown",u[u.LeftRight=12]="LeftRight",u[u.UpLeft=5]="UpLeft",u[u.UpRight=9]="UpRight",u[u.DownLeft=6]="DownLeft",u[u.DownRight=10]="DownRight",u[u.UpDownLeft=7]="UpDownLeft",u[u.UpDownRight=11]="UpDownRight",u[u.UpLeftRight=13]="UpLeftRight",u[u.DownLeftRight=14]="DownLeftRight",u[u.UpDownLeftRight=15]="UpDownLeftRight",u[u.NoChildren=16]="NoChildren"})($e||($e={}));let Ze=2032,_t=882,Pt=Object.create(null),St=[],ut=[],Rr=ke(L,new Set);for(let u of St)u.text=at(u.flowNode,u.circular),he(u);let Tr=Ye(Rr),Mn=tt(Tr);return Xe(Rr,0),un();function Yn(u){return!!(u.flags&128)}function Ei(u){return!!(u.flags&12)&&!!u.antecedent}function U(u){return!!(u.flags&Ze)}function K(u){return!!(u.flags&_t)}function Z(u){let Me=[];for(let je of u.edges)je.source===u&&Me.push(je.target);return Me}function we(u){let Me=[];for(let je of u.edges)je.target===u&&Me.push(je.source);return Me}function ke(u,Me){let je=de(u),B=Pt[je];if(B&&Me.has(u))return B.circular=!0,B={id:-1,flowNode:u,edges:[],text:"",lane:-1,endLane:-1,level:-1,circular:"circularity"},St.push(B),B;if(Me.add(u),!B)if(Pt[je]=B={id:je,flowNode:u,edges:[],text:"",lane:-1,endLane:-1,level:-1,circular:!1},St.push(B),Ei(u))for(let ze of u.antecedent)Ee(B,ze,Me);else U(u)&&Ee(B,u.antecedent,Me);return Me.delete(u),B}function Ee(u,Me,je){let B=ke(Me,je),ze={source:u,target:B};ut.push(ze),u.edges.push(ze),B.edges.push(ze)}function he(u){if(u.level!==-1)return u.level;let Me=0;for(let je of we(u))Me=Math.max(Me,he(je)+1);return u.level=Me}function Ye(u){let Me=0;for(let je of Z(u))Me=Math.max(Me,Ye(je));return Me+1}function tt(u){let Me=O(Array(u),0);for(let je of St)Me[je.level]=Math.max(Me[je.level],je.text.length);return Me}function Xe(u,Me){if(u.lane===-1){u.lane=Me,u.endLane=Me;let je=Z(u);for(let B=0;B<je.length;B++){B>0&&Me++;let ze=je[B];Xe(ze,Me),ze.endLane>u.endLane&&(Me=ze.endLane)}u.endLane=Me}}function De(u){if(u&2)return"Start";if(u&4)return"Branch";if(u&8)return"Loop";if(u&16)return"Assignment";if(u&32)return"True";if(u&64)return"False";if(u&128)return"SwitchClause";if(u&256)return"ArrayMutation";if(u&512)return"Call";if(u&1024)return"ReduceLabel";if(u&1)return"Unreachable";throw new Error}function xn(u){let Me=bi(u);return Bd(Me,u,!1)}function at(u,Me){let je=De(u.flags);if(Me&&(je=`${je}#${de(u)}`),Yn(u)){let B=[],{switchStatement:ze,clauseStart:_n,clauseEnd:Ge}=u.node;for(let Qe=_n;Qe<Ge;Qe++){let Nt=ze.caseBlock.clauses[Qe];gv(Nt)?B.push("default"):B.push(xn(Nt.expression))}je+=` (${B.join(", ")})`}else K(u)&&u.node&&(je+=` (${xn(u.node)})`);return Me==="circularity"?`Circular(${je})`:je}function un(){let u=Mn.length,Me=Fy(St,0,Ge=>Ge.lane)+1,je=O(Array(Me),""),B=Mn.map(()=>Array(Me)),ze=Mn.map(()=>O(Array(Me),0));for(let Ge of St){B[Ge.level][Ge.lane]=Ge;let Qe=Z(Ge);for(let Et=0;Et<Qe.length;Et++){let It=Qe[Et],zt=8;It.lane===Ge.lane&&(zt|=4),Et>0&&(zt|=1),Et<Qe.length-1&&(zt|=2),ze[Ge.level][It.lane]|=zt}Qe.length===0&&(ze[Ge.level][Ge.lane]|=16);let Nt=we(Ge);for(let Et=0;Et<Nt.length;Et++){let It=Nt[Et],zt=4;Et>0&&(zt|=1),Et<Nt.length-1&&(zt|=2),ze[Ge.level-1][It.lane]|=zt}}for(let Ge=0;Ge<u;Ge++)for(let Qe=0;Qe<Me;Qe++){let Nt=Ge>0?ze[Ge-1][Qe]:0,Et=Qe>0?ze[Ge][Qe-1]:0,It=ze[Ge][Qe];It||(Nt&8&&(It|=12),Et&2&&(It|=3),ze[Ge][Qe]=It)}for(let Ge=0;Ge<u;Ge++)for(let Qe=0;Qe<je.length;Qe++){let Nt=ze[Ge][Qe],Et=Nt&4?"\u2500":" ",It=B[Ge][Qe];It?(_n(Qe,It.text),Ge<u-1&&(_n(Qe," "),_n(Qe,qe(Et,Mn[Ge]-It.text.length)))):Ge<u-1&&_n(Qe,qe(Et,Mn[Ge]+1)),_n(Qe,ei(Nt)),_n(Qe,Nt&8&&Ge<u-1&&!B[Ge+1][Qe]?"\u2500":" ")}return`
${je.join(`
`)}
`;function _n(Ge,Qe){je[Ge]+=Qe}}function ei(u){switch(u){case 3:return"\u2502";case 12:return"\u2500";case 5:return"\u256F";case 9:return"\u2570";case 6:return"\u256E";case 10:return"\u256D";case 7:return"\u2524";case 11:return"\u251C";case 13:return"\u2534";case 14:return"\u252C";case 15:return"\u256B"}return" "}function O(u,Me){if(u.fill)u.fill(Me);else for(let je=0;je<u.length;je++)u[je]=Me;return u}function qe(u,Me){if(u.repeat)return Me>0?u.repeat(Me):"";let je="";for(;je.length<Me;)je+=u;return je}}e.formatControlFlowGraph=xr})(q||(q={}));var w3=Date.now,Ed=()=>{},Hy=()=>{},hl,Ae=(e=>(e[e.Unknown=0]="Unknown",e[e.EndOfFileToken=1]="EndOfFileToken",e[e.SingleLineCommentTrivia=2]="SingleLineCommentTrivia",e[e.MultiLineCommentTrivia=3]="MultiLineCommentTrivia",e[e.NewLineTrivia=4]="NewLineTrivia",e[e.WhitespaceTrivia=5]="WhitespaceTrivia",e[e.ShebangTrivia=6]="ShebangTrivia",e[e.ConflictMarkerTrivia=7]="ConflictMarkerTrivia",e[e.NonTextFileMarkerTrivia=8]="NonTextFileMarkerTrivia",e[e.NumericLiteral=9]="NumericLiteral",e[e.BigIntLiteral=10]="BigIntLiteral",e[e.StringLiteral=11]="StringLiteral",e[e.JsxText=12]="JsxText",e[e.JsxTextAllWhiteSpaces=13]="JsxTextAllWhiteSpaces",e[e.RegularExpressionLiteral=14]="RegularExpressionLiteral",e[e.NoSubstitutionTemplateLiteral=15]="NoSubstitutionTemplateLiteral",e[e.TemplateHead=16]="TemplateHead",e[e.TemplateMiddle=17]="TemplateMiddle",e[e.TemplateTail=18]="TemplateTail",e[e.OpenBraceToken=19]="OpenBraceToken",e[e.CloseBraceToken=20]="CloseBraceToken",e[e.OpenParenToken=21]="OpenParenToken",e[e.CloseParenToken=22]="CloseParenToken",e[e.OpenBracketToken=23]="OpenBracketToken",e[e.CloseBracketToken=24]="CloseBracketToken",e[e.DotToken=25]="DotToken",e[e.DotDotDotToken=26]="DotDotDotToken",e[e.SemicolonToken=27]="SemicolonToken",e[e.CommaToken=28]="CommaToken",e[e.QuestionDotToken=29]="QuestionDotToken",e[e.LessThanToken=30]="LessThanToken",e[e.LessThanSlashToken=31]="LessThanSlashToken",e[e.GreaterThanToken=32]="GreaterThanToken",e[e.LessThanEqualsToken=33]="LessThanEqualsToken",e[e.GreaterThanEqualsToken=34]="GreaterThanEqualsToken",e[e.EqualsEqualsToken=35]="EqualsEqualsToken",e[e.ExclamationEqualsToken=36]="ExclamationEqualsToken",e[e.EqualsEqualsEqualsToken=37]="EqualsEqualsEqualsToken",e[e.ExclamationEqualsEqualsToken=38]="ExclamationEqualsEqualsToken",e[e.EqualsGreaterThanToken=39]="EqualsGreaterThanToken",e[e.PlusToken=40]="PlusToken",e[e.MinusToken=41]="MinusToken",e[e.AsteriskToken=42]="AsteriskToken",e[e.AsteriskAsteriskToken=43]="AsteriskAsteriskToken",e[e.SlashToken=44]="SlashToken",e[e.PercentToken=45]="PercentToken",e[e.PlusPlusToken=46]="PlusPlusToken",e[e.MinusMinusToken=47]="MinusMinusToken",e[e.LessThanLessThanToken=48]="LessThanLessThanToken",e[e.GreaterThanGreaterThanToken=49]="GreaterThanGreaterThanToken",e[e.GreaterThanGreaterThanGreaterThanToken=50]="GreaterThanGreaterThanGreaterThanToken",e[e.AmpersandToken=51]="AmpersandToken",e[e.BarToken=52]="BarToken",e[e.CaretToken=53]="CaretToken",e[e.ExclamationToken=54]="ExclamationToken",e[e.TildeToken=55]="TildeToken",e[e.AmpersandAmpersandToken=56]="AmpersandAmpersandToken",e[e.BarBarToken=57]="BarBarToken",e[e.QuestionToken=58]="QuestionToken",e[e.ColonToken=59]="ColonToken",e[e.AtToken=60]="AtToken",e[e.QuestionQuestionToken=61]="QuestionQuestionToken",e[e.BacktickToken=62]="BacktickToken",e[e.HashToken=63]="HashToken",e[e.EqualsToken=64]="EqualsToken",e[e.PlusEqualsToken=65]="PlusEqualsToken",e[e.MinusEqualsToken=66]="MinusEqualsToken",e[e.AsteriskEqualsToken=67]="AsteriskEqualsToken",e[e.AsteriskAsteriskEqualsToken=68]="AsteriskAsteriskEqualsToken",e[e.SlashEqualsToken=69]="SlashEqualsToken",e[e.PercentEqualsToken=70]="PercentEqualsToken",e[e.LessThanLessThanEqualsToken=71]="LessThanLessThanEqualsToken",e[e.GreaterThanGreaterThanEqualsToken=72]="GreaterThanGreaterThanEqualsToken",e[e.GreaterThanGreaterThanGreaterThanEqualsToken=73]="GreaterThanGreaterThanGreaterThanEqualsToken",e[e.AmpersandEqualsToken=74]="AmpersandEqualsToken",e[e.BarEqualsToken=75]="BarEqualsToken",e[e.BarBarEqualsToken=76]="BarBarEqualsToken",e[e.AmpersandAmpersandEqualsToken=77]="AmpersandAmpersandEqualsToken",e[e.QuestionQuestionEqualsToken=78]="QuestionQuestionEqualsToken",e[e.CaretEqualsToken=79]="CaretEqualsToken",e[e.Identifier=80]="Identifier",e[e.PrivateIdentifier=81]="PrivateIdentifier",e[e.JSDocCommentTextToken=82]="JSDocCommentTextToken",e[e.BreakKeyword=83]="BreakKeyword",e[e.CaseKeyword=84]="CaseKeyword",e[e.CatchKeyword=85]="CatchKeyword",e[e.ClassKeyword=86]="ClassKeyword",e[e.ConstKeyword=87]="ConstKeyword",e[e.ContinueKeyword=88]="ContinueKeyword",e[e.DebuggerKeyword=89]="DebuggerKeyword",e[e.DefaultKeyword=90]="DefaultKeyword",e[e.DeleteKeyword=91]="DeleteKeyword",e[e.DoKeyword=92]="DoKeyword",e[e.ElseKeyword=93]="ElseKeyword",e[e.EnumKeyword=94]="EnumKeyword",e[e.ExportKeyword=95]="ExportKeyword",e[e.ExtendsKeyword=96]="ExtendsKeyword",e[e.FalseKeyword=97]="FalseKeyword",e[e.FinallyKeyword=98]="FinallyKeyLine truncated
`,Z=l;continue}l++}return q.assert(ke!==void 0),C=we,ke}function Lt(U){let K=l;if(l++,l>=G)return Y(E.Unexpected_end_of_text),"";let Z=V(l);switch(l++,Z){case 48:if(l>=G||!hi(V(l)))return"\0";case 49:case 50:case 51:l<G&&Ep(V(l))&&l++;case 52:case 53:case 54:case 55:if(l<G&&Ep(V(l))&&l++,R|=2048,U&6){let Ee=parseInt(v.substring(K+1,l),8);return U&4&&!(U&32)&&Z!==48?Y(E.Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended_as_an_escape_sequence_use_the_syntax_0_instead,K,l-K,"\\x"+Ee.toString(16).padStart(2,"0")):Y(E.Octal_escape_sequences_are_not_allowed_Use_the_syntax_0,K,l-K,"\\x"+Ee.toString(16).padStart(2,"0")),String.fromCharCode(Ee)}return v.substring(K,l);case 56:case 57:return R|=2048,U&6?(U&4&&!(U&32)?Y(E.Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class,K,l-K):Y(E.Escape_sequence_0_is_not_allowed,K,l-K,v.substring(K,l)),String.fromCharCode(Z)):v.substring(K,l);case 98:return"\b";case 116:return" ";case 110:return`
`;case 118:return"\v";case 102:return"\f";case 114:return"\r";case 39:return"'";case 34:return'"';case 117:if(l<G&&V(l)===123){l-=2;let Ee=Fn(!!(U&6));return U&17||(R|=2048,U&6&&Y(E.Unicode_escape_sequences_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_set,K,l-K)),Ee}for(;l<K+6;l++)if(!(l<G&&kp(V(l))))return R|=2048,U&6&&Y(E.Hexadecimal_digit_expected),v.substring(K,l);R|=1024;let we=parseInt(v.substring(K+2,l),16),ke=String.fromCharCode(we);if(U&16&&we>=55296&&we<=56319&&l+6<G&&v.substring(l,l+2)==="\\u"&&V(l+2)!==123){let Ee=l,he=l+2;for(;he<Ee+6;he++)if(!kp(V(he)))return ke;let Ye=parseInt(v.substring(Ee+2,he),16);if(Ye>=56320&&Ye<=57343)return l=he,ke+String.fromCharCode(Ye)}return ke;case 120:for(;l<K+4;l++)if(!(l<G&&kp(V(l))))return R|=2048,U&6&&Y(E.Hexadecimal_digit_expected),v.substring(K,l);return R|=4096,String.fromCharCode(parseInt(v.substring(K+2,l),16));case 13:l<G&&V(l)===10&&l++;case 10:case 8232:case 8233:return"";default:return(U&16||U&4&&!(U&8)&&Nr(Z,e))&&Y(E.This_character_cannot_be_escaped_in_a_regular_expression,l-2,2),String.fromCharCode(Z)}}function Fn(U){let K=l;l+=3;let Z=l,we=In(1,!1),ke=we?parseInt(we,16):-1,Ee=!1;return ke<0?(U&&Y(E.Hexadecimal_digit_expected),Ee=!0):ke>1114111&&(U&&Y(E.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive,Z,l-Z),Ee=!0),l>=G?(U&&Y(E.Unexpected_end_of_text),Ee=!0):V(l)===125?l++:(U&&Y(E.Unterminated_Unicode_escape_sequence),Ee=!0),Ee?(R|=2048,v.substring(K,l)):(R|=8,Id(ke))}function On(){if(l+5<G&&V(l+1)===117){let U=l;l+=2;let K=bn(4,!1);return l=U,K}return-1}function jt(){if(ae(l+1)===117&&ae(l+2)===123){let U=l;l+=3;let K=In(1,!1),Z=K?parseInt(K,16):-1;return l=U,Z}return-1}function gt(){let U="",K=l;for(;l<G;){let Z=ae(l);if(Nr(Z,e))l+=Wt(Z);else if(Z===92){if(Z=jt(),Z>=0&&Nr(Z,e)){U+=Fn(!0),K=l;continue}if(Z=On(),!(Z>=0&&Nr(Z,e)))break;R|=1024,U+=v.substring(K,l),U+=Id(Z),l+=6,K=l}else break}return U+=v.substring(K,l),U}function Ke(){let U=C.length;if(U>=2&&U<=12){let K=C.charCodeAt(0);if(K>=97&&K<=122){let Z=sg.get(C);if(Z!==void 0)return k=Z}}return k=80}function zn(U){let K="",Z=!1,we=!1;for(;;){let ke=V(l);if(ke===95){R|=512,Z?(Z=!1,we=!0):Y(we?E.Multiple_consecutive_numeric_separators_are_not_permitted:E.Numeric_separators_are_not_allowed_here,l,1),l++;continue}if(Z=!0,!hi(ke)||ke-48>=U)break;K+=v[l],l++,we=!1}return V(l-1)===95&&Y(E.Numeric_separators_are_not_allowed_here,l-1,1),K}function Zt(){return V(l)===110?(C+="n",R&384&&(C=Lb(C)+"n"),l++,10):(C=""+(R&128?parseInt(C.slice(2),2):R&256?parseInt(C.slice(2),8):+C),9)}function ct(){for(y=l,R=0;;){if(W=l,l>=G)return k=1;let U=ae(l);if(l===0&&U===35&&Xm(v,l)){if(l=$m(v,l),t)continue;return k=6}switch(U){case 10:case 13:if(R|=1,t){l++;continue}else return U===13&&l+1<G&&V(l+1)===10?l+=2:l++,k=4;case 9:case 11:case 12:case 32:case 160:case 5760:case 8192:case 8193:case 8194:case 8195:case 8196:case 8197:case 8198:case 8199:case 8200:case 8201:case 8202:case 8203:case 8239:case 8287:case 12288:case 65279:if(t){l++;continue}else{for(;l<G&&o_(V(l));)l++;return k=5}case 33:return V(l+1)===61?V(l+2)===61?(l+=3,k=38):(l+=2,k=36):(l++,k=54);case 34:case 39:return C=_r(),k=11;case 96:return k=jr(!1);case 37:return V(l+1)===61?(l+=2,k=70):(l++,k=45);case 38:return V(l+1)===38?V(l+2)===61?(l+=3,k=77):(l+=2,k=56):V(l+1)===61?(l+=2,k=74):(l++,k=51);case 40:return l++,k=21;case 41:return l++,k=22;case 42:if(V(l+1)===61)return l+=2,k=67;if(V(l+1)===42)return V(l+2)===61?(l+=3,k=68):(l+=2,k=43);if(l++,xe&&(R&32768)===0&&R&1){R|=32768;continue}return k=42;case 43:return V(l+1)===43?(l+=2,k=46):V(l+1)===61?(l+=2,k=65):(l++,k=40);case 44:return l++,k=28;case 45:return V(l+1)===45?(l+=2,k=47):V(l+1)===61?(l+=2,k=66):(l++,k=41);case 46:return hi(V(l+1))?(ar(),k=9):V(l+1)===46&&V(l+2)===46?(l+=3,k=26):(l++,k=25);case 47:if(V(l+1)===47){for(l+=2;l<G&&!Cn(V(l));)l++;if(pe=ln(pe,v.slice(W,l),pg,W),t)continue;return k=2}if(V(l+1)===42){l+=2;let he=V(l)===42&&V(l+1)!==47,Ye=!1,tt=W;for(;l<G;){let Xe=V(l);if(Xe===42&&V(l+1)===47){l+=2,Ye=!0;break}l++,Cn(Xe)&&(tt=l,R|=1)}if(he&&st()&&(R|=2),pe=ln(pe,v.slice(tt,l),fg,tt),Ye||Y(E.Asterisk_Slash_expected),t)continue;return Ye||(R|=4),k=3}return V(l+1)===61?(l+=2,k=69):(l++,k=44);case 48:if(l+2<G&&(V(l+1)===88||V(l+1)===120))return l+=2,C=In(1,!0),C||(Y(E.Hexadecimal_digit_expected),C="0"),C="0x"+C,R|=64,k=Zt();if(l+2<G&&(V(l+1)===66||V(l+1)===98))return l+=2,C=zn(2),C||(Y(E.Binary_digit_expected),C="0"),C="0b"+C,R|=128,k=Zt();if(l+2<G&&(V(l+1)===79||V(l+1)===111))return l+=2,C=zn(8),C||(Y(E.Octal_digit_expected),C="0"),C="0o"+C,R|=256,k=Zt();case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return k=ar();case 58:return l++,k=59;case 59:return l++,k=27;case 60:if(Qi(v,l)){if(l=Ra(v,l,Y),t)continue;return k=7}return V(l+1)===60?V(l+2)===61?(l+=3,k=71):(l+=2,k=48):V(l+1)===61?(l+=2,k=33):a===1&&V(l+1)===47&&V(l+2)!==42?(l+=2,k=31):(l++,k=30);case 61:if(Qi(v,l)){if(l=Ra(v,l,Y),t)continue;return k=7}retuLine truncated
`)),s}function Ya(e){let t=e.emitNode;return t&&t.flags||0}function w2(e,t,a){q.assertGreaterThanOrEqual(t,0),q.assertGreaterThanOrEqual(a,0),q.assertLessThanOrEqual(t,e.length),q.assertLessThanOrEqual(t+a,e.length)}function gl(e){return e.kind===245&&e.expression.kind===11}function Tf(e){return!!(Ya(e)&2097152)}function qd(e){return Tf(e)&&zf(e)}function k2(e){return et(e.name)&&!e.initializer}function Fd(e){return Tf(e)&&es(e)&&Qp(e.declarationList.declarations,k2)}function E2(e,t){let a=e.kind===170||e.kind===169||e.kind===219||e.kind===220||e.kind===218||e.kind===261||e.kind===282?Kp(Sg(t,e.pos),Bp(t,e.pos)):Bp(t,e.pos);return $r(a,s=>s.end<=e.end&&t.charCodeAt(s.pos+1)===42&&t.charCodeAt(s.pos+2)===42&&t.charCodeAt(s.pos+3)!==47)}function A2(e){if(e)switch(e.kind){case 209:case 307:case 170:case 304:case 173:case 172:case 305:case 261:return!0}return!1}function C2(e){return e&&e.kind===242&&xf(e.parent)}function zd(e){let t=e.kind;return(t===212||t===213)&&e.expression.kind===108}function aa(e){return!!e&&!!(e.flags&524288)}function D2(e){return!!e&&!!(e.flags&16777216)}function P2(e){for(;El(e,!0);)e=e.right;return e}function N2(e){return et(e)&&e.escapedText==="exports"}function I2(e){return et(e)&&e.escapedText==="module"}function g1(e){return(gr(e)||b1(e))&&I2(e.expression)&&b_(e)==="exports"}function Sf(e){let t=M2(e);return t===5||aa(e)?t:0}function O2(e){return s_(e.arguments)===3&&gr(e.expression)&&et(e.expression.expression)&&Pn(e.expression.expression)==="Object"&&Pn(e.expression.name)==="defineProperty"&&Ol(e.arguments[1])&&g_(e.arguments[0],!0)}function b1(e){return Za(e)&&Ol(e.argumentExpression)}function k_(e,t){return gr(e)&&(!t&&e.expression.kind===110||et(e.name)&&g_(e.expression,!0))||v1(e,t)}function v1(e,t){return b1(e)&&(!t&&e.expression.kind===110||Cf(e.expression)||k_(e.expression,!0))}function g_(e,t){return Cf(e)||k_(e,t)}function M2(e){if(Uf(e)){if(!O2(e))return 0;let t=e.arguments[0];return N2(t)||g1(t)?8:k_(t)&&b_(t)==="prototype"?9:7}return e.operatorToken.kind!==64||!E1(e.left)||L2(P2(e))?0:g_(e.left.expression,!0)&&b_(e.left)==="prototype"&&Rf(J2(e))?6:j2(e.left)}function L2(e){return fv(e)&&sa(e.expression)&&e.expression.text==="0"}function wf(e){if(gr(e))return e.name;let t=Ef(e.argumentExpression);return sa(t)||Il(t)?t:e}function b_(e){let t=wf(e);if(t){if(et(t))return t.escapedText;if(Il(t)||sa(t))return Ua(t.text)}}function j2(e){if(e.expression.kind===110)return 4;if(g1(e))return 2;if(g_(e.expression,!0)){if(pb(e.expression))return 3;let t=e;for(;!et(t.expression);)t=t.expression;let a=t.expression;if((a.escapedText==="exports"||a.escapedText==="module"&&b_(t)==="exports")&&k_(e))return 1;if(g_(e,!0)||Za(e)&&Q2(e))return 5}return 0}function J2(e){for(;ra(e.right);)e=e.right;return e.right}function R2(e){return Ll(e)&&ra(e.expression)&&Sf(e.expression)!==0&&ra(e.expression.right)&&(e.expression.right.operatorToken.kind===57||e.expression.right.operatorToken.kind===61)?e.expression.right.right:void 0}function U2(e){switch(e.kind){case 244:let t=Vp(e);return t&&t.initializer;case 173:return e.initializer;case 304:return e.initializer}}function Vp(e){return es(e)?Zp(e.declarationList.declarations):void 0}function B2(e){return Si(e)&&e.body&&e.body.kind===268?e.body:void 0}function kf(e){switch(e.kind){case 220:case 227:case 242:case 253:case 180:case 297:case 264:case 232:case 176:case 177:case 186:case 181:case 252:case 260:case 247:case 213:case 243:case 1:case 267:case 307:case 278:case 279:case 282:case 245:case 250:case 251:case 249:case 263:case 219:case 185:case 178:case 80:case 246:case 273:case 272:case 182:case 265:case 318:case 324:case 257:case 175:case 174:case 268:case 203:case 271:case 211:case 170:case 218:case 212:case 304:case 173:case 172:case 254:case 241:case 179:case 305:case 306:case 256:case 258:case 259:case 266:case 169:case 261:case 244:case 248:case 255:return!0;default:return!1}}function q2(e,t){let a;A2(e)&&y2(e)&&Zi(e.initializer)&&(a=Dn(a,Vd(e,e.initializer.jsDoc)));let s=e;for(;s&&s.parent;){if(Zi(s)&&(a=Dn(a,Vd(e,s.jsDoc))),s.kind===170){a=Dn(a,(t?Lg:Mg)(s));break}if(s.kind===169){a=Dn(a,(t?Jg:jg)(s));break}s=z2(s)}return a||Tt}function Vd(e,t){let a=Dy(t);return Cm(t,s=>{if(s===a){let f=$r(s.tags,h=>F2(e,h));return s.tags===f?[s]:f}else return $r(s.tags,Ev)})}function F2(e,t){return!(Xf(t)||Pv(t))||!t.parent||!ch(t.parent)||!Ml(t.parent.parent)||t.parent.parent===e}function z2(e){let t=e.parent;if(t.kind===304||t.kind===278||t.kind===173||t.kind===245&&e.kind===212||t.kind===254||B2(t)||El(e))return t;if(t.parent&&(Vp(t.parent)===e||El(t)))return t.parent;if(t.parent&&t.parent.parent&&(Vp(t.parent.parent)||U2(t.parent.parent)===e||R2(t.parent.parent)))return t.parent.parent}function Ef(e,t){return $f(e,t?-2147483647:1)}function V2(e){let t=W2(e);if(t&&aa(e)){let a=Rg(e);if(a)return a.class}return t}function W2(e){let t=Af(e.heritageClauses,96);return t&&t.types.length>0?t.types[0]:void 0}function G2(e){if(aa(e))return Ug(e).map(t=>t.cLine truncated
`,te)+1)+4;function ne(Be){X||(X=$),Jn.push(Be),$+=Be.length}for(ze();Yi(5););Yi(4)&&(N=0,$=0);e:for(;;){switch(u()){case 60:vp(Jn),mr||(mr=O()),We(r($)),N=0,X=void 0;break;case 4:Jn.push(t.getTokenText()),N=0,$=0;break;case 42:let Be=t.getTokenText();N===1?(N=2,ne(Be)):(q.assert(N===0),N=1,$+=Be.length);break;case 5:q.assert(N!==2,"whitespace shouldn't come from the scanner while saving top-level comment text");let pt=t.getTokenText();X!==void 0&&$+pt.length>X&&Jn.push(pt.slice(X-$)),$+=pt.length;break;case 1:break e;case 82:N=2,ne(t.getTokenValue());break;case 19:N=2;let hn=t.getTokenFullStart(),cn=t.getTokenEnd()-1,tn=c(cn);if(tn){dr||Vi(Jn),Hr.push(D(y.createJSDocText(Jn.join("")),dr??te,hn)),Hr.push(tn),Jn=[],dr=t.getTokenEnd();break}default:N=2,ne(t.getTokenText());break}N===2?_n(!1):ze()}let re=Jn.join("").trimEnd();Hr.length&&re.length&&Hr.push(D(y.createJSDocText(re),dr??te,mr)),Hr.length&&Ne&&q.assertIsDefined(mr,"having parsed tags implies that the end of the comment span should be set");let Oe=Ne&&Dt(Ne,Xt,Ot);return D(y.createJSDocComment(Hr.length?Dt(Hr,te,mr):re.length?re:void 0,Oe),te,Re)}function Vi(N){for(;N.length&&(N[0]===`
`||N[0]==="\r");)N.shift()}function vp(N){for(;N.length;){let X=N[N.length-1].trimEnd();if(X==="")N.pop();else if(X.length<N[N.length-1].length){N[N.length-1]=X;break}else break}}function Kn(){for(;;){if(ze(),u()===1)return!0;if(!(u()===5||u()===4))return!1}}function wn(){if(!((u()===5||u()===4)&&H(Kn)))for(;u()===5||u()===4;)ze()}function J(){if((u()===5||u()===4)&&H(Kn))return"";let N=t.hasPrecedingLineBreak(),X=!1,$="";for(;N&&u()===42||u()===5||u()===4;)$+=t.getTokenText(),u()===4?(N=!0,X=!0,$=""):u()===42&&(N=!1),ze();return X?$:""}function r(N){q.assert(u()===60);let X=t.getTokenStart();ze();let $=pi(void 0),ne=J(),re;switch($.escapedText){case"author":re=K0(X,$,N,ne);break;case"implements":re=ey(X,$,N,ne);break;case"augments":case"extends":re=ty(X,$,N,ne);break;case"class":case"constructor":re=Gi(X,y.createJSDocClassTag,$,N,ne);break;case"public":re=Gi(X,y.createJSDocPublicTag,$,N,ne);break;case"private":re=Gi(X,y.createJSDocPrivateTag,$,N,ne);break;case"protected":re=Gi(X,y.createJSDocProtectedTag,$,N,ne);break;case"readonly":re=Gi(X,y.createJSDocReadonlyTag,$,N,ne);break;case"override":re=Gi(X,y.createJSDocOverrideTag,$,N,ne);break;case"deprecated":Gn=!0,re=Gi(X,y.createJSDocDeprecatedTag,$,N,ne);break;case"this":re=vd(X,$,N,ne);break;case"enum":re=ay(X,$,N,ne);break;case"arg":case"argument":case"param":return Wi(X,$,2,N);case"return":case"returns":re=X0(X,$,N,ne);break;case"template":re=Td(X,$,N,ne);break;case"type":re=gd(X,$,N,ne);break;case"typedef":re=sy(X,$,N,ne);break;case"callback":re=oy(X,$,N,ne);break;case"overload":re=cy(X,$,N,ne);break;case"satisfies":re=ny(X,$,N,ne);break;case"see":re=$0(X,$,N,ne);break;case"exception":case"throws":re=Q0(X,$,N,ne);break;case"import":re=ry(X,$,N,ne);break;default:re=fe(X,$,N,ne);break}return re}function i(N,X,$,ne){return ne||($+=X-N),_($,ne.slice($))}function _(N,X){let $=O(),ne=[],re=[],Oe,Be=0,pt;function hn(Zn){pt||(pt=N),ne.push(Zn),N+=Zn.length}X!==void 0&&(X!==""&&hn(X),Be=1);let cn=u();e:for(;;){switch(cn){case 4:Be=0,ne.push(t.getTokenText()),N=0;break;case 60:t.resetTokenState(t.getTokenEnd()-1);break e;case 1:break e;case 5:q.assert(Be!==2&&Be!==3,"whitespace shouldn't come from the scanner while saving comment text");let Zn=t.getTokenText();pt!==void 0&&N+Zn.length>pt&&(ne.push(Zn.slice(pt-N)),Be=2),N+=Zn.length;break;case 19:Be=2;let _l=t.getTokenFullStart(),Ma=t.getTokenEnd()-1,ol=c(Ma);ol?(re.push(D(y.createJSDocText(ne.join("")),Oe??$,_l)),re.push(ol),ne=[],Oe=t.getTokenEnd()):hn(t.getTokenText());break;case 62:Be===3?Be=2:Be=3,hn(t.getTokenText());break;case 82:Be!==3&&(Be=2),hn(t.getTokenValue());break;case 42:if(Be===0){Be=1,N+=1;break}default:Be!==3&&(Be=2),hn(t.getTokenText());break}Be===2||Be===3?cn=_n(Be===3):cn=ze()}Vi(ne);let tn=ne.join("").trimEnd();if(re.length)return tn.length&&re.push(D(y.createJSDocText(tn),Oe??$)),Dt(re,$,t.getTokenEnd());if(tn.length)return tn}function c(N){let X=le(T);if(!X)return;ze(),wn();let $=d(),ne=[];for(;u()!==20&&u()!==4&&u()!==1;)ne.push(t.getTokenText()),ze();let re=X==="link"?y.createJSDocLink:X==="linkcode"?y.createJSDocLinkCode:y.createJSDocLinkPlain;return D(re($,ne.join("")),N,t.getTokenEnd())}function d(){if(kt(u())){let N=O(),X=Ut();for(;Je(25);)X=D(y.createQualifiedName(X,u()===81?Yt(80,!1):Ut()),N);for(;u()===81;)It(),ze(),X=D(y.createJSDocMemberName(X,vt()),N);return X}}function T(){if(J(),u()===19&&ze()===60&&kt(ze())){let N=t.getTokenValue();if(F(N))return N}}function F(N){return N==="link"||N==="linkcode"||N==="linkplain"}function fe(N,X,$,ne){return D(y.createJSDocUnknownTag(X,i(N,O(),$,ne)),N)}function We(N){N&&(Ne?Ne.push(N):(Ne=[N],Xt=N.pos),Ot=N.end)}function Mt(){return J(),u()===19?m():void 0}function hr(){let N=Yi(23);N&&wn();let X=Yi(62),$=my();return X&&Hl(62),N&&(wn(),ft(64)&&At(),j(24)),{name:$,isBracketed:N}}function kn(N){switch(N.kind){case 151:return!0;case 189:return kn(N.elementType);default:return Lf(N)&&et(N.typeName)&&N.typeName.escapedText==="Object"&&!N.typeArguments}}function Wi(N,X,$,ne){let re=Mt(),Oe=!re;J();let{name:Be,isBracketed:pt}=hr(),hn=J();Oe&&!H(T)&&(re=Mt());let cn=i(N,O(),ne,hn),tn=H0(re,Be,$,ne);tn&&(re=tn,Oe=!0);let Zn=$===1?y.createJSDocPropertyTag(X,Be,pt,re,Oe,cn):y.createJSDocParameterTag(X,Be,pt,re,Oe,cn);return D(Zn,N)}function H0(N,X,$,ne){if(N&&kn(N.type)){let re=O(),Oe,Be;for(;Oe=le(()=>Tp($,ne,X));)Oe.kind===342||Oe.kind===349?Be=An(Be,Oe):Oe.kind===346&&un(Oe.tagName,E.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag);if(Be){let pt=D(y.createJSDocTypeLiteral(Be,N.type.kind===189),re);return D(y.createJSDocTypeExpression(pt),re)}}}function X0(N,X,$,ne){nn(Ne,Cv)&&at(X.pos,t.getTokenStart(),E._0_tag_already_specified,h_(X.escapedText));let re=Mt();return D(y.createJSDocReturnTag(X,re,i(N,O(),$,ne)),N)}function gd(N,X,$,ne){nn(Ne,Xf)&&at(X.pos,t.getTokenStart(),E._0_tag_already_specified,h_(X.escapedText));let re=m(!0),Oe=$!==void 0&&ne!==void 0?i(N,O(),$,ne):void 0;return D(y.createJSDocTypeTag(X,re,Oe),N)}functLine truncated
`&&f[s-1]==="\r"?s-1:s}getNamedDeclarations(){return this.namedDeclarations||(this.namedDeclarations=this.computeNamedDeclarations()),this.namedDeclarations}computeNamedDeclarations(){let e=Ly();return this.forEachChild(f),e;function t(h){let b=s(h);b&&e.add(b,h)}function a(h){let b=e.get(h);return b||e.set(h,b=[]),b}function s(h){let b=mf(h);return b&&(Nf(b)&&gr(b.expression)?b.expression.name.text:c1(b)?getNameFromPropertyName(b):void 0)}function f(h){switch(h.kind){case 263:case 219:case 175:case 174:let b=h,v=s(b);if(v){let y=a(v),W=Va(y);W&&b.parent===W.parent&&b.symbol===W.symbol?b.body&&!W.body&&(y[y.length-1]=b):y.push(b)}$t(h,f);break;case 264:case 232:case 265:case 266:case 267:case 268:case 272:case 282:case 277:case 274:case 275:case 178:case 179:case 188:t(h),$t(h,f);break;case 170:if(!E_(h,31))break;case 261:case 209:{let y=h;if(s2(y.name)){$t(y.name,f);break}y.initializer&&f(y.initializer)}case 307:case 173:case 172:t(h);break;case 279:let l=h;l.exportClause&&(nh(l.exportClause)?Bn(l.exportClause.elements,f):f(l.exportClause.name));break;case 273:let G=h.importClause;G&&(G.name&&t(G.name),G.namedBindings&&(G.namedBindings.kind===275?t(G.namedBindings):Bn(G.namedBindings.elements,f)));break;case 227:Sf(h)!==0&&t(h);default:$t(h,f)}}}},m6=class{constructor(e,t,a){this.fileName=e,this.text=t,this.skipTrivia=a||(s=>s)}getLineAndCharacterOfPosition(e){return Ym(this,e)}};function h6(){return{getNodeConstructor:()=>Kf,getTokenConstructor:()=>vh,getIdentifierConstructor:()=>xh,getPrivateIdentifierConstructor:()=>Th,getSourceFileConstructor:()=>d6,getSymbolConstructor:()=>u6,getTypeConstructor:()=>p6,getSignatureConstructor:()=>f6,getSourceMapSourceConstructor:()=>m6}}var y6=["getSemanticDiagnostics","getSuggestionDiagnostics","getCompilerOptionsDiagnostics","getSemanticClassifications","getEncodedSemanticClassifications","getCodeFixesAtPosition","getCombinedCodeFix","applyCodeActionCommand","organizeImports","getEditsForFileRename","getEmitOutput","getApplicableRefactors","getEditsForRefactor","prepareCallHierarchy","provideCallHierarchyIncomingCalls","provideCallHierarchyOutgoingCalls","provideInlayHints","getSupportedCodeFixes","getPasteEdits"],rx=[...y6,"getCompletionsAtPosition","getCompletionEntryDetails","getCompletionEntrySymbol","getSignatureHelpItems","getQuickInfoAtPosition","getDefinitionAtPosition","getDefinitionAndBoundSpan","getImplementationAtPosition","getTypeDefinitionAtPosition","getReferencesAtPosition","findReferences","getDocumentHighlights","getNavigateToItems","getRenameInfo","findRenameLocations","getApplicableRefactors","preparePasteEditsForFile"];Tb(h6());var ts=new Proxy({},{get:()=>!0});var kh=ts["4.8"];function rr(e,t=!1){if(e!=null){if(kh){if(t||Rl(e)){let a=r1(e);return a?[...a]:void 0}return}return e.modifiers?.filter(a=>!Ka(a))}}function wi(e,t=!1){if(e!=null){if(kh){if(t||Qf(e)){let a=hf(e);return a?[...a]:void 0}return}return e.decorators?.filter(Ka)}}var Eh={};var Ul=new Proxy({},{get:(e,t)=>t});var Ah=Ul,Ch=Ul;var A=Ah,Bt=Ch;var v6=ts["5.0"],ye=Ae,x6=new Set([ye.AmpersandAmpersandToken,ye.BarBarToken,ye.QuestionQuestionToken]),T6=new Set([Ae.AmpersandAmpersandEqualsToken,Ae.AmpersandEqualsToken,Ae.AsteriskAsteriskEqualsToken,Ae.AsteriskEqualsToken,Ae.BarBarEqualsToken,Ae.BarEqualsToken,Ae.CaretEqualsToken,Ae.EqualsToken,Ae.GreaterThanGreaterThanEqualsToken,Ae.GreaterThanGreaterThanGreaterThanEqualsToken,Ae.LessThanLessThanEqualsToken,Ae.MinusEqualsToken,Ae.PercentEqualsToken,Ae.PlusEqualsToken,Ae.QuestionQuestionEqualsToken,Ae.SlashEqualsToken]),S6=new Set([ye.AmpersandAmpersandToken,ye.AmpersandToken,ye.AsteriskAsteriskToken,ye.AsteriskToken,ye.BarBarToken,ye.BarToken,ye.CaretToken,ye.EqualsEqualsEqualsToken,ye.EqualsEqualsToken,ye.ExclamationEqualsEqualsToken,ye.ExclamationEqualsToken,ye.GreaterThanEqualsToken,ye.GreaterThanGreaterThanGreaterThanToken,ye.GreaterThanGreaterThanToken,ye.GreaterThanToken,ye.InKeyword,ye.InstanceOfKeyword,ye.LessThanEqualsToken,ye.LessThanLessThanToken,ye.LessThanToken,ye.MinusToken,ye.PercentToken,ye.PlusToken,ye.SlashToken]);function w6(e){return T6.has(e.kind)}function k6(e){return x6.has(e.kind)}function E6(e){return S6.has(e.kind)}function qn(e){return rt(e)}function Dh(e){return e.kind!==ye.SemicolonClassElement}function Fe(e,t){return rr(t)?.some(s=>s.kind===e)===!0}function Ph(e){let t=rr(e);return t==null?null:t[t.length-1]??null}function Nh(e){return e.kind===ye.CommaToken}function A6(e){return e.kind===ye.SingleLineCommentTrivia||e.kind===ye.MultiLineCommentTrivia}function C6(e){return e.kind===ye.JSDocComment}function Ih(e){if(w6(e))return{type:A.AssignmentExpression,operator:qn(e.kind)};if(k6(e))return{type:A.LogicalExpression,operator:qn(e.kind)};if(E6(e))return{type:A.BinaryExpression,operator:qn(e.kind)};throw new Error(`Unexpected binary operator ${rt(e.kind)}`)}function C_(e,t){let a=t.getLineAndCharacterOfPosition(e);return{column:a.character,line:a.line+1}}function Zr(e,t){let[a,s]=e.map(f=>C_(f,t));return{end:Line truncated
`))return[];let t=[];for(let a of`*${e.value}*`.split(`
`)){if(a=a.trimStart(),!a.startsWith("*"))return[];t.push(a)}return t}var v0=new WeakMap;function H4(e){return is(v0,e,Y4)}function x0(e){v0.delete(e)}function fd(e){return H4(e).length>0}function T0(e){if(e.length<2)return;let t;for(let a=e.length-1;a>=0;a--){let s=e[a];if(t&&Kt(s)===Qt(t)&&fd(s)&&fd(t)&&(e.splice(a+1,1),s.value+="*//*"+t.value,s.range=[Qt(s),Kt(t)],x0(s)),!h0(s)&&!rs(s))throw new TypeError(`Unknown comment type: "${s.type}".`);t=s}}function X4(e){return e!==null&&typeof e=="object"}var S0=X4;var I_=null;function O_(e){if(I_!==null&&typeof I_.property){let t=I_;return I_=O_.prototype=null,t}return I_=O_.prototype=e??Object.create(null),new O_}var $4=10;for(let e=0;e<=$4;e++)O_();function dd(e){return O_(e)}function Q4(e,t="type"){dd(e);function a(s){let f=s[t],h=e[f];if(!Array.isArray(h))throw Object.assign(new Error(`Missing visitor keys for '${f}'.`),{node:s});return h}return a}var w0=Q4;var M=[["elements"],["left","right"],["value"],["directives","body"],["label"],["callee","typeArguments","arguments"],["test","consequent","alternate"],["body","test"],["expression"],["left","right","body"],["id","typeParameters","params","predicate","returnType","body"],["object","property"],["properties"],["decorators","key","typeParameters","params","returnType","body"],["decorators","key","value"],["argument"],["expressions"],["id","init"],["body"],["decorators","id","typeParameters","superClass","superTypeArguments","mixins","implements","body"],["declaration","specifiers","source","attributes"],["local"],["exported"],["decorators","variance","key","typeAnnotation","value"],["id"],["key","value"],["elementType"],["id","typeParameters"],["id","typeParameters","extends","body"],["id","body"],["typeAnnotation"],["id","typeParameters","right"],["name","typeAnnotation"],["types"],["qualification","id"],["elementTypes"],["expression","typeAnnotation"],["params"],["members"],["objectType","indexType"],["decorators","key","typeAnnotation","value"],["id","typeParameters","params","returnType","body"],["key","typeParameters","params","returnType"],["typeParameters","params","returnType"],["parameterName","typeAnnotation"],["checkType","extendsType","trueType","falseType"],["typeParameter"],["literal"],["expression","typeArguments"],["decorators","key","typeAnnotation"],["argument","cases"],["pattern","body","guard"],["properties","rest"],["node"]],k0={ArrayExpression:M[0],AssignmentExpression:M[1],BinaryExpression:M[1],InterpreterDirective:[],Directive:M[2],DirectiveLiteral:[],BlockStatement:M[3],BreakStatement:M[4],CallExpression:M[5],CatchClause:["param","body"],ConditionalExpression:M[6],ContinueStatement:M[4],DebuggerStatement:[],DoWhileStatement:M[7],EmptyStatement:[],ExpressionStatement:M[8],File:["program"],ForInStatement:M[9],ForStatement:["init","test","update","body"],FunctionDeclaration:M[10],FunctionExpression:M[10],Identifier:["typeAnnotation","decorators"],IfStatement:M[6],LabeledStatement:["label","body"],StringLiteral:[],NumericLiteral:[],NullLiteral:[],BooleanLiteral:[],RegExpLiteral:[],LogicalExpression:M[1],MemberExpression:M[11],NewExpression:M[5],Program:M[3],ObjectExpression:M[12],ObjectMethod:M[13],ObjectProperty:M[14],RestElement:["argument","typeAnnotation","decorators"],ReturnStatement:M[15],SequenceExpression:M[16],ParenthesizedExpression:M[8],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],ThisExpression:[],ThrowStatement:M[15],TryStatement:["block","handler","finalizer"],UnaryExpression:M[15],UpdateExpression:M[15],VariableDeclaration:["declarations"],VariableDeclarator:M[17],WhileStatement:M[7],WithStatement:["object","body"],AssignmentPattern:["left","right","decorators","typeAnnotation"],ArrayPattern:["elements","typeAnnotation","decorators"],ArrowFunctionExpression:["typeParameters","params","predicate","returnType","body"],ClassBody:M[18],ClassExpression:M[19],ClassDeclaration:M[19],ExportAllDeclaration:["source","attributes","exported"],ExportDefaultDeclaration:["declaration"],ExportNamedDeclaration:M[20],ExportSpecifier:["local","exported"],ForOfStatement:M[9],ImportDeclaration:["specifiers","source","attributes"],ImportDefaultSpecifier:M[21],ImportNamespaceSpecifier:M[21],ImportSpecifier:["imported","local"],MetaProperty:["meta","property"],ClassMethod:M[13],ObjectPattern:["decorators","properties","typeAnnotation"],SpreadElement:M[15],Super:[],TaggedTemplateExpression:["tag","typeArguments","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],YieldExpression:M[15],AwaitExpression:M[15],ImportExpression:["source","options"],BigIntLiteral:[],ExportNamespaceSpecifier:M[22],OptionalMemberExpression:M[11],OptionalCallExpression:M[5],ClassProperty:M[23],ClassPrivateProperty:M[23],ClassPrivateMethod:M[13],PrivateName:M[24],StaticBlock:M[18],ImportAttribute:M[25],AnyTypeAnnotation:[],ArrayTypeAnnotation:M[26],BooleanTypeAnnotation:[],BooleanLiteralTypeAnnotation:[],NullLiteralTypeAnnotation:[],ClassImplements:M[27],DeclareClass:["id","tyLine truncated
$1 $2
`);e=e.replace(P0,"").trimEnd();let s=Object.create(null),f=yr(0,e,N0,"").replace(P0,"").trimEnd(),h;for(;h=N0.exec(e);){let b=yr(0,h[2],a3,"");if(typeof s[h[1]]=="string"||Array.isArray(s[h[1]])){let v=s[h[1]];s[h[1]]=[...o3,...Array.isArray(v)?v:[v],b]}else s[h[1]]=b}return{comments:f,pragmas:s}}var M0=["noformat","noprettier"],L0=["format","prettier"];function c3(e){if(!e.startsWith("#!"))return"";let t=e.indexOf(`
`);return t===-1?e:e.slice(0,t)}var j0=c3;function J0(e){let t=j0(e);t&&(e=e.slice(t.length+1));let a=I0(e),{pragmas:s,comments:f}=O0(a);return{shebang:t,text:e,pragmas:s,comments:f}}function R0(e){let{pragmas:t}=J0(e);return L0.some(a=>hd(t,a))}function U0(e){let{pragmas:t}=J0(e);return M0.some(a=>hd(t,a))}function l3(e){return e=typeof e=="function"?{parse:e}:e,{astFormat:"estree",hasPragma:R0,hasIgnorePragma:U0,locStart:Qt,locEnd:Kt,...e}}var B0=l3;var q0=/^[^"'`]*<\/|^[^/]{2}.*\/>/m;function u3(e){return e.charAt(0)==="#"&&e.charAt(1)==="!"?"//"+e.slice(2):e}var F0=u3;var z0="module",V0="commonjs",W0=[z0,V0];function G0(e){if(typeof e=="string"){if(e=e.toLowerCase(),/\.(?:mjs|mts)$/i.test(e))return z0;if(/\.(?:cjs|cts)$/i.test(e))return V0}}var p3={loc:!0,range:!0,comment:!0,tokens:!1,loggerFn:!1,project:!1,jsDocParsingMode:"none",suppressDeprecatedPropertyWarnings:!0,onUnsupportedTypeScriptVersion:"ignore"};function f3(e){let{message:t,location:a}=e;if(!a)return e;let{start:s,end:f}=a;return l0(t,{loc:{start:{line:s.line,column:s.column+1},end:{line:f.line,column:f.column+1}},cause:e})}var d3=e=>e&&/\.(?:js|mjs|cjs|jsx|ts|mts|cts|tsx)$/i.test(e);function m3(e,t){let a=[{...p3,filePath:t}],s=G0(t);if(s?a=a.map(h=>({...h,sourceType:s})):a=W0.flatMap(h=>a.map(b=>({...b,sourceType:h}))),d3(t))return a;let f=q0.test(e);return[f,!f].flatMap(h=>a.map(b=>({...b,jsx:h})))}function h3(e,t){let a=t?.filepath;typeof a!="string"&&(a=void 0);let s=F0(e),f=m3(e,a),h;try{h=u0(f.map(b=>()=>c0(s,b)))}catch({errors:[b]}){throw f3(b)}return D0(h,{text:e,astType:"typescript"})}var y3=B0(h3);export{Y0 as default,yd as parsers};
@@ -0,0 +1 @@
{"version":3,"names":["_checkPrivateRedeclaration","require","_classPrivateMethodInitSpec","obj","privateSet","checkPrivateRedeclaration","add"],"sources":["../../src/helpers/classPrivateMethodInitSpec.ts"],"sourcesContent":["/* @minVersion 7.14.1 */\n\nimport checkPrivateRedeclaration from \"./checkPrivateRedeclaration.ts\";\n\nexport default function _classPrivateMethodInitSpec(\n obj: object,\n privateSet: WeakSet<object>,\n) {\n checkPrivateRedeclaration(obj, privateSet);\n privateSet.add(obj);\n}\n"],"mappings":";;;;;;AAEA,IAAAA,0BAAA,GAAAC,OAAA;AAEe,SAASC,2BAA2BA,CACjDC,GAAW,EACXC,UAA2B,EAC3B;EACA,IAAAC,kCAAyB,EAACF,GAAG,EAAEC,UAAU,CAAC;EAC1CA,UAAU,CAACE,GAAG,CAACH,GAAG,CAAC;AACrB","ignoreList":[]}
@@ -0,0 +1 @@
module.exports={C:{"112":0.00505,"115":0.09081,"120":0.50955,"121":1.01909,"123":0.00505,"124":0.00505,"127":0.00505,"136":0.00505,"140":0.01514,"144":0.00505,"146":0.00505,"147":0.00505,"149":0.00505,"150":0.01009,"151":0.00505,"152":0.01009,"153":0.01514,"154":0.05045,"155":0.16144,"156":0.33297,"157":0.01009,_:"2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 113 114 116 117 118 119 122 125 126 128 129 130 131 132 133 134 135 137 138 139 141 142 143 145 148 158 159 160 3.5 3.6"},D:{"56":0.00505,"62":0.00505,"65":0.00505,"66":0.00505,"68":0.01514,"69":0.02018,"70":0.00505,"71":0.00505,"72":0.01009,"73":0.01514,"74":0.00505,"75":0.00505,"76":0.00505,"77":0.00505,"79":0.00505,"80":0.00505,"81":0.00505,"83":0.01009,"86":0.01514,"87":0.00505,"88":0.00505,"89":0.00505,"91":0.00505,"92":0.00505,"93":0.06054,"95":0.01009,"96":0.00505,"98":0.00505,"101":0.03027,"102":0.06559,"103":0.3027,"104":0.10595,"105":0.11099,"106":0.11604,"107":0.11099,"108":0.11604,"109":1.70017,"110":0.10595,"111":0.19171,"112":0.11099,"113":0.00505,"114":0.02523,"116":0.24216,"117":0.10595,"118":0.68612,"119":1.05441,"120":1.14017,"121":0.01009,"122":0.02523,"123":0.01009,"124":0.12108,"125":0.01009,"126":0.08577,"127":0.01514,"128":0.03027,"129":0.01009,"130":0.03027,"131":0.24721,"132":0.03532,"133":0.23712,"134":0.03027,"135":0.03532,"136":0.04541,"137":0.08072,"138":0.16144,"139":0.0555,"140":0.06054,"141":0.04541,"142":0.09586,"143":0.04036,"144":0.19171,"145":0.07063,"146":0.42883,"147":0.07063,"148":0.14631,"149":0.31784,"150":0.53477,"151":1.77584,"152":7.7239,"153":16.77967,"154":3.72321,"155":0.07063,"156":0.01009,_:"4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 57 58 59 60 61 63 64 67 78 84 85 90 94 97 99 100 115 157"},F:{"36":0.00505,"56":0.00505,"95":0.03532,"101":0.01009,"102":0.00505,"106":0.00505,"133":0.00505,"134":0.02523,"135":0.49441,_:"9 11 12 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 57 58 60 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 96 97 98 99 100 103 104 105 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 131 132 9.5-9.6 10.0-10.1 10.5 10.6 11.1 11.5 11.6 12.1"},B:{"16":0.00505,"18":0.00505,"92":0.02523,"109":0.01514,"114":0.01009,"119":0.5045,"120":0.50955,"122":0.00505,"138":0.00505,"140":0.01009,"141":0.01009,"142":0.01009,"143":0.01009,"144":0.00505,"145":0.01009,"146":0.01009,"147":0.01009,"148":0.01514,"149":0.01514,"150":0.04541,"151":0.07063,"152":0.4591,"153":1.91206,"154":0.62558,_:"12 13 14 15 17 79 80 81 83 84 85 86 87 88 89 90 91 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 110 111 112 113 115 116 117 118 121 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 139"},E:{"27":0.04541,_:"4 5 6 7 8 9 10 11 12 13 14 15 3.1 3.2 5.1 6.1 7.1 9.1 10.1 11.1 12.1 13.1 15.1 15.2-15.3 15.4 15.5 16.0 16.2 16.5 17.0 27.1 27.2 TP","14.1":0.00505,"15.6":0.05045,"16.1":0.01009,"16.3":0.01009,"16.4":0.00505,"16.6":0.03027,"17.1":0.02018,"17.2":0.00505,"17.3":0.00505,"17.4":0.00505,"17.5":0.01009,"17.6":0.04541,"18.0":0.00505,"18.1":0.00505,"18.2":0.00505,"18.3":0.01009,"18.4":0.00505,"18.5-18.7":0.01009,"26.0":0.01009,"26.1":0.00505,"26.2":0.01514,"26.3":0.02018,"26.4":0.01514,"26.5":0.07568,"26.6":0.21189},G:{"8":0,"3.2":0,"4.0-4.1":0,"4.2-4.3":0.00041,"5.0-5.1":0.00041,"6.0-6.1":0,"7.0-7.1":0.00081,"8.1-8.4":0,"9.0-9.2":0,"9.3":0,"10.0-10.2":0,"10.3":0.00406,"11.0-11.2":0.00041,"11.3-11.4":0.00081,"12.0-12.1":0,"12.2-12.5":0.01056,"13.0-13.1":0,"13.2":0.00203,"13.3":0,"13.4-13.7":0.00041,"14.0-14.4":0.00163,"14.5-14.8":0.00244,"15.0-15.1":0.00244,"15.2-15.3":0.00163,"15.4":0.00203,"15.5":0.00244,"15.6-15.8":0.05282,"16.0":0.00406,"16.1":0.00731,"16.2":0.00406,"16.3":0.00894,"16.4":0.00203,"16.5":0.00325,"16.6-16.7":0.07354,"17.0":0.00284,"17.1":0.00406,"17.2":0.00406,"17.3":0.00609,"17.4":0.00853,"17.5":0.01666,"17.6-17.7":0.04307,"18.0":0.00894,"18.1":0.01788,"18.2":0.02438,"18.3":0.04226,"18.4":0.02641,"18.5-18.7":0.54567,"26.0":0.02641,"26.1":0.02682,"26.2":0.06989,"26.3":0.07557,"26.4":0.05526,"26.5":0.37015,"26.6":2.28387,"27.0":0.17512,"27.1":0,"27.2":0.00447},P:{"4":0.05507,"22":0.00918,"23":0.00918,"24":0.00918,"25":0.01836,"26":0.03671,"27":0.00918,"28":0.05507,"29":0.08261,"30":1.04634,_:"20 21 5.0-5.4 6.2-6.4 9.2 10.1 11.1-11.2 12.0 13.0 14.0 15.0 16.0 18.0 19.0","7.2-7.4":0.01836,"8.2":0.00918,"17.0":0.00918},I:{"0":0.01485,"3":0,"4":0,"2.1":0,"2.2":0,"2.3":0,"4.1":0,"4.2-4.3":0,"4.4":0,"4.4.3-4.4.4":0.00001},K:{"0":0.93154,_:"10 11 1Line truncated
@@ -0,0 +1,29 @@
import { expect, test } from "vitest";
import * as z from "zod/v4";
test("Georgian locale uses 'ველი' instead of 'სტრინგი'", () => {
// Save original error map to restore later if needed, though tests are usually isolated or we can reset
// const originalErrorMap = z.getErrorMap(); // z.getErrorMap might not exist, but let's assume isolation or just set it
z.setErrorMap(z.locales.ka().localeError);
// Test 1: Invalid type (Expected string, received number)
const stringSchema = z.string();
const numberResult = stringSchema.safeParse(123);
expect(numberResult.success).toBe(false);
if (!numberResult.success) {
// Expected: "არასწორი შეყვანა: მოსალოდნელი ველი, მიღებული რიცხვი"
expect(numberResult.error.issues[0].message).toBe("არასწორი შეყვანა: მოსალოდნელი ველი, მიღებული რიცხვი");
}
// Test 2: Invalid base64
const base64Schema = z.string().base64();
const base64Result = base64Schema.safeParse("not base64!");
expect(base64Result.success).toBe(false);
if (!base64Result.success) {
// Expected: "არასწორი base64-კოდირებული ველი"
// "არასწორი ${FormatDictionary[_issue.format] ?? issue.format}"
// FormatDictionary['base64'] is "base64-კოდირებული ველი"
expect(base64Result.error.issues[0].message).toBe("არასწორი base64-კოდირებული ველი");
}
});
@@ -0,0 +1 @@
{"version":3,"file":"alert-triangle.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;"}
@@ -0,0 +1,75 @@
/**
* Creates a deep copy of a process coverage.
*
* @param processCov Process coverage to clone.
* @return Cloned process coverage.
*/
function cloneProcessCov(processCov) {
const result = [];
for (const scriptCov of processCov.result) {
result.push(cloneScriptCov(scriptCov));
}
return {
result,
};
}
/**
* Creates a deep copy of a script coverage.
*
* @param scriptCov Script coverage to clone.
* @return Cloned script coverage.
*/
function cloneScriptCov(scriptCov) {
const functions = [];
for (const functionCov of scriptCov.functions) {
functions.push(cloneFunctionCov(functionCov));
}
return {
scriptId: scriptCov.scriptId,
url: scriptCov.url,
functions,
};
}
/**
* Creates a deep copy of a function coverage.
*
* @param functionCov Function coverage to clone.
* @return Cloned function coverage.
*/
function cloneFunctionCov(functionCov) {
const ranges = [];
for (const rangeCov of functionCov.ranges) {
ranges.push(cloneRangeCov(rangeCov));
}
return {
functionName: functionCov.functionName,
ranges,
isBlockCoverage: functionCov.isBlockCoverage,
};
}
/**
* Creates a deep copy of a function coverage.
*
* @param rangeCov Range coverage to clone.
* @return Cloned range coverage.
*/
function cloneRangeCov(rangeCov) {
return {
startOffset: rangeCov.startOffset,
endOffset: rangeCov.endOffset,
count: rangeCov.count,
};
}
module.exports = {
cloneProcessCov,
cloneScriptCov,
cloneFunctionCov,
cloneRangeCov,
};
@@ -0,0 +1 @@
{"version":3,"names":["auxiliaryComment","message","blacklist","breakConfig","experimental","externalHelpers","extra","jsxPragma","loose","metadataUsedHelpers","modules","nonStandard","optional","sourceMapName","stage","whitelist","resolveModuleSource","version","metadata","sourceMapTarget"],"sources":["../../../src/config/validation/removed.ts"],"sourcesContent":["export default {\n auxiliaryComment: {\n message: \"Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`\",\n },\n blacklist: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n breakConfig: {\n message: \"This is not a necessary option in Babel 6\",\n },\n experimental: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n externalHelpers: {\n message:\n \"Use the `external-helpers` plugin instead. \" +\n \"Check out http://babeljs.io/docs/plugins/external-helpers/\",\n },\n extra: {\n message: \"\",\n },\n jsxPragma: {\n message:\n \"use the `pragma` option in the `react-jsx` plugin. \" +\n \"Check out http://babeljs.io/docs/plugins/transform-react-jsx/\",\n },\n loose: {\n message:\n \"Specify the `loose` option for the relevant plugin you are using \" +\n \"or use a preset that sets the option.\",\n },\n metadataUsedHelpers: {\n message: \"Not required anymore as this is enabled by default\",\n },\n modules: {\n message:\n \"Use the corresponding module transform plugin in the `plugins` option. \" +\n \"Check out http://babeljs.io/docs/plugins/#modules\",\n },\n nonStandard: {\n message:\n \"Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. \" +\n \"Also check out the react preset http://babeljs.io/docs/plugins/preset-react/\",\n },\n optional: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n sourceMapName: {\n message:\n \"The `sourceMapName` option has been removed because it makes more sense for the \" +\n \"tooling that calls Babel to assign `map.file` themselves.\",\n },\n stage: {\n message:\n \"Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets\",\n },\n whitelist: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n\n resolveModuleSource: {\n version: 6,\n message: \"Use `babel-plugin-module-resolver@3`'s 'resolvePath' options\",\n },\n metadata: {\n version: 6,\n message:\n \"Generated plugin metadata is always included in the output result\",\n },\n sourceMapTarget: {\n version: 6,\n message:\n \"The `sourceMapTarget` option has been removed because it makes more sense for the tooling \" +\n \"that calls Babel to assign `map.file` themselves.\",\n },\n} as Record<string, { version?: number; message: string }>;\n"],"mappings":";;;;;;iCAAe;EACbA,gBAAgB,EAAE;IAChBC,OAAO,EAAE;EACX,CAAC;EACDC,SAAS,EAAE;IACTD,OAAO,EAAE;EACX,CAAC;EACDE,WAAW,EAAE;IACXF,OAAO,EAAE;EACX,CAAC;EACDG,YAAY,EAAE;IACZH,OAAO,EAAE;EACX,CAAC;EACDI,eAAe,EAAE;IACfJ,OAAO,EACL,6CAA6C,GAC7C;EACJ,CAAC;EACDK,KAAK,EAAE;IACLL,OAAO,EAAE;EACX,CAAC;EACDM,SAAS,EAAE;IACTN,OAAO,EACL,qDAAqD,GACrD;EACJ,CAAC;EACDO,KAAK,EAAE;IACLP,OAAO,EACL,mEAAmE,GACnE;EACJ,CAAC;EACDQ,mBAAmB,EAAE;IACnBR,OAAO,EAAE;EACX,CAAC;EACDS,OAAO,EAAE;IACPT,OAAO,EACL,yEAAyE,GACzE;EACJ,CAAC;EACDU,WAAW,EAAE;IACXV,OAAO,EACL,8EAA8E,GAC9E;EACJ,CAAC;EACDW,QAAQ,EAAE;IACRX,OAAO,EAAE;EACX,CAAC;EACDY,aAAa,EAAE;IACbZ,OAAO,EACL,kFAAkF,GAClF;EACJ,CAAC;EACDa,KAAK,EAAE;IACLb,OAAO,EACL;EACJ,CAAC;EACDc,SAAS,EAAE;IACTd,OAAO,EAAE;EACX,CAAC;EAEDe,mBAAmB,EAAE;IACnBC,OAAO,EAAE,CAAC;IACVhB,OAAO,EAAE;EACX,CAAC;EACDiB,QAAQ,EAAE;IACRD,OAAO,EAAE,CAAC;IACVhB,OAAO,EACL;EACJ,CAAC;EACDkB,eAAe,EAAE;IACfF,OAAO,EAAE,CAAC;IACVhB,OAAO,EACL,4FAA4F,GAC5F;EACJ;AACF,CAAC;AAAA","ignoreList":[]}
@@ -0,0 +1 @@
{"version":3,"file":"event-info.mjs","sources":["../../../src/events/event-info.ts"],"sourcesContent":["import { EventInfo, isPrimaryPointer } from \"motion-dom\"\n\nexport type EventListenerWithPointInfo = (\n e: PointerEvent,\n info: EventInfo\n) => void\n\nexport function extractEventInfo(event: PointerEvent): EventInfo {\n return {\n point: {\n x: event.pageX,\n y: event.pageY,\n },\n }\n}\n\nexport const addPointerInfo =\n (handler: EventListenerWithPointInfo): EventListener =>\n (event: PointerEvent) =>\n isPrimaryPointer(event) && handler(event, extractEventInfo(event))\n"],"names":[],"mappings":";;AAOM,SAAU,gBAAgB,CAAC,KAAmB,EAAA;IAChD,OAAO;AACH,QAAA,KAAK,EAAE;YACH,CAAC,EAAE,KAAK,CAAC,KAAK;YACd,CAAC,EAAE,KAAK,CAAC,KAAK;AACjB,SAAA;KACJ;AACL;AAEO,MAAM,cAAc,GACvB,CAAC,OAAmC,KACpC,CAAC,KAAmB,KAChB,gBAAgB,CAAC,KAAK,CAAC,IAAI,OAAO,CAAC,KAAK,EAAE,gBAAgB,CAAC,KAAK,CAAC;;;;"}
@@ -0,0 +1,19 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const IndianRupee = createLucideIcon("IndianRupee", [
["path", { d: "M6 3h12", key: "ggurg9" }],
["path", { d: "M6 8h12", key: "6g4wlu" }],
["path", { d: "m6 13 8.5 8", key: "u1kupk" }],
["path", { d: "M6 13h3", key: "wdp6ag" }],
["path", { d: "M9 13c6.667 0 6.667-10 0-10", key: "1nkvk2" }]
]);
export { IndianRupee as default };
//# sourceMappingURL=indian-rupee.js.map
@@ -0,0 +1,419 @@
import { a as cleanUrl, c as createManualModuleSource } from './chunk-utils.js';
import { a as automockModule, e as esmWalker } from './chunk-automock.js';
import MagicString from 'magic-string';
import { createFilter, isFileLoadingAllowed } from 'vite';
import { h as hoistMocks } from './chunk-hoistMocks.js';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path/posix';
import { s as slash } from './chunk-helpers.js';
import { M as MockerRegistry, a as ManualMockedModule } from './chunk-registry.js';
import { fileURLToPath } from 'node:url';
import { existsSync, readFileSync } from 'node:fs';
import { findMockRedirect } from './redirect.js';
import { i as isAbsolute, j as join$1, r as resolve } from './chunk-pathe.M-eThtNZ.js';
import 'estree-walker';
import 'node:module';
import 'node:path';
function automockPlugin(options = {}) {
return {
name: "vitest:automock",
enforce: "post",
transform(code, id) {
if (id.includes("mock=automock") || id.includes("mock=autospy")) {
const mockType = id.includes("mock=automock") ? "automock" : "autospy";
const ms = automockModule(code, mockType, this.parse, options);
return {
code: ms.toString(),
map: ms.generateMap({
hires: "boundary",
source: cleanUrl(id)
})
};
}
}
};
}
const regexDynamicImport = /import\s*\(/;
function dynamicImportPlugin(options = {}) {
return {
name: "vitest:browser:esm-injector",
enforce: "post",
transform(source, id) {
// TODO: test is not called for static imports
if (!regexDynamicImport.test(source)) {
return;
}
if (options.filter && !options.filter(id)) {
return;
}
return injectDynamicImport(source, id, this.parse, options);
}
};
}
function injectDynamicImport(code, id, parse, options = {}) {
if (code.includes("wrapDynamicImport")) {
return;
}
const s = new MagicString(code);
let ast;
try {
ast = parse(code);
} catch (err) {
console.error(`Cannot parse ${id}:\n${err.message}`);
return;
}
// 3. convert references to import bindings & import.meta references
esmWalker(ast, {
onImportMeta() {
// s.update(node.start, node.end, viImportMetaKey)
},
onDynamicImport(node) {
const globalThisAccessor = options.globalThisAccessor || "\"__vitest_mocker__\"";
const replaceString = `globalThis[${globalThisAccessor}].wrapDynamicImport(() => import(`;
const importSubstring = code.substring(node.start, node.end);
const hasIgnore = importSubstring.includes("/* @vite-ignore */");
s.overwrite(node.start, node.source.start, replaceString + (hasIgnore ? "/* @vite-ignore */ " : ""));
s.overwrite(node.end - 1, node.end, "))");
}
});
return {
code: s.toString(),
map: s.generateMap({
hires: "boundary",
source: id
})
};
}
function hoistMocksPlugin(options = {}) {
const filter = options.filter || createFilter(options.include, options.exclude);
const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [
"mock",
"unmock",
"doMock",
"doUnmock"
], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"] } = options;
const methods = new Set([
...hoistableMockMethodNames,
...hoistedMethodNames,
...dynamicImportMockMethodNames
]);
const regexpHoistable = new RegExp(`\\b(?:${utilsObjectNames.join("|")})\\s*\.\\s*(?:${Array.from(methods).join("|")})\\s*\\(`);
return {
name: "vitest:mocks",
enforce: "post",
transform(code, id) {
if (!filter(id)) {
return;
}
const s = hoistMocks(code, id, this.parse, {
regexpHoistable,
hoistableMockMethodNames,
hoistedMethodNames,
utilsObjectNames,
dynamicImportMockMethodNames,
...options
});
if (s) {
return {
code: s.toString(),
map: s.generateMap({
hires: "boundary",
source: cleanUrl(id)
})
};
}
}
};
}
// to keeb backwards compat
function hoistMockAndResolve(code, id, parse, options = {}) {
const s = hoistMocks(code, id, parse, options);
if (s) {
return {
code: s.toString(),
map: s.generateMap({
hires: "boundary",
source: cleanUrl(id)
})
};
}
}
function interceptorPlugin(options = {}) {
const registry = options.registry || new MockerRegistry();
return {
name: "vitest:mocks:interceptor",
enforce: "pre",
load: {
order: "pre",
async handler(id) {
const mock = registry.getById(id);
if (!mock) {
return;
}
if (mock.type === "manual") {
const exports$1 = Object.keys(await mock.resolve());
const accessor = options.globalThisAccessor || "\"__vitest_mocker__\"";
return createManualModuleSource(mock.url, exports$1, accessor);
}
if (mock.type === "redirect") {
return readFile(mock.redirect, "utf-8");
}
}
},
transform: {
order: "post",
handler(code, id) {
const mock = registry.getById(id);
if (!mock) {
return;
}
if (mock.type === "automock" || mock.type === "autospy") {
const m = automockModule(code, mock.type, this.parse, { globalThisAccessor: options.globalThisAccessor });
return {
code: m.toString(),
map: m.generateMap({
hires: "boundary",
source: cleanUrl(id)
})
};
}
}
},
configureServer(server) {
if (options.registerWebSocketEvents === false) {
return;
}
server.ws.on("vitest:interceptor:register", (event) => {
if (event.type === "manual") {
const module = ManualMockedModule.fromJSON(event, async () => {
const keys = await getFactoryExports(event.url);
return Object.fromEntries(keys.map((key) => [key, null]));
});
registry.add(module);
} else {
if (event.type === "redirect") {
const redirectUrl = new URL(event.redirect);
const redirect = join(server.config.root, slash(redirectUrl.pathname));
// the redirect is served through the `load` hook below, so it must
// stay inside the file-serving allowlist and never escape the root
if (!isFileLoadingAllowed(server.config, redirect)) {
server.ws.send("vitest:interceptor:register:result");
return;
}
event.redirect = redirect;
}
registry.register(event);
}
server.ws.send("vitest:interceptor:register:result");
});
server.ws.on("vitest:interceptor:delete", (id) => {
registry.delete(id);
server.ws.send("vitest:interceptor:delete:result");
});
server.ws.on("vitest:interceptor:invalidate", () => {
registry.clear();
server.ws.send("vitest:interceptor:invalidate:result");
});
function getFactoryExports(url) {
server.ws.send("vitest:interceptor:resolve", url);
let timeout;
return new Promise((resolve, reject) => {
timeout = setTimeout(() => {
reject(new Error(`Timeout while waiting for factory exports of ${url}`));
}, 1e4);
server.ws.on("vitest:interceptor:resolved", ({ url: resolvedUrl, keys }) => {
if (resolvedUrl === url) {
clearTimeout(timeout);
resolve(keys);
}
});
});
}
}
};
}
const VALID_ID_PREFIX = "/@id/";
class ServerMockResolver {
constructor(server, options = {}) {
this.server = server;
this.options = options;
}
async resolveMock(rawId, importer, options) {
const { id, fsPath, external } = await this.resolveMockId(rawId, importer);
const resolvedUrl = this.normalizeResolveIdToUrl({ id }).url;
if (options.mock === "factory") {
const manifest = getViteDepsManifest(this.server.config);
const needsInterop = manifest?.[fsPath]?.needsInterop ?? false;
return {
mockType: "manual",
resolvedId: id,
resolvedUrl,
needsInterop
};
}
if (options.mock === "spy") {
return {
mockType: "autospy",
resolvedId: id,
resolvedUrl
};
}
const redirectUrl = findMockRedirect(this.server.config.root, fsPath, external);
return {
mockType: redirectUrl === null ? "automock" : "redirect",
redirectUrl,
resolvedId: id,
resolvedUrl
};
}
invalidate(ids) {
ids.forEach((id) => {
const moduleGraph = this.server.moduleGraph;
const module = moduleGraph.getModuleById(id);
if (module) {
module.transformResult = null;
}
});
}
async resolveId(id, importer) {
const resolved = await this.server.pluginContainer.resolveId(id, importer, { ssr: false });
if (!resolved) {
return null;
}
return this.normalizeResolveIdToUrl(resolved);
}
normalizeResolveIdToUrl(resolved) {
const isOptimized = resolved.id.startsWith(withTrailingSlash(this.server.config.cacheDir));
let url;
// normalise the URL to be acceptable by the browser
// https://github.com/vitejs/vite/blob/14027b0f2a9b01c14815c38aab22baf5b29594bb/packages/vite/src/node/plugins/importAnalysis.ts#L103
const root = this.server.config.root;
if (resolved.id.startsWith(withTrailingSlash(root))) {
url = resolved.id.slice(root.length);
} else if (resolved.id !== "/@react-refresh" && isAbsolute(resolved.id) && existsSync(cleanUrl(resolved.id))) {
url = join$1("/@fs/", resolved.id);
} else {
url = resolved.id;
}
if (url[0] !== "." && url[0] !== "/") {
url = resolved.id.startsWith(VALID_ID_PREFIX) ? resolved.id : VALID_ID_PREFIX + resolved.id.replace("\0", "__x00__");
}
return {
id: resolved.id,
url,
optimized: isOptimized
};
}
async resolveMockId(rawId, importer) {
if (!this.server.moduleGraph.getModuleById(importer) && !importer.startsWith(this.server.config.root)) {
importer = join$1(this.server.config.root, importer);
}
const resolved = await this.server.pluginContainer.resolveId(rawId, importer, { ssr: false });
return this.resolveModule(rawId, resolved);
}
resolveModule(rawId, resolved) {
const id = resolved?.id || rawId;
const external = !isAbsolute(id) || isModuleDirectory(this.options, id) ? rawId : null;
return {
id,
fsPath: cleanUrl(id),
external
};
}
}
function isModuleDirectory(config, path) {
const moduleDirectories = config.moduleDirectories || ["/node_modules/"];
return moduleDirectories.some((dir) => path.includes(dir));
}
const metadata = new WeakMap();
function getViteDepsManifest(config) {
if (metadata.has(config)) {
return metadata.get(config);
}
const cacheDirPath = getDepsCacheDir(config);
const metadataPath = resolve(cacheDirPath, "_metadata.json");
if (!existsSync(metadataPath)) {
return null;
}
const { optimized } = JSON.parse(readFileSync(metadataPath, "utf-8"));
const newManifest = {};
for (const name in optimized) {
const dep = optimized[name];
const file = resolve(cacheDirPath, dep.file);
newManifest[file] = {
hash: dep.fileHash,
needsInterop: dep.needsInterop
};
}
metadata.set(config, newManifest);
return newManifest;
}
function getDepsCacheDir(config) {
return resolve(config.cacheDir, "deps");
}
function withTrailingSlash(path) {
if (path.at(-1) !== "/") {
return `${path}/`;
}
return path;
}
// this is an implementation for public usage
// vitest doesn't use this plugin directly
function mockerPlugin(options = {}) {
let server;
const registerPath = resolve(fileURLToPath(new URL("./register.js", import.meta.url)));
return [
{
name: "vitest:mocker:ws-rpc",
config(_, { command }) {
if (command !== "serve") {
return;
}
return {
server: { preTransformRequests: false },
optimizeDeps: { exclude: ["@vitest/mocker/register", "@vitest/mocker/browser"] }
};
},
configureServer(server_) {
server = server_;
const mockResolver = new ServerMockResolver(server);
server.ws.on("vitest:mocks:resolveId", async ({ id, importer }) => {
const resolved = await mockResolver.resolveId(id, importer);
server.ws.send("vitest:mocks:resolvedId:result", resolved);
});
server.ws.on("vitest:mocks:resolveMock", async ({ id, importer, options }) => {
const resolved = await mockResolver.resolveMock(id, importer, options);
server.ws.send("vitest:mocks:resolveMock:result", resolved);
});
server.ws.on("vitest:mocks:invalidate", async ({ ids }) => {
mockResolver.invalidate(ids);
server.ws.send("vitest:mocks:invalidate:result");
});
},
async load(id) {
if (id !== registerPath) {
return;
}
if (!server) {
// mocker doesn't work during build
return "export {}";
}
const content = await readFile(registerPath, "utf-8");
const result = content.replace(/__VITEST_GLOBAL_THIS_ACCESSOR__/g, options.globalThisAccessor ?? "\"__vitest_mocker__\"").replace("__VITEST_MOCKER_ROOT__", JSON.stringify(server.config.root));
return result;
}
},
hoistMocksPlugin(options.hoistMocks),
interceptorPlugin(options),
automockPlugin(options),
dynamicImportPlugin(options)
];
}
export { ServerMockResolver, automockModule, automockPlugin, createManualModuleSource, dynamicImportPlugin, findMockRedirect, hoistMockAndResolve as hoistMocks, hoistMocksPlugin, interceptorPlugin, mockerPlugin };
@@ -0,0 +1 @@
{"version":3,"file":"more-vertical.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;"}
@@ -0,0 +1 @@
{"version":3,"file":"scope.js","sourceRoot":"","sources":["../../../lib/compile/codegen/scope.ts"],"names":[],"mappings":";;;AAAA,iCAAyC;AAezC,MAAM,UAAW,SAAQ,KAAK;IAE5B,YAAY,IAAoB;QAC9B,KAAK,CAAC,uBAAuB,IAAI,cAAc,CAAC,CAAA;QAChD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAA;IACzB,CAAC;CACF;AAuBD,IAAY,cAGX;AAHD,WAAY,cAAc;IACxB,yDAAO,CAAA;IACP,6DAAS,CAAA;AACX,CAAC,EAHW,cAAc,8BAAd,cAAc,QAGzB;AAMY,QAAA,QAAQ,GAAG;IACtB,KAAK,EAAE,IAAI,WAAI,CAAC,OAAO,CAAC;IACxB,GAAG,EAAE,IAAI,WAAI,CAAC,KAAK,CAAC;IACpB,GAAG,EAAE,IAAI,WAAI,CAAC,KAAK,CAAC;CACrB,CAAA;AAED,MAAa,KAAK;IAKhB,YAAY,EAAC,QAAQ,EAAE,MAAM,KAAkB,EAAE;QAJ9B,WAAM,GAAqC,EAAE,CAAA;QAK9D,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAA;QACzB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAA;IACvB,CAAC;IAED,MAAM,CAAC,YAA2B;QAChC,OAAO,YAAY,YAAY,WAAI,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,CAAA;IAC9E,CAAC;IAED,IAAI,CAAC,MAAc;QACjB,OAAO,IAAI,WAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAA;IACxC,CAAC;IAES,QAAQ,CAAC,MAAc;QAC/B,MAAM,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAA;QACzD,OAAO,GAAG,MAAM,GAAG,EAAE,CAAC,KAAK,EAAE,EAAE,CAAA;IACjC,CAAC;IAEO,UAAU,CAAC,MAAc;;QAC/B,IAAI,CAAA,MAAA,MAAA,IAAI,CAAC,OAAO,0CAAE,SAAS,0CAAE,GAAG,CAAC,MAAM,CAAC,KAAI,CAAC,IAAI,CAAC,SAAS,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;YAC5F,MAAM,IAAI,KAAK,CAAC,oBAAoB,MAAM,gCAAgC,CAAC,CAAA;QAC7E,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAC,MAAM,EAAE,KAAK,EAAE,CAAC,EAAC,CAAC,CAAA;IACnD,CAAC;CACF;AA7BD,sBA6BC;AAOD,MAAa,cAAe,SAAQ,WAAI;IAKtC,YAAY,MAAc,EAAE,OAAe;QACzC,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;IAED,QAAQ,CAAC,KAAgB,EAAE,EAAC,QAAQ,EAAE,SAAS,EAAY;QACzD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;QAClB,IAAI,CAAC,SAAS,GAAG,IAAA,QAAC,EAAA,IAAI,IAAI,WAAI,CAAC,QAAQ,CAAC,IAAI,SAAS,GAAG,CAAA;IAC1D,CAAC;CACF;AAdD,wCAcC;AAMD,MAAM,IAAI,GAAG,IAAA,QAAC,EAAA,IAAI,CAAA;AAElB,MAAa,UAAW,SAAQ,KAAK;IAKnC,YAAY,IAAuB;QACjC,KAAK,CAAC,IAAI,CAAC,CAAA;QALM,YAAO,GAAgB,EAAE,CAAA;QAM1C,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAA;QACxB,IAAI,CAAC,IAAI,GAAG,EAAC,GAAG,IAAI,EAAE,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,UAAG,EAAC,CAAA;IACpD,CAAC;IAED,GAAG;QACD,OAAO,IAAI,CAAC,MAAM,CAAA;IACpB,CAAC;IAED,IAAI,CAAC,MAAc;QACjB,OAAO,IAAI,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAA;IAC1D,CAAC;IAED,KAAK,CAAC,YAAqC,EAAE,KAAgB;;QAC3D,IAAI,KAAK,CAAC,GAAG,KAAK,SAAS;YAAE,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAA;QACpF,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,YAAY,CAAmB,CAAA;QACxD,MAAM,EAAC,MAAM,EAAC,GAAG,IAAI,CAAA;QACrB,MAAM,QAAQ,GAAG,MAAA,KAAK,CAAC,GAAG,mCAAI,KAAK,CAAC,GAAG,CAAA;QACvC,IAAI,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA;QAC7B,IAAI,EAAE,EAAE,CAAC;YACP,MAAM,KAAK,GAAG,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAA;YAC9B,IAAI,KAAK;gBAAE,OAAO,KAAK,CAAA;QACzB,CAAC;aAAM,CAAC;YACN,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,IAAI,GAAG,EAAE,CAAA;QACvC,CAAC;QACD,EAAE,CAAC,GAAG,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;QAEtB,MAAM,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,CAAA;QAC3D,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,CAAA;QAC1B,CAAC,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,GAAG,CAAA;QACxB,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,EAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAC,CAAC,CAAA;QACnD,OAAO,IAAI,CAAA;IACb,CAAC;IAED,QAAQ,CAAC,MAAc,EAAE,QAAiB;QACxC,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA;QAC/B,IAAI,CAAC,EAAE;YAAE,OAAM;QACf,OAAO,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAA;IACzB,CAAC;IAED,SAAS,CAAC,SAAe,EAAE,SAAuC,IAAI,CAAC,OAAO;QAC5E,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,CAAC,IAAoB,EAAE,EAAE;YACzD,IAAI,IAAI,CAAC,SAAS,KAAK,SAAS;gBAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,IAAI,gBAAgB,CAAC,CAAA;YACzF,OAAO,IAAA,QAAC,EAAA,GAAG,SAAS,GAAG,IAAI,CAAC,SAAS,EAAE,CAAA;QACzC,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,SAAS,CACP,SAAuC,IAAI,CAAC,OAAO,EACnD,UAA4B,EAC5B,OAAiD;QAEjD,OAAO,IAAI,CAAC,aAAa,CACvB,MAAM,EACN,CAAC,IAAoB,EAAE,EAAE;YACvB,IAAI,IAAI,CAAC,KAAK,KAAK,SAAS;gBAAE,MAAM,IAAI,KAAK,CAAC,kBAAkB,IAAI,gBAAgB,CAAC,CAAA;YACrF,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAA;QACxB,CAAC,EACD,UAAU,EACV,OAAO,CACR,CAAA;IACH,CAAC;IAEO,aAAa,CACnB,MAAoC,EACpC,SAAkD,EAClD,aAA8B,EAAE,EAChC,OAAiD;QAEjD,IAAI,IAAI,GAAS,UAAG,CAAA;QACpB,KAAK,MAAM,MAAM,IAAI,MAAM,EAAE,CAAC;YAC5B,MAAM,EAAE,GAAG,MAAM,CAAC,MAAM,CAAC,CAAA;YACzB,IAAI,CAAC,EAAE;gBAAE,SAAQ;YACjB,MAAM,OAAO,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,GAAG,UAAU,CAAC,MAAM,CAAC,IAAI,IAAI,GAAG,EAAE,CAAC,CAAA;YACtE,EAAE,CAAC,OAAO,CAAC,CAAC,IAAoB,EAAE,EAAE;gBAClC,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC;oBAAE,OAAM;gBAC7B,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,OAAO,CAAC,CAAA;gBACzC,IAAI,CAAC,GAAG,SAAS,CAAC,IAAI,CAAC,CAAA;gBACvB,IAAI,CAAC,EAAE,CAAC;oBACN,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,gBAAQ,CAAC,KAAK,CAAA;oBACzD,IAAI,GAAG,IAAA,QAAC,EAAA,GAAG,IAAI,GAAG,GAAG,IAAI,IAAI,MAAM,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAA;gBACxD,CAAC;qBAAM,IAAI,CAAC,CAAC,GAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAG,IAAI,CAAC,CAAC,EAAE,CAAC;oBACjC,IAAI,GAAG,IAAA,QAAC,EAAA,GAAG,IAAI,GAAG,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAA;gBACtC,CAAC;qBAAM,CAAC;oBACN,MAAM,IAAI,UAALine truncated
@@ -0,0 +1,4 @@
var zr=Object.defineProperty;var Ur=(s,t)=>{for(var e in t)zr(s,e,{get:t[e],enumerable:!0})};import Qr from"events";import I from"fs";import{EventEmitter as Di}from"node:events";import Cs from"node:stream";import{StringDecoder as Hr}from"node:string_decoder";var Ds=typeof process=="object"&&process?process:{stdout:null,stderr:null},Wr=s=>!!s&&typeof s=="object"&&(s instanceof A||s instanceof Cs||Gr(s)||Zr(s)),Gr=s=>!!s&&typeof s=="object"&&s instanceof Di&&typeof s.pipe=="function"&&s.pipe!==Cs.Writable.prototype.pipe,Zr=s=>!!s&&typeof s=="object"&&s instanceof Di&&typeof s.write=="function"&&typeof s.end=="function",Q=Symbol("EOF"),J=Symbol("maybeEmitEnd"),nt=Symbol("emittedEnd"),De=Symbol("emittingEnd"),qt=Symbol("emittedError"),Ne=Symbol("closed"),Ns=Symbol("read"),Ae=Symbol("flush"),As=Symbol("flushChunk"),z=Symbol("encoding"),Mt=Symbol("decoder"),g=Symbol("flowing"),Qt=Symbol("paused"),Bt=Symbol("resume"),b=Symbol("buffer"),N=Symbol("pipes"),_=Symbol("bufferLength"),bi=Symbol("bufferPush"),Ie=Symbol("bufferShift"),L=Symbol("objectMode"),S=Symbol("destroyed"),_i=Symbol("error"),Oi=Symbol("emitData"),Is=Symbol("emitEnd"),Ti=Symbol("emitEnd2"),Z=Symbol("async"),xi=Symbol("abort"),Ce=Symbol("aborted"),Jt=Symbol("signal"),Rt=Symbol("dataListeners"),C=Symbol("discarded"),jt=s=>Promise.resolve().then(s),Yr=s=>s(),Kr=s=>s==="end"||s==="finish"||s==="prefinish",Vr=s=>s instanceof ArrayBuffer||!!s&&typeof s=="object"&&s.constructor&&s.constructor.name==="ArrayBuffer"&&s.byteLength>=0,$r=s=>!Buffer.isBuffer(s)&&ArrayBuffer.isView(s),Fe=class{src;dest;opts;ondrain;constructor(t,e,i){this.src=t,this.dest=e,this.opts=i,this.ondrain=()=>t[Bt](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Li=class extends Fe{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,i){super(t,e,i),this.proxyErrors=r=>this.dest.emit("error",r),t.on("error",this.proxyErrors)}},Xr=s=>!!s.objectMode,qr=s=>!s.objectMode&&!!s.encoding&&s.encoding!=="buffer",A=class extends Di{[g]=!1;[Qt]=!1;[N]=[];[b]=[];[L];[z];[Z];[Mt];[Q]=!1;[nt]=!1;[De]=!1;[Ne]=!1;[qt]=null;[_]=0;[S]=!1;[Jt];[Ce]=!1;[Rt]=0;[C]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Xr(e)?(this[L]=!0,this[z]=null):qr(e)?(this[z]=e.encoding,this[L]=!1):(this[L]=!1,this[z]=null),this[Z]=!!e.async,this[Mt]=this[z]?new Hr(this[z]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[b]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[N]});let{signal:i}=e;i&&(this[Jt]=i,i.aborted?this[xi]():i.addEventListener("abort",()=>this[xi]()))}get bufferLength(){return this[_]}get encoding(){return this[z]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[L]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Z]}set async(t){this[Z]=this[Z]||!!t}[xi](){this[Ce]=!0,this.emit("abort",this[Jt]?.reason),this.destroy(this[Jt]?.reason)}get aborted(){return this[Ce]}set aborted(t){}write(t,e,i){if(this[Ce])return!1;if(this[Q])throw new Error("write after end");if(this[S])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(i=e,e="utf8"),e||(e="utf8");let r=this[Z]?jt:Yr;if(!this[L]&&!Buffer.isBuffer(t)){if($r(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Vr(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[L]?(this[g]&&this[_]!==0&&this[Ae](!0),this[g]?this.emit("data",t):this[bi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):t.length?(typeof t=="string"&&!(e===this[z]&&!this[Mt]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[z]&&(t=this[Mt].write(t)),this[g]&&this[_]!==0&&this[Ae](!0),this[g]?this.emit("data",t):this[bi](t),this[_]!==0&&this.emit("readable"),i&&r(i),this[g]):(this[_]!==0&&this.emit("readable"),i&&r(i),this[g])}read(t){if(this[S])return null;if(this[C]=!1,this[_]===0||t===0||t&&t>this[_])return this[J](),null;this[L]&&(t=null),this[b].length>1&&!this[L]&&(this[b]=[this[z]?this[b].join(""):Buffer.concat(this[b],this[_])]);let e=this[Ns](t||null,this[b][0]);return this[J](),e}[Ns](t,e){if(this[L])this[Ie]();else{let i=e;t===i.length||t===null?this[Ie]():typeof i=="string"?(this[b][0]=i.slice(t),e=i.slice(0,t),this[_]-=t):(this[b][0]=i.subarray(t),e=i.subarray(0,t),this[_]-=t)}return this.emit("data",e),!this[b].length&&!this[Q]&&this.emit("drain"),e}end(t,e,i){return typeof t=="function"&&(i=t,t=void 0),typeof e=="function"&&(i=e,e="utf8"),t!==vLine truncated
`,n=Buffer.byteLength(r),o=Math.floor(Math.log(n)/Math.log(10))+1;return n+o>=Math.pow(10,o)&&(o+=1),o+n+r}static parse(t,e,i=!1){return new s(On(Tn(t),e),i)}},On=(s,t)=>t?Object.assign({},t,s):s,Tn=s=>s.replace(/\n$/,"").split(`
`).reduce(xn,Object.create(null)),xn=(s,t)=>{let e=parseInt(t,10);if(e!==Buffer.byteLength(t)+1)return s;t=t.slice((e+" ").length);let i=t.split("="),r=i.shift();if(!r)return s;let n=r.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),o=i.join("=").replace(/\0.*/,"");switch(n){case"path":case"linkpath":case"type":case"charset":case"comment":case"gname":case"uname":s[n]=o;break;case"ctime":case"atime":case"mtime":s[n]=new Date(Number(o)*1e3);break;case"size":let h=+o;h>=0&&(s[n]=h);break;case"gid":case"uid":case"dev":case"ino":case"nlink":case"mode":s[n]=+o;break}return s};var Ln=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,f=Ln!=="win32"?s=>String(s):s=>String(s).replaceAll(/\\/g,"/");var $e=class extends A{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,i){switch(super({}),this.pause(),this.extended=e,this.globalExtended=i,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=f(t.path),this.mode=t.mode,this.mode&&(this.mode=this.mode&4095),this.uid=t.uid,this.gid=t.gid,this.uname=t.uname,this.gname=t.gname,this.size=this.remain,this.mtime=t.mtime,this.atime=t.atime,this.ctime=t.ctime,this.linkpath=t.linkpath?f(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#t(e),i&&this.#t(i,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let i=this.remain,r=this.blockRemain;return this.remain=Math.max(0,i-e),this.blockRemain=Math.max(0,r-e),this.ignore?!0:i>=e?super.write(t):super.write(t.subarray(0,i))}#t(t,e=!1){t.path&&(t.path=f(t.path)),t.linkpath&&(t.linkpath=f(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([i,r])=>!(r==null||i==="path"&&e))))}};var Dt=(s,t,e,i={})=>{s.file&&(i.file=s.file),s.cwd&&(i.cwd=s.cwd),i.code=e instanceof Error&&e.code||t,i.tarCode=t,!s.strict&&i.recoverable!==!1?(e instanceof Error&&(i=Object.assign(e,i),e=e.message),s.emit("warn",t,e,i)):e instanceof Error?s.emit("error",Object.assign(e,i)):s.emit("error",Object.assign(new Error(`${t}: ${e}`),i))};var Nn=1024*1024,Xi=Buffer.from([31,139]),qi=Buffer.from([40,181,47,253]),An=Math.max(Xi.length,qi.length),B=Symbol("state"),Nt=Symbol("writeEntry"),it=Symbol("readEntry"),Zi=Symbol("nextEntry"),Zs=Symbol("processEntry"),V=Symbol("extendedHeader"),he=Symbol("globalExtendedHeader"),dt=Symbol("meta"),Ys=Symbol("emitMeta"),p=Symbol("buffer"),st=Symbol("queue"),ut=Symbol("ended"),Yi=Symbol("emittedEnd"),At=Symbol("emit"),w=Symbol("unzip"),Xe=Symbol("consumeChunk"),qe=Symbol("consumeChunkSub"),Ki=Symbol("consumeBody"),Ks=Symbol("consumeMeta"),Vs=Symbol("consumeHeader"),ae=Symbol("consuming"),Vi=Symbol("bufferConcat"),Qe=Symbol("maybeEnd"),Yt=Symbol("writing"),$=Symbol("aborted"),Je=Symbol("onDone"),It=Symbol("sawValidEntry"),je=Symbol("sawNullBlock"),ti=Symbol("sawEOF"),$s=Symbol("closeStream"),In=1e3,le=Symbol("compressedBytesRead"),$i=Symbol("decompressedBytesRead"),Xs=Symbol("checkDecompressionRatio"),Cn=()=>!0,rt=class extends Dn{file;strict;maxMetaEntrySize;filter;brotli;zstd;maxDecompressionRatio;writable=!0;readable=!1;[st]=[];[p];[it];[Nt];[B]="begin";[dt]="";[V];[he];[ut]=!1;[w];[$]=!1;[It];[je]=!1;[ti]=!1;[Yt]=!1;[ae]=!1;[Yi]=!1;[le]=0;[$i]=0;constructor(t={}){super(),this.file=t.file||"",this.on(Je,()=>{(this[B]==="begin"||this[It]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Je,t.ondone):this.on(Je,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxDecompressionRatio=typeof t.maxDecompressionRatio=="number"?t.maxDecompressionRatio:In,this.maxMetaEntrySize=t.maxMetaEntrySize||Nn,this.filter=typeof t.filter=="function"?t.filter:Cn;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let i=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:i?!0:void 0,this.on("end",()=>this[$s]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,i={}){Dt(this,t,e,i)}[Vs](t,e){this[It]===void 0&&(this[It]=!1);let i;try{i=new F(t,e,this[V],this[he])}catch(r){return this.warn("TAR_ENTRY_INVALID",r)}if(i.nullBlock)this[je]?(this[ti]=!0,this[B]==="begin"&Line truncated
//# sourceMappingURL=index.min.js.map
@@ -0,0 +1,169 @@
// Traversal pattern adapted from Jaen's v3 `mapOnSchema` (Apache-2.0): https://gist.github.com/jaens/7e15ae1984bb338c86eb5e452dee3010
import * as schemas from "./schemas.js";
import { clone } from "./util.js";
const RESOLVING = Symbol("z.visit/resolving");
export function visit(schema, fnOrHandlers) {
const fn = typeof fnOrHandlers === "function"
? fnOrHandlers
: (node, rewritten) => {
// A union of handlers isn't callable with one argument; handler `K` only ever sees kind `K`.
const h = fnOrHandlers[node._zod.def.type];
return h ? h(node, rewritten) : node;
};
const cache = new Map();
function run(s) {
const cached = cache.get(s);
if (cached === RESOLVING) {
// Non-lazy cycle. Defer to parse time, when the cache holds the finished node.
return new schemas.$ZodLazy({
type: "lazy",
getter: () => cache.get(s),
});
}
if (cached !== undefined)
return cached;
cache.set(s, RESOLVING);
const inner = mapInner(s);
const mapped = fn(inner, inner !== s);
cache.set(s, mapped);
return mapped;
}
function mapInner(s) {
const def = s._zod.def;
const kind = def.type;
switch (kind) {
case "object": {
const oldShape = def.shape;
const keys = Object.keys(oldShape);
let changed = false;
const newShape = {};
for (const k of keys) {
const mapped = run(oldShape[k]);
if (mapped !== oldShape[k])
changed = true;
newShape[k] = mapped;
}
let newCatchall = def.catchall;
if (def.catchall) {
newCatchall = run(def.catchall);
if (newCatchall !== def.catchall)
changed = true;
}
return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s;
}
case "array": {
const mapped = run(def.element);
return mapped === def.element ? s : clone(s, { ...def, element: mapped });
}
case "tuple": {
const oldItems = def.items;
let changed = false;
const newItems = [];
for (const item of oldItems) {
const mapped = run(item);
if (mapped !== item)
changed = true;
newItems.push(mapped);
}
let newRest = def.rest;
if (def.rest) {
newRest = run(def.rest);
if (newRest !== def.rest)
changed = true;
}
return changed ? clone(s, { ...def, items: newItems, rest: newRest }) : s;
}
case "record":
case "map": {
const newKey = run(def.keyType);
const newVal = run(def.valueType);
return newKey === def.keyType && newVal === def.valueType
? s
: clone(s, { ...def, keyType: newKey, valueType: newVal });
}
case "set": {
const newVal = run(def.valueType);
return newVal === def.valueType ? s : clone(s, { ...def, valueType: newVal });
}
case "union": {
const oldOptions = def.options;
let changed = false;
const newOptions = [];
for (const opt of oldOptions) {
const mapped = run(opt);
if (mapped !== opt)
changed = true;
newOptions.push(mapped);
}
return changed ? clone(s, { ...def, options: newOptions }) : s;
}
case "intersection": {
const newLeft = run(def.left);
const newRight = run(def.right);
return newLeft === def.left && newRight === def.right
? s
: clone(s, { ...def, left: newLeft, right: newRight });
}
case "optional":
case "nullable":
case "default":
case "prefault":
case "catch":
case "readonly":
case "nonoptional":
case "promise":
case "success": {
const newInner = run(def.innerType);
return newInner === def.innerType ? s : clone(s, { ...def, innerType: newInner });
}
case "pipe": {
const newIn = run(def.in);
const newOut = run(def.out);
return newIn === def.in && newOut === def.out ? s : clone(s, { ...def, in: newIn, out: newOut });
}
case "function": {
const newInput = run(def.input);
const newOutput = run(def.output);
return newInput === def.input && newOutput === def.output
? s
: clone(s, { ...def, input: newInput, output: newOutput });
}
case "lazy": {
// Invoking the getter here would trip the cycle check, so lazy nodes always re-clone.
const original = def.getter;
// Drop the memo, or it shadows the new getter forever.
const { _cachedInner, ...rest } = def;
return clone(s, { ...rest, getter: () => run(original()) });
}
// A leaf by choice: `parts` are regex fragments, not data positions.
case "template_literal":
// Leaves.
case "string":
case "number":
case "int":
case "boolean":
case "bigint":
case "symbol":
case "undefined":
case "null":
case "void":
case "never":
case "any":
case "unknown":
case "date":
case "nan":
case "enum":
case "literal":
case "file":
case "transform":
case "custom":
return s;
default: {
// A new built-in kind becomes a compile error here; unknown user kinds fall through.
kind;
return s;
}
}
}
return run(schema);
}
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"_E"},B:{"1":"_ML _CD","2":"_pJ _6K _TM"},C:{"1":"_uD","2":"_LS jB _L","194":"kB _ZP"},D:{"1":"_ML _EF","2":"_xF _6K _TM"},E:{"1":"XD","2":"_FO"},F:{"1":"_jG _ZF _h","2":"0 _8 _VC _O"},G:{"2":"_M"},H:{"2":"1D"},I:{"1":"I","2":"_G"},J:{"2":"_B"},K:{"2":"_N"},L:{"1":"I"},M:{"1":"YC"},N:{"2":"_A"},O:{"2":"bC"},P:{"1":"_rB","2":"_SN _CG _wE"},Q:{"2":"JE"},R:{"2":"KE"},S:{"2":"_C"}},B:7,C:"CSS3 attr() function for all properties",D:true};
@@ -0,0 +1,331 @@
import type * as errors from "./errors.js";
import type { $ZodMemoizer, $ZodType, $ZodTypeDef, ParseContextInternal, ParsePayload } from "./schemas.js";
import * as util from "./util.js";
export class $ZodCyclicError extends Error {
constructor() {
super(`Cannot parse a reference cycle that closes through a transform`);
this.name = "ZodCyclicError";
}
}
interface Entry {
value: unknown;
/** `null` until the node's children are parsed. */
issues: errors.$ZodRawIssue[] | null;
}
interface State {
/** Weak throughout because `attach` caches a bucket on the schema instance, which outlives the parse. */
buckets: WeakMap<$ZodType, WeakMap<object, Entry>>;
/** Nodes a back-edge resolved to before they finished. */
backEdges: WeakSet<object> | undefined;
}
/** Keyed off the context object every schema in one parse call already shares. */
const STATE = "~memo";
type WithState = { [STATE]?: State };
const NO_ISSUES: errors.$ZodRawIssue[] = [];
// a value a cycle can close through
function isRef(value: unknown): value is object {
return value !== null && typeof value === "object";
}
// Receivers prefix paths in place, so the cache and every hand-out need their own copies.
function cloneIssues(issues: errors.$ZodRawIssue[]): errors.$ZodRawIssue[] {
return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }));
}
const recursive: WeakMap<object, boolean> = /*@__PURE__*/ new WeakMap();
/** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */
const NONE = 0;
const ASSUMED = 1;
const PROVEN = 2;
type Answer = typeof NONE | typeof ASSUMED | typeof PROVEN;
/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */
function isRecursive(inst: $ZodType, stack: Set<object>, resolve: boolean): Answer {
const cached = recursive.get(inst);
if (cached !== undefined) return cached ? PROVEN : NONE;
// Relative to the walk in progress, so not cached.
if (stack.has(inst)) return PROVEN;
stack.add(inst);
let result: Answer = NONE;
const check = (child: any) => {
if (result !== PROVEN && child?._zod) {
const answer = isRecursive(child, stack, resolve);
if (answer > result) result = answer;
}
};
// `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen
const shape = (sh: object, spread: boolean): Answer => {
let answer: Answer = NONE;
for (const key of Reflect.ownKeys(sh)) {
const desc = Object.getOwnPropertyDescriptor(sh, key)!;
// an object resolves its shape by spread, so a key it does not enumerate is never parsed; `z.properties` reads every own key and so keeps them all
if (spread && !desc.enumerable) continue;
// resolving runs user code, and a factory mints a fresh subtree per read, so an edge the walk can't follow counts as a cycle
const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;
if (child > answer) answer = child;
}
return answer;
};
const merge = (answer: Answer) => {
if (answer > result) result = answer;
};
const def = inst._zod.def as any;
const kind = def.type as $ZodTypeDef["type"];
switch (kind) {
case "object": {
const raw = util.rawShape(def);
// a def with no raw shape answers `shape` from an accessor of its own, and running that can mint a whole fresh subtree
merge(raw ? shape(raw, true) : ASSUMED);
check(def.catchall);
break;
}
case "array":
check(def.element);
break;
case "tuple":
for (const el of def.items) check(el);
check(def.rest);
break;
case "record":
case "map":
check(def.keyType);
check(def.valueType);
break;
case "set":
check(def.valueType);
break;
case "union":
for (const el of def.options) check(el);
break;
case "intersection":
check(def.left);
check(def.right);
break;
case "optional":
case "nullable":
case "default":
case "prefault":
case "catch":
case "readonly":
case "nonoptional":
case "promise":
case "success":
check(def.innerType);
break;
case "pipe":
check(def.in);
check(def.out);
break;
case "function":
check(def.input);
check(def.output);
break;
// `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
case "lazy": {
const inner = def._cachedInner ?? (resolve ? (inst as any)._zod.innerType : undefined);
// walked with resolution off: one hop sees past the deferral, and a lazy that yields only another unresolved lazy is generative, so it stops there
merge(inner ? isRecursive(inner, stack, false) : ASSUMED);
break;
}
// a leaf by choice: `parts` are regex fragments, not data positions
case "template_literal":
// leaves
case "string":
case "number":
case "int":
case "boolean":
case "bigint":
case "symbol":
case "undefined":
case "null":
case "void":
case "never":
case "any":
case "unknown":
case "date":
case "nan":
case "enum":
case "literal":
case "file":
case "transform":
case "custom":
break;
default: {
// a new built-in kind becomes a compile error here
kind satisfies never;
// a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code
for (const key in def) {
const desc = Object.getOwnPropertyDescriptor(def, key);
if (!desc || desc.get) continue;
const value = desc.value;
if (!value || typeof value !== "object") continue;
if (value._zod) check(value);
else if (Array.isArray(value)) for (const el of value) check(el);
}
}
}
stack.delete(inst);
return settle(inst, result);
}
/** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */
function settle(inst: $ZodType, answer: Answer): Answer {
if (answer !== ASSUMED) recursive.set(inst, answer === PROVEN);
return answer;
}
/**
* Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.
* Exported for `z.compile`, which refuses to compile such a schema: cycle
* breaking is driven from here off state keyed on the parse context, and a
* generated fast path has no context to key on.
*/
export function isRecursiveSchema(inst: $ZodType): boolean {
// z.compile never parses, so nothing would ever resolve a lazy for it; it runs once and already treats a throw here as recursive
return isRecursive(inst, new Set(), true) !== NONE;
}
function bucketFor(state: State, inst: $ZodType): WeakMap<object, Entry> {
let bucket = state.buckets.get(inst);
if (!bucket) {
bucket = new WeakMap();
state.buckets.set(inst, bucket);
}
return bucket;
}
// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving.
let handoff: WeakMap<object, Entry> | undefined;
// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema.
const open: Entry[] = [];
const memo: $ZodMemoizer = {
alloc(_inst, payload, empty) {
const bucket = handoff;
if (!bucket) return empty;
handoff = undefined;
const entry: Entry = { value: empty, issues: null };
bucket.set(payload.value as object, entry);
open.push(entry);
return empty;
},
guard(inst) {
inst._zod.deferred ??= [];
inst._zod.deferred.push(() => {
const base = inst._zod.parse;
const wrapped = (payload: ParsePayload, ctx: ParseContextInternal): util.MaybeAsync<ParsePayload> => {
// The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind.
if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) throw new $ZodCyclicError();
return base(payload, ctx);
};
inst._zod.parse = wrapped;
if (inst._zod.run === base) inst._zod.run = wrapped;
});
},
attach(inst) {
let isRecursiveInst: boolean | undefined;
let rechecked = false;
// a recursive schema is re-entered many times per parse and its bucket never changes
let lastCtx: object | undefined;
let lastBucket: WeakMap<object, Entry> | undefined;
// Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically.
inst._zod.deferred ??= [];
inst._zod.deferred.push(() => {
const base = inst._zod.parse;
const wrapped = (payload: ParsePayload, ctx: ParseContextInternal): util.MaybeAsync<ParsePayload> => {
if (isRecursiveInst === undefined) {
const walked = isRecursive(inst, new Set(), false);
if (walked === NONE) {
// Nothing here can ever fire, so take it back out.
inst._zod.parse = base;
if (inst._zod.run === wrapped) inst._zod.run = base;
return base(payload, ctx);
}
// this parse resolves the deferred edges on its own path, so ask once more before latching
if (walked === PROVEN || rechecked) isRecursiveInst = true;
else rechecked = true;
}
const input = payload.value;
if (!isRef(input)) return base(payload, ctx);
let state = (ctx as WithState)[STATE];
if (!state) {
state = { buckets: new WeakMap(), backEdges: undefined };
(ctx as WithState)[STATE] = state;
}
let bucket: WeakMap<object, Entry>;
if (lastCtx === ctx) {
bucket = lastBucket!;
} else {
bucket = bucketFor(state, inst);
lastCtx = ctx;
lastBucket = bucket;
}
const hit = bucket.get(input);
if (hit) {
payload.value = hit.value;
if (hit.issues) {
if (hit.issues.length) payload.issues.push(...cloneIssues(hit.issues));
} else {
// Still being parsed: its own checks cover it, so skip them here.
payload.memo = true;
state.backEdges ??= new WeakSet();
state.backEdges.add(hit.value as object);
}
return payload;
}
handoff = bucket;
const depth = open.length;
const result = base(payload, ctx);
handoff = undefined;
// A container that rejected its input outright allocated nothing.
const entry = open.length > depth ? open.pop()! : undefined;
// Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined.
if (result instanceof Promise) {
return result.then((r) => {
if (entry) entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;
return r;
});
}
if (entry) entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;
return result;
};
inst._zod.parse = wrapped;
if (inst._zod.run === base) inst._zod.run = wrapped;
});
},
};
/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */
export function memoizer(): $ZodMemoizer {
return memo;
}
/** Whether this value is a node a back-edge resolved to before it finished. */
export function isBackEdge(ctx: object, value: unknown): boolean {
const backEdges = (ctx as WithState)[STATE]?.backEdges;
return backEdges !== undefined && isRef(value) && backEdges.has(value);
}
@@ -0,0 +1 @@
{"version":3,"file":"gitlab.js","sources":["../../../src/icons/gitlab.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Gitlab\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJtMjIgMTMuMjktMy4zMy0xMGEuNDIuNDIgMCAwIDAtLjE0LS4xOC4zOC4zOCAwIDAgMC0uMjItLjExLjM5LjM5IDAgMCAwLS4yMy4wNy40Mi40MiAwIDAgMC0uMTQuMThsLTIuMjYgNi42N0g4LjMyTDYuMSAzLjI2YS40Mi40MiAwIDAgMC0uMS0uMTguMzguMzggMCAwIDAtLjI2LS4wOC4zOS4zOSAwIDAgMC0uMjMuMDcuNDIuNDIgMCAwIDAtLjE0LjE4TDIgMTMuMjlhLjc0Ljc0IDAgMCAwIC4yNy44M0wxMiAyMWw5LjY5LTYuODhhLjcxLjcxIDAgMCAwIC4zMS0uODNaIiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/gitlab\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n * @deprecated Brand icons have been deprecated and are due to be removed, please refer to https://github.com/lucide-icons/lucide/issues/670. We recommend using https://simpleicons.org/?q=gitlab instead. This icon will be removed in v1.0\n */\nconst Gitlab = createLucideIcon('Gitlab', [\n [\n 'path',\n {\n d: 'm22 13.29-3.33-10a.42.42 0 0 0-.14-.18.38.38 0 0 0-.22-.11.39.39 0 0 0-.23.07.42.42 0 0 0-.14.18l-2.26 6.67H8.32L6.1 3.26a.42.42 0 0 0-.1-.18.38.38 0 0 0-.26-.08.39.39 0 0 0-.23.07.42.42 0 0 0-.14.18L2 13.29a.74.74 0 0 0 .27.83L12 21l9.69-6.88a.71.71 0 0 0 .31-.83Z',\n key: '148pdi',\n },\n ],\n]);\n\nexport default Gitlab;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAS,iBAAiB,QAAU,CAAA,CAAA,CAAA;AAAA,CACxC,CAAA,CAAA;AAAA,CAAA,CAAA,CAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACA,CAAA,CAAA,CAAA,CAAA;AAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACP,CAAA,CAAA,CAAA,CAAA;AAAA,CACF,CAAA,CAAA;AACF,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _iterableToArray;
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) {
return Array.from(iter);
}
}
//# sourceMappingURL=iterableToArray.js.map
@@ -0,0 +1,94 @@
"use strict"
module.exports = require('./loader')(global, loadImplementation);
/**
* Node.js version of loadImplementation.
*
* Requires the given implementation and returns the registration
* containing {Promise, implementation}
*
* If implementation is undefined or global.Promise, loads it
* Otherwise uses require
*/
function loadImplementation(implementation){
var impl = null
if(shouldPreferGlobalPromise(implementation)){
// if no implementation or env specified use global.Promise
impl = {
Promise: global.Promise,
implementation: 'global.Promise'
}
} else if(implementation){
// if implementation specified, require it
var lib = require(implementation)
impl = {
Promise: lib.Promise || lib,
implementation: implementation
}
} else {
// try to auto detect implementation. This is non-deterministic
// and should prefer other branches, but this is our last chance
// to load something without throwing error
impl = tryAutoDetect()
}
if(impl === null){
throw new Error('Cannot find any-promise implementation nor'+
' global.Promise. You must install polyfill or call'+
' require("any-promise/register") with your preferred'+
' implementation, e.g. require("any-promise/register/bluebird")'+
' on application load prior to any require("any-promise").')
}
return impl
}
/**
* Determines if the global.Promise should be preferred if an implementation
* has not been registered.
*/
function shouldPreferGlobalPromise(implementation){
if(implementation){
return implementation === 'global.Promise'
} else if(typeof global.Promise !== 'undefined'){
// Load global promise if implementation not specified
// Versions < 0.11 did not have global Promise
// Do not use for version < 0.12 as version 0.11 contained buggy versions
var version = (/v(\d+)\.(\d+)\.(\d+)/).exec(process.version)
return !(version && +version[1] == 0 && +version[2] < 12)
}
// do not have global.Promise or another implementation was specified
return false
}
/**
* Look for common libs as last resort there is no guarantee that
* this will return a desired implementation or even be deterministic.
* The priority is also nearly arbitrary. We are only doing this
* for older versions of Node.js <0.12 that do not have a reasonable
* global.Promise implementation and we the user has not registered
* the preference. This preserves the behavior of any-promise <= 0.1
* and may be deprecated or removed in the future
*/
function tryAutoDetect(){
var libs = [
"es6-promise",
"promise",
"native-promise-only",
"bluebird",
"rsvp",
"when",
"q",
"pinkie",
"lie",
"vow"]
var i = 0, len = libs.length
for(; i < len; i++){
try {
return loadImplementation(libs[i])
} catch(e){}
}
return null
}
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"_E"},B:{"1":"_K","2":"_I"},C:{"2":"_q _aH yB _L","1028":"_aN","3076":"zB _hC _WB _hF","8193":"_oH _p"},D:{"1":"_HS","2":"_eL","132":"7B 8B","260":"_cQ","516":"BC _RF"},E:{"1":"_6D","2":"_LI","4100":"G _BN _7E"},F:{"1":"_ZJ _RD","2":"_qO","132":"uB vB","260":"wB xB","516":"_aC _zD"},G:{"1":"_UE","2":"_3F","4100":"_QT _aG"},H:{"2":"1D"},I:{"1":"I","2":"_G"},J:{"2":"_B"},K:{"1":"H","2":"_D"},L:{"1":"I"},M:{"8193":"YC"},N:{"2":"_A"},O:{"1":"bC"},P:{"1":"_hB","16":"_rC"},Q:{"1":"JE"},R:{"1":"KE"},S:{"3076":"_C"}},B:1,C:"createImageBitmap",D:true};
@@ -0,0 +1,9 @@
import * as ts from 'typescript';
import type { TSESTree } from './ts-estree';
/**
* Convert all comments for the given AST.
* @param ast the AST object
* @returns the converted ESTreeComment
* @private
*/
export declare function convertComments(ast: ts.SourceFile): TSESTree.Comment[];
@@ -0,0 +1,75 @@
{
"name": "@zxcvbn-ts/dictionary-compression",
"version": "3.0.1",
"type": "commonjs",
"exports": {
"./compress": {
"import": {
"types": "./dist/compress.d.mts",
"default": "./dist/compress.mjs"
},
"require": {
"types": "./dist/compress.d.ts",
"default": "./dist/compress.cjs"
},
"default": "./dist/compress.cjs"
},
"./decompress": {
"import": {
"types": "./dist/decompress.d.mts",
"default": "./dist/decompress.mjs"
},
"require": {
"types": "./dist/decompress.d.ts",
"default": "./dist/decompress.cjs"
},
"default": "./dist/decompress.cjs"
}
},
"scripts": {
"build": "tsup",
"lint": "eslint --ext .ts --fix --cache .",
"typecheck": "tsc --noEmit"
},
"description": "dictionary-compression helper for zxcvbn-ts language packages",
"license": "MIT",
"homepage": "https://github.com/zxcvbn-ts/dictionary-compression",
"repository": {
"type": "git",
"url": "https://github.com/zxcvbn-ts/dictionary-compression.git"
},
"author": "zxcvbn-ts",
"files": [
"dist",
"src"
],
"publishConfig": {
"access": "public",
"provenance": true
},
"dependencies": {},
"devDependencies": {
"@types/jest": "29.5.13",
"@types/node": "20.14.8",
"@typescript-eslint/eslint-plugin": "8.8.0",
"@typescript-eslint/parser": "8.8.0",
"eslint": "8.57.0",
"eslint-config-airbnb-base": "15.0.0",
"eslint-config-prettier": "9.1.0",
"eslint-import-resolver-alias": "1.1.2",
"eslint-import-resolver-webpack": "0.13.9",
"eslint-plugin-compat": "6.0.1",
"eslint-plugin-import": "2.30.0",
"eslint-plugin-prettier": "5.2.1",
"prettier": "3.3.3",
"semantic-release": "24.1.2",
"typescript": "5.6.2",
"tsup": "8.3.0"
},
"keywords": [
"zxcvbn-ts",
"language",
"compression",
"decompression"
]
}
@@ -0,0 +1 @@
{"version":3,"file":"signal-high.js","sources":["../../../src/icons/signal-high.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name SignalHigh\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMiAyMGguMDEiIC8+CiAgPHBhdGggZD0iTTcgMjB2LTQiIC8+CiAgPHBhdGggZD0iTTEyIDIwdi04IiAvPgogIDxwYXRoIGQ9Ik0xNyAyMFY4IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/signal-high\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst SignalHigh = createLucideIcon('SignalHigh', [\n ['path', { d: 'M2 20h.01', key: '4haj6o' }],\n ['path', { d: 'M7 20v-4', key: 'j294jx' }],\n ['path', { d: 'M12 20v-8', key: 'i3yub9' }],\n ['path', { d: 'M17 20V8', key: '1tkaf5' }],\n]);\n\nexport default SignalHigh;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAa,iBAAiB,YAAc,CAAA,CAAA,CAAA;AAAA,CAAA,CAChD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAa,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC1C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAY,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACzC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAa,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC1C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAY,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC3C,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,114 @@
import findLevenshteinDistance, {
FindLevenshteinDistanceResult,
} from '../../utils/levenshtein'
import Options from '../../Options'
import {
DictionaryNames,
DictionaryMatch,
UserInputsOptions,
MatcherBaseClass,
RankedDictionaries,
} from '../../types'
import { DictionaryMatchOptions } from './types'
import mergeUserInputDictionary from '../../utils/mergeUserInputDictionary'
class MatchDictionary extends MatcherBaseClass {
constructor(
options: Options,
protected wordSequenceCheck?: boolean,
) {
super(options)
}
private getRangedDictionaries(userInputsOptions?: UserInputsOptions) {
if (this.wordSequenceCheck) {
const rankedDictionaries: RankedDictionaries = {}
const rankedDictionariesMaxWordSize: Record<string, number> = {}
Object.keys(this.options.rankedDictionaries).forEach((key) => {
if (this.options.isWordSequence(key)) {
rankedDictionaries[key] = this.options.rankedDictionaries[key]
rankedDictionariesMaxWordSize[key] =
this.options.rankedDictionariesMaxWordSize[key]
}
})
return {
rankedDictionaries,
rankedDictionariesMaxWordSize,
}
}
return mergeUserInputDictionary(
this.options.rankedDictionaries,
this.options.rankedDictionariesMaxWordSize,
userInputsOptions,
)
}
public match({
password,
userInputsOptions,
useLevenshtein = true,
}: DictionaryMatchOptions) {
const matches: DictionaryMatch[] = []
const passwordLength = password.length
const passwordLower = password.toLowerCase()
const { rankedDictionaries, rankedDictionariesMaxWordSize } =
this.getRangedDictionaries(userInputsOptions)
// eslint-disable-next-line complexity,max-statements
Object.keys(rankedDictionaries).forEach((dictionaryName) => {
const rankedDict = rankedDictionaries[dictionaryName as DictionaryNames]
const longestDictionaryWordSize =
rankedDictionariesMaxWordSize[dictionaryName]
const searchWidth = Math.min(longestDictionaryWordSize, passwordLength)
for (let i = 0; i < passwordLength; i += 1) {
const searchEnd = Math.min(i + searchWidth, passwordLength)
for (let j = i; j < searchEnd; j += 1) {
const usedPassword = passwordLower.slice(i, j + 1 || 9e9)
const isInDictionary = usedPassword in rankedDict
let foundLevenshteinDistance: Partial<FindLevenshteinDistanceResult> =
{}
// only use levenshtein distance on full password to minimize the performance drop
// and because otherwise there would be to many false positives
const isFullPassword = i === 0 && j === passwordLength - 1
if (
this.options.useLevenshteinDistance &&
isFullPassword &&
!isInDictionary &&
useLevenshtein
) {
foundLevenshteinDistance = findLevenshteinDistance(
usedPassword,
rankedDict,
this.options.levenshteinThreshold,
)
}
const isLevenshteinMatch =
Object.keys(foundLevenshteinDistance).length !== 0
if (isInDictionary || isLevenshteinMatch) {
const usedRankPassword = isLevenshteinMatch
? foundLevenshteinDistance.levenshteinDistanceEntry!
: usedPassword
const rank = rankedDict[usedRankPassword]
matches.push({
pattern: 'dictionary',
i,
j,
token: password.slice(i, j + 1 || 9e9),
matchedWord: usedPassword,
rank,
dictionaryName: dictionaryName,
reversed: false,
l33t: false,
...foundLevenshteinDistance,
})
}
}
}
})
return matches
}
}
export default MatchDictionary
@@ -0,0 +1 @@
require("../dist/register").registerTSLegacyModuleInterop();
@@ -0,0 +1,3 @@
//#region src/middleware/etag/digest.d.ts
export declare const generateDigest: (stream: ReadableStream<Uint8Array<ArrayBuffer>> | null, generator: (body: Uint8Array<ArrayBuffer>) => ArrayBuffer | Promise<ArrayBuffer>) => Promise<string | null>;
//#endregion
@@ -0,0 +1,36 @@
import { __assign, __rest } from "tslib";
import * as React from 'react';
import { fullWidthClassName, zeroRightClassName } from 'react-remove-scroll-bar/constants';
import { useMergeRefs } from 'use-callback-ref';
import { effectCar } from './medium';
var nothing = function () {
return;
};
/**
* Removes scrollbar from the page and contain the scroll within the Lock
*/
var RemoveScroll = React.forwardRef(function (props, parentRef) {
var ref = React.useRef(null);
var _a = React.useState({
onScrollCapture: nothing,
onWheelCapture: nothing,
onTouchMoveCapture: nothing,
}), callbacks = _a[0], setCallbacks = _a[1];
var forwardProps = props.forwardProps, children = props.children, className = props.className, removeScrollBar = props.removeScrollBar, enabled = props.enabled, shards = props.shards, sideCar = props.sideCar, noRelative = props.noRelative, noIsolation = props.noIsolation, inert = props.inert, allowPinchZoom = props.allowPinchZoom, _b = props.as, Container = _b === void 0 ? 'div' : _b, gapMode = props.gapMode, rest = __rest(props, ["forwardProps", "children", "className", "removeScrollBar", "enabled", "shards", "sideCar", "noRelative", "noIsolation", "inert", "allowPinchZoom", "as", "gapMode"]);
var SideCar = sideCar;
var containerRef = useMergeRefs([ref, parentRef]);
var containerProps = __assign(__assign({}, rest), callbacks);
return (React.createElement(React.Fragment, null,
enabled && (React.createElement(SideCar, { sideCar: effectCar, removeScrollBar: removeScrollBar, shards: shards, noRelative: noRelative, noIsolation: noIsolation, inert: inert, setCallbacks: setCallbacks, allowPinchZoom: !!allowPinchZoom, lockRef: ref, gapMode: gapMode })),
forwardProps ? (React.cloneElement(React.Children.only(children), __assign(__assign({}, containerProps), { ref: containerRef }))) : (React.createElement(Container, __assign({}, containerProps, { className: className, ref: containerRef }), children))));
});
RemoveScroll.defaultProps = {
enabled: true,
removeScrollBar: true,
inert: false,
};
RemoveScroll.classNames = {
fullWidth: fullWidthClassName,
zeroRight: zeroRightClassName,
};
export { RemoveScroll };
@@ -0,0 +1,161 @@
import type { $ZodStringFormats } from "../core/checks.js";
import type * as errors from "../core/errors.js";
import type { $ZodInvalidTypeExpected } from "../core/errors.js";
import * as util from "../core/util.js";
const error: () => errors.$ZodErrorMap = () => {
const Sizable: Record<string, { unit: string }> = {
string: { unit: "caracteres" },
file: { unit: "bytes" },
array: { unit: "elementos" },
set: { unit: "elementos" },
map: { unit: "entradas" },
};
function getSizing(origin: string): { unit: string } | null {
return Sizable[origin] ?? null;
}
const FormatDictionary: {
[k in $ZodStringFormats | (string & {})]?: string;
} = {
regex: "a entrada",
email: "o endereço de e-mail",
url: "o URL",
emoji: "o emoji",
uuid: "o UUID",
uuidv4: "o UUIDv4",
uuidv6: "o UUIDv6",
nanoid: "o nanoid",
guid: "o GUID",
cuid: "o cuid",
cuid2: "o cuid2",
ulid: "o ULID",
xid: "o XID",
ksuid: "o KSUID",
datetime: "a data e hora ISO",
date: "a data ISO",
time: "a hora ISO",
duration: "a duração ISO",
ipv4: "o endereço IPv4",
ipv6: "o endereço IPv6",
mac: "o endereço MAC",
cidrv4: "a faixa de endereços IPv4",
cidrv6: "a faixa de endereços IPv6",
base64: "o texto codificado em base64",
base64url: "o texto codificado em base64url",
json_string: "o texto JSON",
e164: "o número E.164",
credit_card: "o número de cartão de crédito",
currency_code: "o código de moeda",
iban: "o IBAN",
jwt: "o JWT",
template_literal: "a entrada",
};
type Articles = { definite: string; indefinite: string };
const Gender: { [k in "masculine" | "feminine"]: Articles } = {
masculine: { definite: "o", indefinite: "um" },
feminine: { definite: "a", indefinite: "uma" },
};
const TypeDictionary: {
[k in errors.$ZodInvalidTypeExpected | (string & {})]?: { name: string; articles: Articles };
} = {
string: { name: "texto", articles: Gender.masculine },
number: { name: "número", articles: Gender.masculine },
int: { name: "número inteiro", articles: Gender.masculine },
boolean: { name: "valor booleano", articles: Gender.masculine },
bigint: { name: "número bigint", articles: Gender.masculine },
symbol: { name: "símbolo", articles: Gender.masculine },
undefined: { name: 'valor "undefined"', articles: Gender.masculine },
null: { name: 'valor "nulo"', articles: Gender.masculine },
never: { name: 'valor "never"', articles: Gender.masculine },
void: { name: 'valor "void"', articles: Gender.masculine },
date: { name: "data", articles: Gender.feminine },
array: { name: "vetor", articles: Gender.masculine },
object: { name: "objeto", articles: Gender.masculine },
tuple: { name: "tupla", articles: Gender.feminine },
record: { name: "registro", articles: Gender.masculine },
map: { name: "mapa", articles: Gender.masculine },
set: { name: "conjunto", articles: Gender.masculine },
file: { name: "arquivo", articles: Gender.masculine },
nonoptional: { name: "valor não opcional", articles: Gender.masculine },
nan: { name: 'valor "NaN"', articles: Gender.masculine }, // Compatibility: "nan" -> "NaN" for display
function: { name: "função", articles: Gender.feminine },
};
function translateOriginWithArticle(
type: $ZodInvalidTypeExpected | (string & {}),
articleType: "definite" | "indefinite"
): string {
const translatedValue = TypeDictionary[type] ?? { name: `valor "${type}"`, articles: Gender.masculine };
return `${translatedValue.articles[articleType]} ${translatedValue.name}`;
}
return (issue) => {
switch (issue.code) {
case "invalid_type": {
const expected = translateOriginWithArticle(issue.expected, "indefinite");
const receivedType = util.parsedType(issue.input);
const received = translateOriginWithArticle(receivedType, "indefinite");
return `Entrada inválida: esperava ${expected}, recebeu ${received}`;
}
case "invalid_value":
if (issue.values.length === 1) return `Entrada inválida: esperava ${util.stringifyPrimitive(issue.values[0])}`;
return `Opção inválida: esperava uma das seguintes opções: ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing)
return `Grande demais: esperava que ${translateOriginWithArticle(issue.origin, "definite")} tivesse ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "elementos"}`;
return `Grande demais: esperava que ${translateOriginWithArticle(issue.origin, "definite")} fosse ${adj} ${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Pequeno demais: esperava que ${translateOriginWithArticle(issue.origin, "definite")} tivesse ${adj} ${issue.minimum.toString()} ${sizing.unit ?? "elementos"}`;
}
return `Pequeno demais: esperava que ${translateOriginWithArticle(issue.origin, "definite")} fosse ${adj} ${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue as errors.$ZodStringFormatIssues;
if (_issue.format === "starts_with") {
return `Texto inválido: deve começar com "${_issue.prefix}"`;
}
if (_issue.format === "ends_with") return `Texto inválido: deve terminar com "${_issue.suffix}"`;
if (_issue.format === "includes") return `Texto inválido: deve incluir "${_issue.includes}"`;
if (_issue.format === "regex") return `Texto inválido: deve corresponder ao padrão ${_issue.pattern}`;
return `Formato d${FormatDictionary[_issue.format] ?? issue.format} inválido`;
}
case "not_multiple_of":
return `Número inválido: deve ser múltiplo de ${issue.divisor}`;
case "unrecognized_keys": {
const plural = issue.keys.length > 1 ? "s" : "";
return `Chave${plural} inválida${plural}: ${util.joinValues(issue.keys, ", ")}`;
}
case "invalid_key":
return `Entrada inválida n${translateOriginWithArticle(issue.origin, "definite")}`;
case "invalid_union":
if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {
const opts = issue.options.map((o) => `'${o}'`).join(" | ");
return `Valor de discriminação inválido. Esperava ${opts}`;
}
return "Entrada inválida";
case "invalid_element":
return `Entrada inválida n${translateOriginWithArticle(issue.origin, "definite")}`;
default:
return `Entrada inválida`;
}
};
};
export default function (): { localeError: errors.$ZodErrorMap } {
return {
localeError: error(),
};
}
@@ -0,0 +1,29 @@
import MatchDictionary from '../../matching'
import { DictionaryMatch } from '../../../../types'
import { DictionaryMatchOptions } from '../../types'
/*
* -------------------------------------------------------------------------------
* Dictionary reverse matching --------------------------------------------------
* -------------------------------------------------------------------------------
*/
class MatchReverse extends MatchDictionary {
public match(matchOptions: DictionaryMatchOptions) {
const passwordReversed = matchOptions.password.split('').reverse().join('')
return super
.match({
...matchOptions,
password: passwordReversed,
})
.map((match: DictionaryMatch) => ({
...match,
token: match.token.split('').reverse().join(''), // reverse back
reversed: true,
// map coordinates back to original string
i: matchOptions.password.length - 1 - match.j,
j: matchOptions.password.length - 1 - match.i,
}))
}
}
export default MatchReverse
@@ -0,0 +1,60 @@
{
"name": "istanbul-reports",
"version": "3.2.0",
"description": "istanbul reports",
"author": "Krishnan Anantheswaran <kananthmail-github@yahoo.com>",
"main": "index.js",
"files": [
"index.js",
"lib"
],
"scripts": {
"test": "nyc mocha --recursive",
"prepare": "webpack --config lib/html-spa/webpack.config.js --mode production",
"prepare:watch": "webpack --config lib/html-spa/webpack.config.js --watch --mode development"
},
"dependencies": {
"html-escaper": "^2.0.0",
"istanbul-lib-report": "^3.0.0"
},
"devDependencies": {
"@babel/core": "^7.7.5",
"@babel/preset-env": "^7.7.5",
"@babel/preset-react": "^7.7.4",
"babel-loader": "^8.0.6",
"chai": "^4.2.0",
"is-windows": "^1.0.2",
"istanbul-lib-coverage": "^3.0.0",
"mocha": "^6.2.2",
"nyc": "^15.0.0-beta.2",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10"
},
"license": "BSD-3-Clause",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/istanbuljs/istanbuljs.git",
"directory": "packages/istanbul-reports"
},
"keywords": [
"istanbul",
"reports"
],
"bugs": {
"url": "https://github.com/istanbuljs/istanbuljs/issues"
},
"homepage": "https://istanbul.js.org/",
"nyc": {
"exclude": [
"lib/html/assets/**",
"lib/html-spa/assets/**",
"lib/html-spa/rollup.config.js",
"test/**"
]
},
"engines": {
"node": ">=8"
}
}
@@ -0,0 +1,8 @@
'use strict';
var call = Function.prototype.call;
var $hasOwn = Object.prototype.hasOwnProperty;
var bind = require('function-bind');
/** @type {import('.')} */
module.exports = bind.call(call, $hasOwn);
@@ -0,0 +1,41 @@
import { isBuiltin } from 'node:module';
let port;
const initialize = async ({ port: _port, time: _time }) => {
port = _port;
};
const NOW_LENGTH = Date.now().toString().length;
const REGEXP_VITEST = new RegExp(`%3Fvitest=\\d{${NOW_LENGTH}}`);
const REGEXP_MOCK_ACTUAL = /\?mock=actual/;
const resolve = (specifier, context, defaultResolve) => {
if (specifier.includes("mock=actual")) {
// url is already resolved by `importActual`
const moduleId = specifier.replace(REGEXP_MOCK_ACTUAL, "");
return {
url: moduleId,
format: isBuiltin(moduleId) ? "builtin" : void 0,
shortCircuit: true
};
}
const isVitest = specifier.includes("%3Fvitest=");
const result = defaultResolve(isVitest ? specifier.replace(REGEXP_VITEST, "") : specifier, context);
if (!port || !context?.parentURL) return result;
if (typeof result === "object" && "then" in result) return result.then((resolved) => {
ensureModuleGraphEntry(resolved.url, context.parentURL);
if (isVitest) resolved.url = `${resolved.url}?vitest=${Date.now()}`;
return resolved;
});
if (isVitest) result.url = `${result.url}?vitest=${Date.now()}`;
ensureModuleGraphEntry(result.url, context.parentURL);
return result;
};
function ensureModuleGraphEntry(url, parentURL) {
if (url.includes("/node_modules/")) return;
port.postMessage({
event: "register-module-graph-entry",
url,
parentURL
});
}
export { initialize, resolve };
@@ -0,0 +1,926 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromJSONSchema = fromJSONSchema;
const registries_js_1 = require("../core/registries.cjs");
const util_js_1 = require("../core/util.cjs");
const _checks = __importStar(require("./checks.cjs"));
const _iso = __importStar(require("./iso.cjs"));
const _schemas = __importStar(require("./schemas.cjs"));
// Local z object to avoid circular dependency with ../index.js
const z = {
..._schemas,
..._checks,
iso: _iso,
};
// Keys that are recognized and handled by the conversion logic
const RECOGNIZED_KEYS = /*@__PURE__*/ new Set([
// Schema identification
"$schema",
"$ref",
"$defs",
"definitions",
// Core schema keywords
"$id",
"id",
"$comment",
"$anchor",
"$vocabulary",
"$dynamicRef",
"$dynamicAnchor",
// Type
"type",
"enum",
"const",
// Composition
"anyOf",
"oneOf",
"allOf",
"not",
// Object
"properties",
"required",
"additionalProperties",
"patternProperties",
"propertyNames",
"minProperties",
"maxProperties",
// Array
"items",
"prefixItems",
"additionalItems",
"minItems",
"maxItems",
"uniqueItems",
"contains",
"minContains",
"maxContains",
// String
"minLength",
"maxLength",
"pattern",
"format",
// Number
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"multipleOf",
// Already handled metadata
"description",
"default",
// Content
"contentEncoding",
"contentMediaType",
"contentSchema",
// Unsupported (error-throwing)
"unevaluatedItems",
"unevaluatedProperties",
"if",
"then",
"else",
"dependentSchemas",
"dependentRequired",
// OpenAPI
"nullable",
"readOnly",
]);
function detectVersion(schema, defaultTarget) {
const $schema = schema.$schema;
if ($schema === "https://json-schema.org/draft/2020-12/schema") {
return "draft-2020-12";
}
if ($schema === "http://json-schema.org/draft-07/schema#") {
return "draft-7";
}
if ($schema === "http://json-schema.org/draft-04/schema#") {
return "draft-4";
}
// Use defaultTarget if provided, otherwise default to draft-2020-12
return defaultTarget ?? "draft-2020-12";
}
// Positional schemas constrain the elements that are present; only minItems makes them required.
function applyMinItems(items, minItems) {
return items.map((item, index) => (index < minItems ? item : item.optional()));
}
// Inverse of the encoding applied to $ref pointer segments in to-json-schema.ts. Per RFC 6901 the `~1` replacement must run before `~0`.
function decodeJSONPointerSegment(segment) {
return segment.replace(/~1/g, "/").replace(/~0/g, "~");
}
function resolveRef(ref, ctx) {
if (!ref.startsWith("#")) {
throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
}
const path = ref.slice(1).split("/").filter(Boolean);
// Handle root reference "#"
if (path.length === 0) {
return ctx.rootSchema;
}
const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
if (path[0] === defsKey) {
const key = path[1] === undefined ? undefined : decodeJSONPointerSegment(path[1]);
if (!key || !ctx.defs[key]) {
throw new Error(`Reference not found: ${ref}`);
}
return ctx.defs[key];
}
throw new Error(`Reference not found: ${ref}`);
}
/**
* Enforces the keywords that constrain an object's own keys — `propertyNames`,
* `minProperties`, `maxProperties` — before `objectSchema` runs. The guard has
* to see the raw input: an object parse drops `__proto__` and can add keys from
* a property `default`, so its output is not the set of names the instance
* actually carried.
*/
function checkObjectGuards(objectSchema, guards) {
// An identity transform, not z.any(), so `toJSONSchema` reports the object on both the input and the output side of the pipe.
const guard = z
.transform((value) => value)
.check((payload) => {
const value = payload.value;
if (typeof value !== "object" || value === null || Array.isArray(value))
return;
const keys = Object.getOwnPropertyNames(value);
if (guards.minProperties !== undefined && keys.length < guards.minProperties) {
payload.issues.push({
origin: "object",
code: "too_small",
minimum: guards.minProperties,
inclusive: true,
message: `Too small: expected object to have >=${guards.minProperties} properties`,
input: value,
inst: objectSchema,
continue: true,
});
}
if (guards.maxProperties !== undefined && keys.length > guards.maxProperties) {
payload.issues.push({
origin: "object",
code: "too_big",
maximum: guards.maxProperties,
inclusive: true,
message: `Too big: expected object to have <=${guards.maxProperties} properties`,
input: value,
inst: objectSchema,
continue: true,
});
}
if (guards.keySchema) {
for (const key of keys) {
const result = guards.keySchema.safeParse(key);
if (result.success)
continue;
payload.issues.push({
code: "invalid_key",
origin: "record",
issues: result.error.issues,
input: key,
path: [key],
continue: true,
});
}
}
});
return guard.pipe(objectSchema);
}
/**
* An injective string for JSON data: two values share a key exactly when `uniqueItems` calls them
* equal, so duplicate detection is a Map lookup rather than a pairwise walk. Strings and keys are
* length-prefixed so no value can spell another one. `null` means "never equal to anything" — a
* cycle or a NaN, neither of which JSON can express.
*/
function canonicalKey(value, seen) {
if (value === null)
return "z";
const type = typeof value;
if (type !== "object") {
if (type === "number" && Number.isNaN(value))
return null;
const raw = String(value);
return `${type[0]}${raw.length}:${raw}`;
}
if (seen.has(value))
return null;
seen.add(value);
try {
if (Array.isArray(value)) {
const parts = [];
for (const item of value) {
const key = canonicalKey(item, seen);
if (key === null)
return null;
parts.push(key);
}
return `a${parts.length}:[${parts.join(",")}]`;
}
const keys = Object.keys(value).sort();
const parts = [];
for (const k of keys) {
const key = canonicalKey(value[k], seen);
if (key === null)
return null;
parts.push(`${k.length}:${k}=${key}`);
}
return `o${parts.length}:{${parts.join(",")}}`;
}
finally {
seen.delete(value);
}
}
// keywords whose value is a schema or an array of them
const SCHEMA_KEYWORDS = /*@__PURE__*/ new Set([
"items",
"prefixItems",
"additionalItems",
"additionalProperties",
"contains",
"propertyNames",
"not",
"if",
"then",
"else",
"allOf",
"anyOf",
"oneOf",
"unevaluatedItems",
"unevaluatedProperties",
"contentSchema",
]);
// keywords whose value maps names to schemas. draft-7 `dependencies` also allows an array of property names, which holds no schema to walk
const SCHEMA_MAP_KEYWORDS = /*@__PURE__*/ new Set([
"properties",
"patternProperties",
"dependentSchemas",
"dependencies",
"$defs",
"definitions",
]);
/**
* True when a subschema holds a `$ref` anywhere a schema can appear. Only those positions are
* walked: `$ref` under `default` or an `x-` annotation is instance data with an ordinary key, and
* reading it as a reference would drop a constraint that resolves perfectly well.
*/
function containsRef(value) {
if (typeof value !== "object" || value === null)
return false;
if (Array.isArray(value))
return value.some(containsRef);
if (typeof value.$ref === "string")
return true;
return Object.entries(value).some(([key, sub]) => {
if (SCHEMA_KEYWORDS.has(key))
return containsRef(sub);
if (!SCHEMA_MAP_KEYWORDS.has(key) || typeof sub !== "object" || sub === null)
return false;
return Object.values(sub).some(containsRef);
});
}
function plural(n) {
return n === 1 ? "element" : "elements";
}
/**
* Enforces `uniqueItems` and the `contains` family before `arraySchema` runs, for the same reason
* `checkObjectGuards` runs pre-pipe: an item parse can apply a nested `default`, so the parsed
* array is not the instance the keywords are defined over. A guard issue aborts the pipe, so
* `minItems`/`maxItems` are not also reported on the same parse — instance correctness is worth
* more than co-reporting two issues.
*/
function checkArrayGuards(arraySchema, guards) {
// An identity transform, not z.any(), so `toJSONSchema` reports the array on both the input and the output side of the pipe.
const guard = z
.transform((value) => value)
.check((payload) => {
const items = payload.value;
if (!Array.isArray(items))
return;
if (guards.uniqueItems === true) {
const firstSeen = new Map();
for (let i = 0; i < items.length; i++) {
const key = canonicalKey(items[i], new Set());
if (key === null)
continue;
const first = firstSeen.get(key);
if (first === undefined) {
firstSeen.set(key, i);
continue;
}
payload.issues.push({
code: "custom",
message: `Array items must be unique: element at index ${i} duplicates the one at index ${first}`,
input: items,
path: [i],
continue: true,
});
}
}
if (guards.containsSchema) {
const minContains = guards.minContains ?? 1;
// one past the ceiling already proves the failure, and nothing above it changes the verdict
const ceiling = guards.maxContains !== undefined ? guards.maxContains + 1 : Number.POSITIVE_INFINITY;
let matches = 0;
for (const item of items) {
if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling)
break;
}
if (matches < minContains) {
// the scan ran to the end, so this count is exact
payload.issues.push({
code: "custom",
message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,
input: items,
continue: true,
});
}
if (guards.maxContains !== undefined && matches > guards.maxContains) {
payload.issues.push({
code: "custom",
message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,
input: items,
continue: true,
});
}
}
});
return guard.pipe(arraySchema);
}
function getTupleRest(restSchema, ctx) {
if (restSchema === false) {
return undefined;
}
if (restSchema === undefined || restSchema === true) {
return z.any();
}
return convertSchema(restSchema, ctx);
}
// the RFC 3339 full-time keyword, narrower than `z.iso.time()`; local because sharing it via `timeSource` pins that builder into every bundle (+139 B gzipped on a mini `z.boolean()`)
const fullTime = /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;
function convertBaseSchema(schema, ctx) {
// Handle unsupported features
if (schema.not !== undefined) {
// Special case: { not: {} } represents never
if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) {
return z.never();
}
throw new Error("not is not supported in Zod (except { not: {} } for never)");
}
if (schema.unevaluatedItems !== undefined) {
throw new Error("unevaluatedItems is not supported");
}
if (schema.unevaluatedProperties !== undefined) {
throw new Error("unevaluatedProperties is not supported");
}
if (schema.if !== undefined || schema.then !== undefined || schema.else !== undefined) {
throw new Error("Conditional schemas (if/then/else) are not supported");
}
if (schema.dependentSchemas !== undefined || schema.dependentRequired !== undefined) {
throw new Error("dependentSchemas and dependentRequired are not supported");
}
// Handle $ref
if (schema.$ref) {
const refPath = schema.$ref;
if (ctx.refs.has(refPath)) {
return ctx.refs.get(refPath);
}
if (ctx.processing.has(refPath)) {
// Circular reference - use lazy
return z.lazy(() => {
if (!ctx.refs.has(refPath)) {
throw new Error(`Circular reference not resolved: ${refPath}`);
}
return ctx.refs.get(refPath);
});
}
ctx.processing.add(refPath);
const resolved = resolveRef(refPath, ctx);
const zodSchema = convertSchema(resolved, ctx);
ctx.refs.set(refPath, zodSchema);
ctx.processing.delete(refPath);
return zodSchema;
}
// Handle enum
if (schema.enum !== undefined) {
const enumValues = schema.enum;
// Special case: OpenAPI 3.0 null representation { type: "string", nullable: true, enum: [null] }
if (ctx.version === "openapi-3.0" &&
schema.nullable === true &&
enumValues.length === 1 &&
enumValues[0] === null) {
return z.null();
}
if (enumValues.length === 0) {
return z.never();
}
if (enumValues.length === 1) {
return z.literal(enumValues[0]);
}
// Check if all values are strings
if (enumValues.every((v) => typeof v === "string")) {
return z.enum(enumValues);
}
// Mixed types - use union of literals
const literalSchemas = enumValues.map((v) => z.literal(v));
if (literalSchemas.length < 2) {
return literalSchemas[0];
}
return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]);
}
// Handle const
if (schema.const !== undefined) {
return z.literal(schema.const);
}
// Handle type
const type = schema.type;
if (Array.isArray(type)) {
// Expand type array into anyOf union
const typeSchemas = type.map((t) => {
const typeSchema = { ...schema, type: t };
return convertBaseSchema(typeSchema, ctx);
});
if (typeSchemas.length === 0) {
return z.never();
}
if (typeSchemas.length === 1) {
return typeSchemas[0];
}
return z.union(typeSchemas);
}
if (!type) {
// No type specified - empty schema (any)
return z.any();
}
let zodSchema;
switch (type) {
case "string": {
let stringSchema = z.string();
// Apply format using .check() with Zod format functions
if (schema.format) {
const format = schema.format;
// Map common formats to Zod check functions
if (format === "email") {
stringSchema = stringSchema.check(z.email());
}
else if (format === "uri" || format === "uri-reference") {
stringSchema = stringSchema.check(z.url());
}
else if (format === "uuid" || format === "guid") {
stringSchema = stringSchema.check(z.uuid());
}
else if (format === "date-time") {
stringSchema = stringSchema.check(z.iso.datetime({ offset: true }));
}
else if (format === "date") {
stringSchema = stringSchema.check(z.iso.date());
}
else if (format === "time") {
stringSchema = stringSchema.check(z.regex(fullTime));
}
else if (format === "duration") {
stringSchema = stringSchema.check(z.iso.duration());
}
else if (format === "hostname") {
stringSchema = stringSchema.check(z.hostname());
}
else if (format === "ipv4") {
stringSchema = stringSchema.check(z.ipv4());
}
else if (format === "ipv6") {
stringSchema = stringSchema.check(z.ipv6());
}
else if (format === "mac") {
stringSchema = stringSchema.check(z.mac());
}
else if (format === "cidr") {
stringSchema = stringSchema.check(z.cidrv4());
}
else if (format === "cidr-v6") {
stringSchema = stringSchema.check(z.cidrv6());
}
else if (format === "base64") {
stringSchema = stringSchema.check(z.base64());
}
else if (format === "base64url") {
stringSchema = stringSchema.check(z.base64url());
}
else if (format === "e164") {
stringSchema = stringSchema.check(z.e164());
}
else if (format === "credit_card") {
stringSchema = stringSchema.check(z.creditCard());
}
else if (format === "iban") {
stringSchema = stringSchema.check(z.iban());
}
else if (format === "jwt") {
stringSchema = stringSchema.check(z.jwt());
}
else if (format === "emoji") {
stringSchema = stringSchema.check(z.emoji());
}
else if (format === "nanoid") {
stringSchema = stringSchema.check(z.nanoid());
}
else if (format === "cuid") {
stringSchema = stringSchema.check(z.cuid());
}
else if (format === "cuid2") {
stringSchema = stringSchema.check(z.cuid2());
}
else if (format === "ulid") {
stringSchema = stringSchema.check(z.ulid());
}
else if (format === "xid") {
stringSchema = stringSchema.check(z.xid());
}
else if (format === "ksuid") {
stringSchema = stringSchema.check(z.ksuid());
}
// Note: json-string format is not currently supported by Zod
// Custom formats are ignored - keep as plain string
}
// Apply constraints
if (typeof schema.minLength === "number") {
stringSchema = stringSchema.min(schema.minLength);
}
if (typeof schema.maxLength === "number") {
stringSchema = stringSchema.max(schema.maxLength);
}
if (schema.pattern) {
// JSON Schema patterns are not implicitly anchored (match anywhere in string)
stringSchema = stringSchema.regex(new RegExp(schema.pattern));
}
zodSchema = stringSchema;
break;
}
case "number":
case "integer": {
let numberSchema = type === "integer" ? z.number().int() : z.number();
// Apply constraints
// In draft-04, `exclusiveMinimum: true` makes the sibling `minimum` exclusive rather than an independent bound, so the inclusive `.min()` is skipped; emitting it too would be dominated by the exclusive check and report a second, weaker issue.
if (typeof schema.minimum === "number" && schema.exclusiveMinimum !== true) {
numberSchema = numberSchema.min(schema.minimum);
}
if (typeof schema.maximum === "number" && schema.exclusiveMaximum !== true) {
numberSchema = numberSchema.max(schema.maximum);
}
if (typeof schema.exclusiveMinimum === "number") {
numberSchema = numberSchema.gt(schema.exclusiveMinimum);
}
else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") {
numberSchema = numberSchema.gt(schema.minimum);
}
if (typeof schema.exclusiveMaximum === "number") {
numberSchema = numberSchema.lt(schema.exclusiveMaximum);
}
else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") {
numberSchema = numberSchema.lt(schema.maximum);
}
if (typeof schema.multipleOf === "number") {
numberSchema = numberSchema.multipleOf(schema.multipleOf);
}
zodSchema = numberSchema;
break;
}
case "boolean": {
zodSchema = z.boolean();
break;
}
case "null": {
zodSchema = z.null();
break;
}
case "object": {
const shape = {};
const properties = schema.properties || {};
const requiredSet = new Set(schema.required || []);
const additionalSchema = typeof schema.additionalProperties === "object"
? convertSchema(schema.additionalProperties, ctx)
: undefined;
// Convert properties - mark optional ones
for (const [key, propSchema] of Object.entries(properties)) {
const propZodSchema = convertSchema(propSchema, ctx);
// If not in required array, make it optional. assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter
(0, util_js_1.assignProp)(shape, key, requiredSet.has(key) ? propZodSchema : propZodSchema.optional());
}
// Handle patternProperties
if (schema.patternProperties) {
// patternProperties: keys matching pattern must satisfy corresponding schema. Use loose records so non-matching keys pass through
const patternProps = schema.patternProperties;
const patternKeys = Object.keys(patternProps);
const looseRecords = [];
for (const pattern of patternKeys) {
const patternValue = convertSchema(patternProps[pattern], ctx);
const keySchema = z.string().regex(new RegExp(pattern));
looseRecords.push(z.looseRecord(keySchema, patternValue));
}
// Build intersection: object schema + all pattern property records
const schemasToIntersect = [];
if (Object.keys(shape).length > 0) {
// Use passthrough so patternProperties can validate additional keys
schemasToIntersect.push(z.object(shape).passthrough());
}
schemasToIntersect.push(...looseRecords);
if (schemasToIntersect.length === 0) {
zodSchema = z.object({}).passthrough();
}
else if (schemasToIntersect.length === 1) {
zodSchema = schemasToIntersect[0];
}
else {
// Chain intersections: (A & B) & C & D ...
let result = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);
for (let i = 2; i < schemasToIntersect.length; i++) {
result = z.intersection(result, schemasToIntersect[i]);
}
zodSchema = result;
}
// When additionalProperties is false, reject keys that are neither defined in properties nor matched by any patternProperty.
if (schema.additionalProperties === false) {
const propertyKeys = Object.keys(shape);
const patterns = patternKeys.map((p) => new RegExp(p));
const basePatternSchema = zodSchema;
zodSchema = zodSchema.check((payload) => {
if (!(0, util_js_1.isPlainObject)(payload.value))
return;
const unrecognized = [];
for (const key of Object.keys(payload.value)) {
if (propertyKeys.includes(key))
continue;
if (patterns.some((regex) => regex.test(key)))
continue;
unrecognized.push(key);
}
if (unrecognized.length) {
payload.issues.push({
code: "unrecognized_keys",
keys: unrecognized,
input: payload.value,
inst: basePatternSchema,
});
}
});
}
}
else {
// Handle additionalProperties. In JSON Schema, additionalProperties defaults to true (allow any extra properties). In Zod, objects strip unknown keys by default, so we need to handle this explicitly
const objectSchema = z.object(shape);
if (schema.additionalProperties === false) {
// Strict mode - no extra properties allowed
zodSchema = objectSchema.strict();
}
else if (additionalSchema) {
// Extra properties must match the specified schema
zodSchema = objectSchema.catchall(additionalSchema);
}
else {
// additionalProperties is true or undefined - allow any extra properties (passthrough)
zodSchema = objectSchema.passthrough();
}
}
// propertyNames constrains key *names* only, and says nothing about which keys are required or how their values validate. Layering it on top of the result keeps properties/patternProperties/additionalProperties composing underneath. `true` allows every name, so it needs no guard.
const hasKeyGuard = schema.propertyNames !== undefined && schema.propertyNames !== true;
const minProperties = typeof schema.minProperties === "number" ? schema.minProperties : undefined;
const maxProperties = typeof schema.maxProperties === "number" ? schema.maxProperties : undefined;
if (hasKeyGuard || minProperties !== undefined || maxProperties !== undefined) {
let keySchema;
if (hasKeyGuard) {
// Keys are always strings, so a propertyNames subschema that omits `type` still constrains them — without this it would convert to z.any().
const keyJSONSchema = typeof schema.propertyNames === "object" && schema.propertyNames.type === undefined
? { type: "string", ...schema.propertyNames }
: schema.propertyNames;
keySchema = convertSchema(keyJSONSchema, ctx);
}
zodSchema = checkObjectGuards(zodSchema, { keySchema, minProperties, maxProperties });
}
break;
}
case "array": {
// Check if this is a tuple (prefixItems or items as array)
const prefixItems = schema.prefixItems;
const items = schema.items;
if (prefixItems && Array.isArray(prefixItems)) {
// Tuple with prefixItems (draft-2020-12)
const minItems = typeof schema.minItems === "number" ? schema.minItems : 0;
const tupleItems = prefixItems.map((item) => convertSchema(item, ctx));
const positionalItems = applyMinItems(tupleItems, minItems);
const rest = !Array.isArray(items) ? getTupleRest(items, ctx) : undefined;
const tupleSchema = z.tuple(positionalItems);
zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema;
// Apply minItems/maxItems constraints to tuples
if (typeof schema.minItems === "number") {
zodSchema = zodSchema.check(z.minLength(schema.minItems));
}
if (typeof schema.maxItems === "number") {
zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
}
}
else if (Array.isArray(items)) {
// Tuple with items array (draft-7)
const minItems = typeof schema.minItems === "number" ? schema.minItems : 0;
const tupleItems = items.map((item) => convertSchema(item, ctx));
const positionalItems = applyMinItems(tupleItems, minItems);
const rest = getTupleRest(schema.additionalItems, ctx);
const tupleSchema = z.tuple(positionalItems);
zodSchema = rest ? tupleSchema.rest(rest) : tupleSchema;
// Apply minItems/maxItems constraints to tuples
if (typeof schema.minItems === "number") {
zodSchema = zodSchema.check(z.minLength(schema.minItems));
}
if (typeof schema.maxItems === "number") {
zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
}
}
else if (items !== undefined) {
// Regular array
const element = convertSchema(items, ctx);
let arraySchema = z.array(element);
// Apply constraints
if (typeof schema.minItems === "number") {
arraySchema = arraySchema.min(schema.minItems);
}
if (typeof schema.maxItems === "number") {
arraySchema = arraySchema.max(schema.maxItems);
}
zodSchema = arraySchema;
}
else {
// No items specified - array of any
zodSchema = z.array(z.any());
}
// minContains/maxContains only constrain anything when `contains` itself is present
if (schema.uniqueItems === true || schema.contains !== undefined) {
zodSchema = checkArrayGuards(zodSchema, {
uniqueItems: schema.uniqueItems === true,
containsSchema: schema.contains !== undefined ? convertSchema(schema.contains, ctx) : undefined,
minContains: typeof schema.minContains === "number" ? schema.minContains : undefined,
maxContains: typeof schema.maxContains === "number" ? schema.maxContains : undefined,
});
}
break;
}
default:
throw new Error(`Unsupported type: ${type}`);
}
return zodSchema;
}
function convertSchema(schema, ctx) {
if (typeof schema === "boolean") {
return schema ? z.any() : z.never();
}
// Convert base schema first (ignoring composition keywords)
let baseSchema = convertBaseSchema(schema, ctx);
const hasExplicitType = schema.type || schema.enum !== undefined || schema.const !== undefined;
// Process composition keywords LAST (they can appear together)
// Handle anyOf - wrap base schema with union
if (schema.anyOf && Array.isArray(schema.anyOf)) {
const options = schema.anyOf.map((s) => convertSchema(s, ctx));
const anyOfUnion = z.union(options);
baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;
}
// Handle oneOf - exclusive union (exactly one must match)
if (schema.oneOf && Array.isArray(schema.oneOf)) {
const options = schema.oneOf.map((s) => convertSchema(s, ctx));
const oneOfUnion = z.xor(options);
baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion;
}
// Handle allOf - wrap base schema with intersection
if (schema.allOf && Array.isArray(schema.allOf)) {
if (schema.allOf.length === 0) {
baseSchema = hasExplicitType ? baseSchema : z.any();
}
else {
let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);
const startIdx = hasExplicitType ? 0 : 1;
for (let i = startIdx; i < schema.allOf.length; i++) {
result = z.intersection(result, convertSchema(schema.allOf[i], ctx));
}
baseSchema = result;
}
}
// Handle nullable (OpenAPI 3.0)
if (schema.nullable === true && ctx.version === "openapi-3.0") {
baseSchema = z.nullable(baseSchema);
}
// Handle readOnly
if (schema.readOnly === true) {
baseSchema = z.readonly(baseSchema);
}
// Apply `default` so it wraps the fully-composed schema. This ensures `parse(undefined) -> default` works regardless of which branch of `convertBaseSchema` produced the inner schema (enum/const/not/typed/etc.).
if (schema.default !== undefined) {
baseSchema = baseSchema.default(schema.default);
}
// Collect non-description annotation metadata into the user-supplied registry. Description is handled separately below via `.describe()` to preserve the contract that `schema.description` reads from globalRegistry.
const extraMeta = {};
const coreMetadataKeys = ["$id", "id", "$comment", "$anchor", "$vocabulary", "$dynamicRef", "$dynamicAnchor"];
for (const key of coreMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
const contentMetadataKeys = ["contentEncoding", "contentMediaType", "contentSchema"];
for (const key of contentMetadataKeys) {
if (key in schema) {
extraMeta[key] = schema[key];
}
}
// `propertyNames` and `contains` are enforced by a guard, which `toJSONSchema` cannot infer, so the original keyword is carried as metadata to keep the round-trip lossless. Only where it was actually applied: on any other type it is inert, and on a `$ref` the metadata would land on the target every reference shares. A carried subschema is copied verbatim while the root `$defs` stay behind, so one holding a `$ref` is dropped rather than emitted as a dangling reference.
if (schema.type === "object" && schema.$ref === undefined) {
if (schema.propertyNames !== undefined && !containsRef(schema.propertyNames)) {
extraMeta.propertyNames = schema.propertyNames;
}
for (const key of ["minProperties", "maxProperties"]) {
if (schema[key] !== undefined)
extraMeta[key] = schema[key];
}
}
if (schema.type === "array" && schema.$ref === undefined) {
if (schema.contains !== undefined && !containsRef(schema.contains)) {
extraMeta.contains = schema.contains;
}
for (const key of ["uniqueItems", "minContains", "maxContains"]) {
if (schema[key] !== undefined)
extraMeta[key] = schema[key];
}
}
for (const key of Object.keys(schema)) {
if (!RECOGNIZED_KEYS.has(key)) {
(0, util_js_1.assignProp)(extraMeta, key, schema[key]);
}
}
if (Object.keys(extraMeta).length > 0) {
ctx.registry.add(baseSchema, extraMeta);
}
// Apply description last. `.describe()` clones the schema and sets `_zod.parent` on the clone, so registry lookups on the returned reference still resolve `extraMeta` via parent inheritance.
if (schema.description) {
baseSchema = baseSchema.describe(schema.description);
}
return baseSchema;
}
/**
* Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */
function fromJSONSchema(schema, params) {
// Handle boolean schemas
if (typeof schema === "boolean") {
return schema ? z.any() : z.never();
}
// Normalize input via a JSON round-trip. This guarantees the converter walks a plain, finite, JSON-valid object graph: cyclic inputs fail here, getter/Proxy-based properties are materialized into static values, and class instances collapse to plain objects.
let normalized;
try {
normalized = JSON.parse(JSON.stringify(schema));
}
catch {
throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
}
const version = detectVersion(normalized, params?.defaultTarget);
const defs = (normalized.$defs || normalized.definitions || {});
const ctx = {
version,
defs,
refs: new Map(),
processing: new Set(),
rootSchema: normalized,
registry: params?.registry ?? registries_js_1.globalRegistry,
};
return convertSchema(normalized, ctx);
}
// seal-cjs-exports
(function () {
var keys = Object.getOwnPropertyNames(exports);
for (var i = 0; i < keys.length; i++) {
var desc = Object.getOwnPropertyDescriptor(exports, keys[i]);
if (!desc || !desc.get || !desc.configurable) continue;
var value;
try {
value = desc.get();
} catch (e) {
continue;
}
// a circular require may not have settled this one yet, so leave it live
if (value === undefined) continue;
Object.defineProperty(exports, keys[i], { value: value, writable: false, enumerable: desc.enumerable, configurable: false });
}
Object.freeze(exports);
})();
@@ -0,0 +1,2 @@
export default function dayOfYear(date: Date): number;
export default function dayOfYear(date: Date, val: number): Date;
@@ -0,0 +1,142 @@
"use strict";
// translate the various posix character classes into unicode properties
// this works across all unicode locales
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseClass = void 0;
// { <posix class>: [<translation>, negated]
const posixClasses = {
'[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}'],
'[:alpha:]': ['\\p{L}\\p{Nl}'],
'[:ascii:]': ['\\x' + '00-\\x' + '7f'],
'[:blank:]': ['\\p{Zs}\\t'],
'[:cntrl:]': ['\\p{Cc}'],
'[:digit:]': ['\\p{Nd}'],
'[:graph:]': ['\\p{Z}\\p{C}', true],
'[:lower:]': ['\\p{Ll}'],
'[:print:]': ['\\p{C}', true],
'[:punct:]': ['\\p{P}\\p{S}'],
'[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f'],
'[:upper:]': ['\\p{Lu}'],
'[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}'],
'[:xdigit:]': ['A-Fa-f0-9'],
};
// only need to escape a few things inside of brace expressions
// escapes: [ \ ] -
const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
const noMatch = /$./;
// Takes a glob string at a posix brace expression. Returns a RegExp
// that tests one character, and the number of glob chars consumed.
// If the class is not closed, consumed is 0, and the `[` must be
// treated as a literal character.
// Out of order ranges are removed. If nothing is left, the RegExp
// is `/$./`, and the rest of the glob is consumed, so that the
// whole glob cannot match.
const parseClass = (glob, position, nocase = false, form) => {
// normalize one class member, if it stays one code point
const norm = (c) => {
const n = form ? c.normalize(form) : c;
return [...n].length === 1 ? n : c;
};
const pos = position;
/* c8 ignore start */
if (glob.charAt(pos) !== '[') {
throw new Error('not in a brace expression');
}
/* c8 ignore stop */
const ranges = [];
const negs = [];
let i = pos + 1;
let sawStart = false;
let escaping = false;
let negate = false;
let endPos = pos;
let rangeStart = '';
WHILE: while (i < glob.length) {
const c = String.fromCodePoint(glob.codePointAt(i));
if ((c === '!' || c === '^') && i === pos + 1) {
negate = true;
i++;
continue;
}
if (c === ']' && sawStart && !escaping) {
endPos = i + 1;
break;
}
sawStart = true;
if (c === '\\') {
if (!escaping) {
escaping = true;
i++;
continue;
}
// escaped \ char, fall through and treat like normal char
}
if (c === '[' && !escaping) {
// either a posix class, a collation equivalent, or just a [
for (const [cls, [unip, neg]] of Object.entries(posixClasses)) {
if (glob.startsWith(cls, i)) {
// invalid, [a-[] is fine, but not [a-[:alpha]]
if (rangeStart) {
return [noMatch, glob.length - pos];
}
i += cls.length;
if (neg)
negs.push(unip);
else
ranges.push(unip);
continue WHILE;
}
}
}
// now it's just a normal character, effectively
escaping = false;
const n = norm(c);
if (rangeStart) {
// throw this range away if it's not valid, but others
// can still match.
if (n.codePointAt(0) > rangeStart.codePointAt(0)) {
ranges.push(braceEscape(rangeStart) + '-' + braceEscape(n));
}
else if (n === rangeStart) {
ranges.push(braceEscape(n));
}
rangeStart = '';
i += c.length;
continue;
}
// now might be the start of a range.
// can be either c-d or c-] or c<more...>] or c] at this point
if (glob.startsWith('-]', i + c.length)) {
ranges.push(braceEscape(n + '-'));
i += c.length + 1;
continue;
}
if (glob.startsWith('-', i + c.length)) {
rangeStart = n;
i += c.length + 1;
continue;
}
// not the start of a range, just a single character
ranges.push(braceEscape(n));
i += c.length;
}
if (endPos < i) {
// didn't see the end of the class, not a valid class,
// but might still be valid as a literal match.
return [noMatch, 0];
}
// if we got no ranges and no negates, then we have a range that
// cannot possibly match anything, and that poisons the whole glob
if (!ranges.length && !negs.length) {
return [noMatch, glob.length - pos];
}
const sranges = '[' + (negate ? '^' : '') + ranges.join('') + ']';
const snegs = '[' + (negate ? '' : '^') + negs.join('') + ']';
const comb = '^' +
(ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
: ranges.length ? sranges
: snegs);
return [new RegExp(comb, nocase ? 'iu' : 'u'), endPos - pos];
};
exports.parseClass = parseClass;
//# sourceMappingURL=parse-class.js.map
@@ -0,0 +1,434 @@
flf2a$ 4 4 99 0 20
Bulbhead by Jef Poskanzer, 23jun94
Figlet release 2.0 -- August 5, 1993
____ __ __ __ ____ _ _ ____ __ ____
( _ \( )( )( ) ( _ \( )_( )( ___) /__\ ( _ \
) _ < )(__)( )(__ ) _ < ) _ ( )___) /(__)\ )(_) )
(____/(______)(____)(____/(_) (_)(____)(__)(__)(____/
Update February 12, 2002 by Markus Gebhard markus@jave.de
Added german umlauts
Explanation of first line:
flf2 - "magic number" for file identification
a - should always be `a', for now
$ - the "hardblank" -- prints as a blank, but can't be smushed
4 - height of a character
4 - height of a character, not including descenders
99 - max line length (excluding comment lines) + a fudge factor
0 - default smushmode for this font (like "-m 0" on command line)
13 - number of comment lines
$$@
$$@
$$@
$$@@
/\@
)(@
\/@
()@@
||@
@
@
@@
| | @
-|-|-@
-|-|-@
| | @@
_|_ @
/ |_)@
\_| \@
(_|_/@@
_ _ @
(_)/ ) @
/ /_ @
(_/(_)@@
_ @
( ) @
/_\/@
(__/\@@
/@
@
@
@@
_ @
/ )@
( ( @
\_)@@
_ @
( \ @
) )@
(_/ @@
@
\|/@
/|\@
@@
_ @
_| |_ @
(_ _)@
|_| @@
@
@
()@
/ @@
@
___ @
(___)@
@@
@
@
@
()@@
_ @
/ )@
/ / @
(_/ @@
___ @
/ _ \ @
( (_) )@
\___/ @@
__ @
/ )@
)( @
(__)@@
___ @
(__ \ @
/ _/ @
(____)@@
___ @
(__ )@
(_ \@
(___/@@
__ @
/. | @
(_ _)@
(_) @@
___ @
| __)@
|__ \@
(___/@@
_ @
/ ) @
/ _ \@
\___/@@
___ @
(__ )@
/ / @
(_/ @@
___ @
( _ )@
/ _ \@
\___/@@
___ @
/ _ \@
\_ /@
(_/ @@
@
()@
@
()@@
()@
@
()@
/ @@
__@
/ /@
< < @
\_\@@
___ @
(___)@
___ @
(___)@@
__ @
\ \ @
> >@
/_/ @@
___ @
(__ )@
(_/ @
(_) @@
__ @
/ \@
| ()/@
\__ @@
__ @
/__\ @
/(__)\ @
(__)(__)@@
____ @
( _ \@
) _ <@
(____/@@
___ @
/ __)@
( (__ @
\___)@@
____ @
( _ \ @
)(_) )@
(____/ @@
____ @
( ___)@
)__) @
(____)@@
____ @
( ___)@
)__) @
(__) @@
___ @
/ __)@
( (_-.@
\___/@@
_ _ @
( )_( )@
) _ ( @
(_) (_)@@
____ @
(_ _)@
_)(_ @
(____)@@
____ @
(_ _)@
.-_)( @
\____) @@
_ _ @
( )/ )@
) ( @
(_)\_)@@
__ @
( ) @
)(__ @
(____)@@
__ __ @
( \/ )@
) ( @
(_/\/\_)@@
_ _ @
( \( )@
) ( @
(_)\_)@@
_____ @
( _ )@
)(_)( @
(_____)@@
____ @
( _ \@
)___/@
(__) @@
_____ @
( _ )@
)(_)( @
(___/\\@@
____ @
( _ \@
) /@
(_)\_)@@
___ @
/ __)@
\__ \@
(___/@@
____ @
(_ _)@
)( @
(__) @@
__ __ @
( )( )@
)(__)( @
(______)@@
_ _ @
( \/ )@
\ / @
\/ @@
_ _ @
( \/\/ )@
) ( @
(__/\__)@@
_ _ @
( \/ )@
) ( @
(_/\_)@@
_ _ @
( \/ )@
\ / @
(__) @@
____ @
(_ )@
/ /_ @
(____)@@
__@
| @
| @
|__@@
_ @
( \ @
\ \ @
\_)@@
__ @
|@
|@
__|@@
/ \ @
(_^_)@
@
@@
@
@
___ @
(___)@@
\@
@
@
@@
__ @
/__\ @
/(__)\ @
(__)(__)@@
____ @
( _ \@
) _ <@
(____/@@
___ @
/ __)@
( (__ @
\___)@@
____ @
( _ \ @
)(_) )@
(____/ @@
____ @
( ___)@
)__) @
(____)@@
____ @
( ___)@
)__) @
(__) @@
___ @
/ __)@
( (_-.@
\___/@@
_ _ @
( )_( )@
) _ ( @
(_) (_)@@
____ @
(_ _)@
_)(_ @
(____)@@
____ @
(_ _)@
.-_)( @
\____) @@
_ _ @
( )/ )@
) ( @
(_)\_)@@
__ @
( ) @
)(__ @
(____)@@
__ __ @
( \/ )@
) ( @
(_/\/\_)@@
_ _ @
( \( )@
) ( @
(_)\_)@@
_____ @
( _ )@
)(_)( @
(_____)@@
____ @
( _ \@
)___/@
(__) @@
_____ @
( _ )@
)(_)( @
(___/\\@@
____ @
( _ \@
) /@
(_)\_)@@
___ @
/ __)@
\__ \@
(___/@@
____ @
(_ _)@
)( @
(__) @@
__ __ @
( )( )@
)(__)( @
(______)@@
_ _ @
( \/ )@
\ / @
\/ @@
_ _ @
( \/\/ )@
) ( @
(__/\__)@@
_ _ @
( \/ )@
) ( @
(_/\_)@@
_ _ @
( \/ )@
\ / @
(__) @@
____ @
(_ )@
/ /_ @
(____)@@
,-@
_| @
| @
`-@@
/\@
||@
||@
\/@@
-. @
|_@
| @
-' @@
@
/\/@
@
@@
(_)(_) @
/__\ @
/(__)\ @
(__)(__)@@
(_)_(_)@
( _ )@
)(_)( @
(_____)@@
(_)(_) @
( )( )@
)(__)( @
(______)@@
(_)(_) @
/__\ @
/(__)\ @
(__)(__)@@
(_)_(_)@
( _ )@
)(_)( @
(_____)@@
(_)(_) @
( )( )@
)(__)( @
(______)@@
___ @
/ _ )@
| _ \@
| __/@@
160 NO-BREAK SPACE
$@
$@
$@
$@@
@@ -0,0 +1 @@
{"version":3,"file":"escape.d.ts","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,WAAW,EAAE,MAAiC,CAAC;AAW5D,eAAO,MAAM,YAAY,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,MAWoB,CAAC;AAE9E;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CA0B/C;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,MAAM,EAAE,OAAO,SAAqB,CAAC;AAqClD;;;;;;GAMG;AACH,eAAO,MAAM,UAAU,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAG1C,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,eAAe,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAQ3C,CAAC;AAEN;;;;;GAKG;AACH,eAAO,MAAM,UAAU,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAQ1C,CAAC"}
@@ -0,0 +1,123 @@
{
"name": "@typescript-eslint/eslint-plugin",
"version": "8.58.2",
"description": "TypeScript plugin for ESLint",
"files": [
"dist",
"!**/*.tsbuildinfo",
"index.d.ts",
"raw-plugin.d.ts",
"rules.d.ts",
"package.json",
"./README.md",
"LICENSE"
],
"type": "commonjs",
"exports": {
".": {
"types": "./index.d.ts",
"default": "./dist/index.js"
},
"./package.json": "./package.json",
"./use-at-your-own-risk/rules": {
"types": "./rules.d.ts",
"default": "./dist/rules/index.js"
},
"./use-at-your-own-risk/raw-plugin": {
"types": "./raw-plugin.d.ts",
"default": "./dist/raw-plugin.js"
}
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"repository": {
"type": "git",
"url": "https://github.com/typescript-eslint/typescript-eslint.git",
"directory": "packages/eslint-plugin"
},
"bugs": {
"url": "https://github.com/typescript-eslint/typescript-eslint/issues"
},
"homepage": "https://typescript-eslint.io/packages/eslint-plugin",
"license": "MIT",
"keywords": [
"eslint",
"eslintplugin",
"eslint-plugin",
"typescript"
],
"dependencies": {
"@eslint-community/regexpp": "^4.12.2",
"ignore": "^7.0.5",
"natural-compare": "^1.4.0",
"ts-api-utils": "^2.5.0",
"@typescript-eslint/scope-manager": "8.58.2",
"@typescript-eslint/type-utils": "8.58.2",
"@typescript-eslint/utils": "8.58.2",
"@typescript-eslint/visitor-keys": "8.58.2"
},
"devDependencies": {
"@types/json-schema": "^7.0.15",
"@types/mdast": "^4.0.4",
"@types/natural-compare": "^1.4.3",
"@types/react": "^18.3.21",
"@vitest/coverage-v8": "^4.0.18",
"ajv": "^6.12.6",
"eslint": "^10.0.0",
"json-schema": "^0.4.0",
"markdown-table": "^3.0.4",
"marked": "^15.0.12",
"mdast-util-from-markdown": "^2.0.2",
"mdast-util-mdx": "^3.0.0",
"micromark-extension-mdxjs": "^3.0.0",
"prettier": "3.8.0",
"rimraf": "^5.0.10",
"title-case": "^4.3.2",
"tsx": "^4.7.2",
"typescript": ">=4.8.4 <6.1.0",
"unist-util-visit": "^5.0.0",
"vitest": "^4.0.18",
"@typescript-eslint/rule-schema-to-typescript-types": "8.58.2",
"@typescript-eslint/rule-tester": "8.58.2"
},
"peerDependencies": {
"eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
"typescript": ">=4.8.4 <6.1.0",
"@typescript-eslint/parser": "^8.58.2"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"nx": {
"name": "eslint-plugin",
"includedScripts": [
"clean"
],
"targets": {
"generate-breaking-changes": {
"command": "tsx tools/generate-breaking-changes.mts",
"options": {
"cwd": "{projectRoot}"
},
"dependsOn": [
"type-utils:build"
]
},
"lint": {
"command": "eslint"
}
}
},
"scripts": {
"build": "pnpm -w exec nx build",
"clean": "rimraf dist/ coverage/",
"format": "pnpm -w run format",
"generate-breaking-changes": "tsx tools/generate-breaking-changes.mts",
"generate-configs": "pnpm -w run generate-configs",
"lint": "pnpm -w exec nx lint",
"test": "pnpm -w exec nx test",
"typecheck": "pnpm -w exec nx typecheck"
}
}
@@ -0,0 +1 @@
{"version":3,"file":"dialects-BGO_ZrYF.cjs","names":["DRAFT_2020_12_URIS: ReadonlySet<string>","DRAFT_2019_09_URIS: ReadonlySet<string>","DRAFT_07_URIS: ReadonlySet<string>","DRAFT_06_URIS: ReadonlySet<string>"],"sources":["../../core-internal/src/validators/dialects.ts"],"sourcesContent":["/**\n * Declared-dialect classification shared by the default validator providers.\n */\n\nimport type { JsonSchemaType } from './types';\n\n/**\n * Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped).\n */\nconst DRAFT_2020_12_URIS: ReadonlySet<string> = new Set([\n 'https://json-schema.org/draft/2020-12/schema',\n 'http://json-schema.org/draft/2020-12/schema'\n]);\nconst DRAFT_2019_09_URIS: ReadonlySet<string> = new Set([\n 'https://json-schema.org/draft/2019-09/schema',\n 'http://json-schema.org/draft/2019-09/schema'\n]);\nconst DRAFT_07_URIS: ReadonlySet<string> = new Set(['https://json-schema.org/draft-07/schema', 'http://json-schema.org/draft-07/schema']);\nconst DRAFT_06_URIS: ReadonlySet<string> = new Set(['https://json-schema.org/draft-06/schema', 'http://json-schema.org/draft-06/schema']);\n\n/**\n * Dialects the default providers dispatch on. draft-06 maps to `'draft-7'`: draft-07 only adds\n * keywords over draft-06 (`if`/`then`/`else`), and enforcing them on a draft-06 schema is the\n * accepted downlevel.\n */\nexport type DeclaredDialect = '2020-12' | '2019-09' | 'draft-7';\n\n/**\n * Whether a `$schema` value declares the 2019-09 dialect — the only supported dialect with\n * `$recursiveRef`/`$recursiveAnchor`. Non-throwing (unlike {@linkcode declaredDialect}) so\n * wire-layer callers can consult it for documents whose dialect may be unsupported.\n */\nexport function declares2019Dialect($schema: unknown): boolean {\n return typeof $schema === 'string' && DRAFT_2019_09_URIS.has($schema.replace(/#$/, ''));\n}\n\n/**\n * Classify a schema's declared `$schema` dialect. No `$schema` (or a non-string one) means\n * 2020-12. Any other dialect throws a plain `Error` with a clear message rather than letting the\n * engine crash on an opaque internal error or silently mis-validate; `remedy` names the calling\n * provider's escape hatch in that message.\n */\nexport function declaredDialect(schema: JsonSchemaType, remedy: string): DeclaredDialect {\n if (!('$schema' in schema) || typeof schema.$schema !== 'string') {\n return '2020-12';\n }\n const declared = schema.$schema.replace(/#$/, '');\n if (DRAFT_2020_12_URIS.has(declared)) {\n return '2020-12';\n }\n if (DRAFT_2019_09_URIS.has(declared)) {\n return '2019-09';\n }\n if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) {\n return 'draft-7';\n }\n throw new Error(\n `JSON Schema declares an unsupported dialect (\"$schema\": \"${schema.$schema.slice(0, 200)}\"). ` +\n `The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`\n );\n}\n"],"mappings":";;;;;AASA,MAAMA,qBAA0C,IAAI,IAAI,CACpD,gDACA,8CACH,CAAC;AACF,MAAMC,qBAA0C,IAAI,IAAI,CACpD,gDACA,8CACH,CAAC;AACF,MAAMC,gBAAqC,IAAI,IAAI,CAAC,2CAA2C,yCAAyC,CAAC;AACzI,MAAMC,gBAAqC,IAAI,IAAI,CAAC,2CAA2C,yCAAyC,CAAC;;;;;;AAczI,SAAgB,oBAAoB,SAA2B;AAC3D,QAAO,OAAO,YAAY,YAAY,mBAAmB,IAAI,QAAQ,QAAQ,MAAM,GAAG,CAAC;;;;;;;;AAS3F,SAAgB,gBAAgB,QAAwB,QAAiC;AACrF,KAAI,EAAE,aAAa,WAAW,OAAO,OAAO,YAAY,SACpD,QAAO;CAEX,MAAM,WAAW,OAAO,QAAQ,QAAQ,MAAM,GAAG;AACjD,KAAI,mBAAmB,IAAI,SAAS,CAChC,QAAO;AAEX,KAAI,mBAAmB,IAAI,SAAS,CAChC,QAAO;AAEX,KAAI,cAAc,IAAI,SAAS,IAAI,cAAc,IAAI,SAAS,CAC1D,QAAO;AAEX,OAAM,IAAI,MACN,4DAA4D,OAAO,QAAQ,MAAM,GAAG,IAAI,CAAC,2FACG,SAC/F"}
@@ -0,0 +1 @@
{"version":3,"file":"gallery-vertical-end.js","sources":["../../../src/icons/gallery-vertical-end.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name GalleryVerticalEnd\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNNyAyaDEwIiAvPgogIDxwYXRoIGQ9Ik01IDZoMTQiIC8+CiAgPHJlY3Qgd2lkdGg9IjE4IiBoZWlnaHQ9IjEyIiB4PSIzIiB5PSIxMCIgcng9IjIiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/gallery-vertical-end\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst GalleryVerticalEnd = createLucideIcon('GalleryVerticalEnd', [\n ['path', { d: 'M7 2h10', key: 'nczekb' }],\n ['path', { d: 'M5 6h14', key: 'u2x4p' }],\n ['rect', { width: '18', height: '12', x: '3', y: '10', rx: '2', key: 'l0tzu3' }],\n]);\n\nexport default GalleryVerticalEnd;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAqB,iBAAiB,oBAAsB,CAAA,CAAA,CAAA;AAAA,CAAA,CAChE,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACxC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,SAAS,CAAA,CAAA;AAAA,CAAA,CACvC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAO,MAAM,CAAQ,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAM,CAAG,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,GAAG,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AACjF,CAAC,CAAA,CAAA;;"}
@@ -0,0 +1,9 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
export { default } from './square-arrow-down.js';
//# sourceMappingURL=arrow-down-square.js.map
@@ -0,0 +1,14 @@
"use strict";const _format=require("./shared/confbox.3768c7e9.cjs");function getDefaultExportFromCjs(u){return u&&u.__esModule&&Object.prototype.hasOwnProperty.call(u,"default")?u.default:u}var unicode$1={};unicode$1.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,unicode$1.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-Line truncated
`?(line++,column=0):u?column+=u.length:column++,u&&(pos+=u.length),u}const lexStates={default(){switch(c){case" ":case"\v":case"\f":case" ":case"\xA0":case"\uFEFF":case`
`:case"\r":case"\u2028":case"\u2029":read();return;case"/":read(),lexState="comment";return;case void 0:return read(),newToken("eof")}if(util$1.isSpaceSeparator(c)){read();return}return lexStates[parseState]()},comment(){switch(c){case"*":read(),lexState="multiLineComment";return;case"/":read(),lexState="singleLineComment";return}throw invalidChar(read())},multiLineComment(){switch(c){case"*":read(),lexState="multiLineCommentAsterisk";return;case void 0:throw invalidChar(read())}read()},multiLineCommentAsterisk(){switch(c){case"*":read();return;case"/":read(),lexState="default";return;case void 0:throw invalidChar(read())}read(),lexState="multiLineComment"},singleLineComment(){switch(c){case`
`:case"\r":case"\u2028":case"\u2029":read(),lexState="default";return;case void 0:return read(),newToken("eof")}read()},value(){switch(c){case"{":case"[":return newToken("punctuator",read());case"n":return read(),literal("ull"),newToken("null",null);case"t":return read(),literal("rue"),newToken("boolean",!0);case"f":return read(),literal("alse"),newToken("boolean",!1);case"-":case"+":read()==="-"&&(sign=-1),lexState="sign";return;case".":buffer=read(),lexState="decimalPointLeading";return;case"0":buffer=read(),lexState="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":buffer=read(),lexState="decimalInteger";return;case"I":return read(),literal("nfinity"),newToken("numeric",1/0);case"N":return read(),literal("aN"),newToken("numeric",NaN);case'"':case"'":doubleQuote=read()==='"',buffer="",lexState="string";return}throw invalidChar(read())},identifierNameStartEscape(){if(c!=="u")throw invalidChar(read());read();const u=unicodeEscape();switch(u){case"$":case"_":break;default:if(!util$1.isIdStartChar(u))throw invalidIdentifier();break}buffer+=u,lexState="identifierName"},identifierName(){switch(c){case"$":case"_":case"\u200C":case"\u200D":buffer+=read();return;case"\\":read(),lexState="identifierNameEscape";return}if(util$1.isIdContinueChar(c)){buffer+=read();return}return newToken("identifier",buffer)},identifierNameEscape(){if(c!=="u")throw invalidChar(read());read();const u=unicodeEscape();switch(u){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!util$1.isIdContinueChar(u))throw invalidIdentifier();break}buffer+=u,lexState="identifierName"},sign(){switch(c){case".":buffer=read(),lexState="decimalPointLeading";return;case"0":buffer=read(),lexState="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":buffer=read(),lexState="decimalInteger";return;case"I":return read(),literal("nfinity"),newToken("numeric",sign*(1/0));case"N":return read(),literal("aN"),newToken("numeric",NaN)}throw invalidChar(read())},zero(){switch(c){case".":buffer+=read(),lexState="decimalPoint";return;case"e":case"E":buffer+=read(),lexState="decimalExponent";return;case"x":case"X":buffer+=read(),lexState="hexadecimal";return}return newToken("numeric",sign*0)},decimalInteger(){switch(c){case".":buffer+=read(),lexState="decimalPoint";return;case"e":case"E":buffer+=read(),lexState="decimalExponent";return}if(util$1.isDigit(c)){buffer+=read();return}return newToken("numeric",sign*Number(buffer))},decimalPointLeading(){if(util$1.isDigit(c)){buffer+=read(),lexState="decimalFraction";return}throw invalidChar(read())},decimalPoint(){switch(c){case"e":case"E":buffer+=read(),lexState="decimalExponent";return}if(util$1.isDigit(c)){buffer+=read(),lexState="decimalFraction";return}return newToken("numeric",sign*Number(buffer))},decimalFraction(){switch(c){case"e":case"E":buffer+=read(),lexState="decimalExponent";return}if(util$1.isDigit(c)){buffer+=read();return}return newToken("numeric",sign*Number(buffer))},decimalExponent(){switch(c){case"+":case"-":buffer+=read(),lexState="decimalExponentSign";return}if(util$1.isDigit(c)){buffer+=read(),lexState="decimalExponentInteger";return}throw invalidChar(read())},decimalExponentSign(){if(util$1.isDigit(c)){buffer+=read(),lexState="decimalExponentInteger";return}throw invalidChar(read())},decimalExponentInteger(){if(util$1.isDigit(c)){buffer+=read();return}return newToken("numeric",sign*Number(buffer))},hexadecimal(){if(util$1.isHexDigit(c)){buffer+=read(),lexState="hexadecimalInteger";return}throw invalidChar(read())},hexadecimalInteger(){if(util$1.isHexDigit(c)){buffer+=read();return}return newToken("numeric",sign*Number(buffer))},string(){switch(c){case"\\":read(),buffer+=escape();return;case'"':if(doubleQuote)return read(),newToken("string",buffer);buffer+=read();return;case"'":if(!doubleQuote)return read(),newToken("string",buffer);buffer+=read();return;case`
`:case"\r":throw invalidChar(read());case"\u2028":case"\u2029":separatorChar(c);break;case void 0:throw invalidChar(read())}buffer+=read()},start(){switch(c){case"{":case"[":return newToken("punctuator",read())}lexState="value"},beforePropertyName(){switch(c){case"$":case"_":buffer=read(),lexState="identifierName";return;case"\\":read(),lexState="identifierNameStartEscape";return;case"}":return newToken("punctuator",read());case'"':case"'":doubleQuote=read()==='"',lexState="string";return}if(util$1.isIdStartChar(c)){buffer+=read(),lexState="identifierName";return}throw invalidChar(read())},afterPropertyName(){if(c===":")return newToken("punctuator",read());throw invalidChar(read())},beforePropertyValue(){lexState="value"},afterPropertyValue(){switch(c){case",":case"}":return newToken("punctuator",read())}throw invalidChar(read())},beforeArrayValue(){if(c==="]")return newToken("punctuator",read());lexState="value"},afterArrayValue(){switch(c){case",":case"]":return newToken("punctuator",read())}throw invalidChar(read())},end(){throw invalidChar(read())}};function newToken(u,e){return{type:u,value:e,line,column}}function literal(u){for(const e of u){if(peek()!==e)throw invalidChar(read());read()}}function escape(){switch(peek()){case"b":return read(),"\b";case"f":return read(),"\f";case"n":return read(),`
`;case"r":return read(),"\r";case"t":return read()," ";case"v":return read(),"\v";case"0":if(read(),util$1.isDigit(peek()))throw invalidChar(read());return"\0";case"x":return read(),hexEscape();case"u":return read(),unicodeEscape();case`
`:case"\u2028":case"\u2029":return read(),"";case"\r":return read(),peek()===`
`&&read(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw invalidChar(read());case void 0:throw invalidChar(read())}return read()}function hexEscape(){let u="",e=peek();if(!util$1.isHexDigit(e)||(u+=read(),e=peek(),!util$1.isHexDigit(e)))throw invalidChar(read());return u+=read(),String.fromCodePoint(parseInt(u,16))}function unicodeEscape(){let u="",e=4;for(;e-- >0;){const t=peek();if(!util$1.isHexDigit(t))throw invalidChar(read());u+=read()}return String.fromCodePoint(parseInt(u,16))}const parseStates={start(){if(token.type==="eof")throw invalidEOF();push()},beforePropertyName(){switch(token.type){case"identifier":case"string":key=token.value,parseState="afterPropertyName";return;case"punctuator":pop();return;case"eof":throw invalidEOF()}},afterPropertyName(){if(token.type==="eof")throw invalidEOF();parseState="beforePropertyValue"},beforePropertyValue(){if(token.type==="eof")throw invalidEOF();push()},beforeArrayValue(){if(token.type==="eof")throw invalidEOF();if(token.type==="punctuator"&&token.value==="]"){pop();return}push()},afterPropertyValue(){if(token.type==="eof")throw invalidEOF();switch(token.value){case",":parseState="beforePropertyName";return;case"}":pop()}},afterArrayValue(){if(token.type==="eof")throw invalidEOF();switch(token.value){case",":parseState="beforeArrayValue";return;case"]":pop()}},end(){}};function push(){let u;switch(token.type){case"punctuator":switch(token.value){case"{":u={};break;case"[":u=[];break}break;case"null":case"boolean":case"numeric":case"string":u=token.value;break}if(root===void 0)root=u;else{const e=stack[stack.length-1];Array.isArray(e)?e.push(u):Object.defineProperty(e,key,{value:u,writable:!0,enumerable:!0,configurable:!0})}if(u!==null&&typeof u=="object")stack.push(u),Array.isArray(u)?parseState="beforeArrayValue":parseState="beforePropertyName";else{const e=stack[stack.length-1];e==null?parseState="end":Array.isArray(e)?parseState="afterArrayValue":parseState="afterPropertyValue"}}function pop(){stack.pop();const u=stack[stack.length-1];u==null?parseState="end":Array.isArray(u)?parseState="afterArrayValue":parseState="afterPropertyValue"}function invalidChar(u){return syntaxError(u===void 0?`JSON5: invalid end of input at ${line}:${column}`:`JSON5: invalid character '${formatChar(u)}' at ${line}:${column}`)}function invalidEOF(){return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)}function invalidIdentifier(){return column-=5,syntaxError(`JSON5: invalid identifier character at ${line}:${column}`)}function separatorChar(u){console.warn(`JSON5: '${formatChar(u)}' in strings is not valid ECMAScript; consider escaping`)}function formatChar(u){const e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[u])return e[u];if(u<" "){const t=u.charCodeAt(0).toString(16);return"\\x"+("00"+t).substring(t.length)}return u}function syntaxError(u){const e=new SyntaxError(u);return e.lineNumber=line,e.columnNumber=column,e}const o=getDefaultExportFromCjs(parse),util=util$2;var stringify=function(e,t,C){const s=[];let E="",f,h,l="",g;if(t!=null&&typeof t=="object"&&!Array.isArray(t)&&(C=t.space,g=t.quote,t=t.replacer),typeof t=="function")h=t;else if(Array.isArray(t)){f=[];for(const F of t){let r;typeof F=="string"?r=F:(typeof F=="number"||F instanceof String||F instanceof Number)&&(r=String(F)),r!==void 0&&f.indexOf(r)<0&&f.push(r)}}return C instanceof Number?C=Number(C):C instanceof String&&(C=String(C)),typeof C=="number"?C>0&&(C=Math.min(10,Math.floor(C)),l=" ".substr(0,C)):typeof C=="string"&&(l=C.substr(0,10)),m("",{"":e});function m(F,r){let D=r[F];switch(D!=null&&(typeof D.toJSON5=="function"?D=D.toJSON5(F):typeof D.toJSON=="function"&&(D=D.toJSON(F))),h&&(D=h.call(r,F,D)),D instanceof Number?D=Number(D):D instanceof String?D=String(D):D instanceof Boolean&&(D=D.valueOf()),D){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof D=="string")return p(D);if(typeof D=="number")return String(D);if(typeof D=="object")return Array.isArray(D)?b(D):y(D)}function p(F){const r={"'":.1,'"':.2},D={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};let n="";for(let A=0;A<F.length;A++){const B=F[A];switch(B){case"'":case'"':r[B]++,n+=B;continue;case"\0":if(util.isDigit(F[A+1])){n+="\\x00";continue}}if(D[B]){n+=D[B];continue}if(B<" "){let d=B.charCodeAt(0).toString(16);n+="\\x"+("00"+d).substring(d.length);continue}n+=B}const i=g||Object.keys(r).reduce((A,B)=>r[A]<r[B]?A:B);return n=n.replace(new RegExp(i,"g"),D[i]),i+n+i}function y(F){if(s.indexOf(F)>=0)throw TypeError("Converting circular structure to JSON5");s.push(F);let r=E;E=E+l;let D=f||Object.keys(F),n=[];for(const A of D){const B=m(A,F);if(B!==void 0){let d=w(A)+":";l!==""&&(d+=" "),d+=B,n.push(d)}}let i;if(n.length===0)i="{}";else{let A;if(l==="")A=Line truncated
`+E;A=n.join(B),i=`{
`+E+A+`,
`+r+"}"}}return s.pop(),E=r,i}function w(F){if(F.length===0)return p(F);const r=String.fromCodePoint(F.codePointAt(0));if(!util.isIdStartChar(r))return p(F);for(let D=r.length;D<F.length;D++)if(!util.isIdContinueChar(String.fromCodePoint(F.codePointAt(D))))return p(F);return F}function b(F){if(s.indexOf(F)>=0)throw TypeError("Converting circular structure to JSON5");s.push(F);let r=E;E=E+l;let D=[];for(let i=0;i<F.length;i++){const A=m(String(i),F);D.push(A!==void 0?A:"null")}let n;if(D.length===0)n="[]";else if(l==="")n="["+D.join(",")+"]";else{let i=`,
`+E,A=D.join(i);n=`[
`+E+A+`,
`+r+"]"}return s.pop(),E=r,n}};const a=getDefaultExportFromCjs(stringify);function parseJSON5(u,e){const t=o(u,e?.reviver);return _format.storeFormat(u,t,e),t}function stringifyJSON5(u,e){const t=_format.getFormat(u,e),C=a(u,e?.replacer,t.indent);return t.whitespace.start+C+t.whitespace.end}exports.parseJSON5=parseJSON5,exports.stringifyJSON5=stringifyJSON5;
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 Tinylibs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,106 @@
# base-log-factory
[![npm package](https://nodei.co/npm/base-log-factory.png?downloads=true&downloadRank=true&stars=true)](https://www.npmjs.com/package/base-log-factory)
[![NPM version](https://img.shields.io/npm/v/base-log-factory.svg?style=flat)](https://npmjs.org/package/base-log-factory)
[![NPM Downloads](https://img.shields.io/npm/dm/base-log-factory.svg?style=flat)](https://npmjs.org/package/base-log-factory)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![TypeScript](https://img.shields.io/badge/lang-TypeScript-007ACC.svg)](https://www.typescriptlang.org/)
> 🚀 A flexible and simple JS logging library that allows logging or collecting logs in different environments by configuring various Appenders. Suitable for browser, NodeJS and other environments.
---
## 🌟 Core Features
- **Multi-level logging**
Supports `TRACE/DEBUG/INFO/WARN/ERROR/FATAL/OFF` with precise control over log granularity.
- **Flexible Appender Configuration**
Built-in `ConsoleAppender`, `FileAppender` (size-based rolling), `DateFileAppender` (date-based rolling), and custom Appender extensions.
- **Rich Formatting Options**
Provides `BasicLayout` and `PatternLayout` (similar to Log4j) with customizable placeholders.
- **Context Management**
Supports Mapped Diagnostic Context (MDC) for attaching request IDs, user information, etc.
---
## 📅 Documentation
For detailed usage instructions and API references, please visit the official documentation:
👉 [View Full Documentation](https://fengxinming.github.io/base-log-factory/)
---
## 🚀 Quick Start
### 1. Installation
```bash
npm install base-log-factory
```
### 2. Basic Usage
```typescript
// factory.ts
import { LogFactory, ConsoleAppender } from 'base-log-factory';
export default new LogFactory({
appenders: [new ConsoleAppender()]
});
// main.ts
import logFactory from './factory';
const logger = logFactory.getLogger('app');
logger.info('Server started successfully');
```
---
## 🛠 Core Concepts
### 1. Log Levels (with color coding)
| Level | Value | Description | Recommended Use Cases |
|---------|-------|---------------------------|-------------------------------------|
| **TRACE** | 6 | Detailed tracking logs | Debugging code flow |
| **DEBUG** | 5 | Debugging information | Development-stage debugging |
| **INFO** | 4 | Operational information | Key business process milestones |
| **WARN** | 3 | Non-critical issues | Resource warnings (e.g., low memory)|
| **ERROR** | 2 | Error events | Failed operations |
| **FATAL** | 1 | Critical system failures | System crashes |
| OFF | 0 | Disable all logging | Disable logging |
### 2. Appender Comparison
| Type | Features | Use Cases |
|--------------------|-----------------------------------|---------------------------|
| `ConsoleAppender` | Realtime console output | Development debugging |
| `FileAppender` | Size-based rolling (e.g., app.log.1)| Production logging |
| `DateFileAppender` | Date-based rolling (e.g., app.2023-08-01.log)| Daily log archiving |
---
## 📝 Contribution Guide
1. **Development Setup**
```bash
npm install
```
2. **Testing**
```bash
npm test # Run unit tests
```
3. **Before Submitting PRs**
- Ensure ESLint is configured (VSCode plugin recommended)
- Add test cases for new features
- Update documentation
---
## 📄 License
[MIT License](../../LICENSE)
@@ -0,0 +1 @@
{"version":3,"file":"follow-value.mjs","sources":["../../../src/value/follow-value.ts"],"sourcesContent":["import { MotionValue, motionValue } from \".\"\nimport { JSAnimation } from \"../animation/JSAnimation\"\nimport { AnyResolvedKeyframe, ValueAnimationTransition } from \"../animation/types\"\nimport { frame } from \"../frameloop\"\nimport { isMotionValue } from \"./utils/is-motion-value\"\n\n/**\n * Options for useFollowValue hook, extending ValueAnimationTransition\n * but excluding lifecycle callbacks that don't make sense for the hook pattern.\n */\nexport type FollowValueOptions = Omit<\n ValueAnimationTransition,\n \"onUpdate\" | \"onComplete\" | \"onPlay\" | \"onRepeat\" | \"onStop\"\n> & {\n /**\n * When true, the first change from a tracked `MotionValue` source\n * will jump to the new value instead of animating. Subsequent\n * changes animate normally. This prevents unwanted animations\n * on page refresh or back navigation (e.g. `useScroll` + `useSpring`).\n *\n * @default false\n */\n skipInitialAnimation?: boolean\n}\n\n/**\n * Create a `MotionValue` that animates to its latest value using any transition type.\n * Can either be a value or track another `MotionValue`.\n *\n * ```jsx\n * const x = motionValue(0)\n * const y = followValue(x, { type: \"spring\", stiffness: 300 })\n * // or with tween\n * const z = followValue(x, { type: \"tween\", duration: 0.5, ease: \"easeOut\" })\n * ```\n *\n * @param source - Initial value or MotionValue to track\n * @param options - Animation transition options\n * @returns `MotionValue`\n *\n * @public\n */\nexport function followValue<T extends AnyResolvedKeyframe>(\n source: T | MotionValue<T>,\n options?: FollowValueOptions\n) {\n const initialValue = isMotionValue(source) ? source.get() : source\n const value = motionValue(initialValue)\n\n attachFollow(value, source, options)\n\n return value\n}\n\n/**\n * Attach an animation to a MotionValue that will animate whenever the value changes.\n * Similar to attachSpring but supports any transition type (spring, tween, inertia, etc.)\n *\n * @param value - The MotionValue to animate\n * @param source - Initial value or MotionValue to track\n * @param options - Animation transition options\n * @returns Cleanup function\n *\n * @public\n */\nexport function attachFollow<T extends AnyResolvedKeyframe>(\n value: MotionValue<T>,\n source: T | MotionValue<T>,\n options: FollowValueOptions = {}\n): VoidFunction {\n const initialValue = value.get()\n\n let activeAnimation: JSAnimation<number> | null = null\n let latestValue = initialValue\n let latestSetter: (v: T) => void\n\n const unit =\n typeof initialValue === \"string\"\n ? initialValue.replace(/[\\d.-]/g, \"\")\n : undefined\n\n const stopAnimation = () => {\n if (activeAnimation) {\n activeAnimation.stop()\n activeAnimation = null\n }\n value.animation = undefined\n }\n\n const startAnimation = () => {\n const currentValue = asNumber(value.get())\n const targetValue = asNumber(latestValue)\n\n // Don't animate if we're already at the target\n if (currentValue === targetValue) {\n stopAnimation()\n return\n }\n\n // Use the running animation's analytical velocity for accuracy,\n // falling back to the MotionValue's velocity for the initial animation.\n // This prevents systematic velocity loss at high frame rates (240hz+).\n const velocity = activeAnimation\n ? activeAnimation.getGeneratorVelocity()\n : value.getVelocity()\n\n stopAnimation()\n\n activeAnimation = new JSAnimation({\n keyframes: [currentValue, targetValue],\n velocity,\n // Default to spring if no type specified (matches useSpring behavior)\n type: \"spring\",\n restDelta: 0.001,\n restSpeed: 0.01,\n ...options,\n onUpdate: latestSetter,\n })\n }\n\n // Use a stable function reference so the frame loop Set deduplicates\n // multiple calls within the same frame (e.g. rapid mouse events)\n const scheduleAnimation = () => {\n startAnimation()\n value.animation = activeAnimation ?? undefined\n value[\"events\"].animationStart?.notify()\n activeAnimation?.then(() => {\n value.animation = undefined\n value[\"events\"].animationComplete?.notify()\n })\n }\n\n value.attach((v, set) => {\n latestValue = v\n latestSetter = (latest) => set(parseValue(latest, unit) as T)\n frame.postRender(scheduleAnimation)\n }, stopAnimation)\n\n if (isMotionValue(source)) {\n let skipNextAnimation = options.skipInitialAnimation === true\n\n const removeSourceOnChange = source.on(\"change\", (v) => {\n if (skipNextAnimaLine truncated
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"_E"},B:{"1":"_9C","2":"_aB"},C:{"1":"_pF","2":"_WR"},D:{"1":"_OJ _KE","2":"_9E _hD"},E:{"1":"_JB","2":"_RB"},F:{"1":"_7R","2":"_JP"},G:{"1":"_9","2":"_iB"},H:{"2":"1D"},I:{"1":"I","2":"_G"},J:{"2":"_B"},K:{"1":"H","2":"_D"},L:{"1":"I"},M:{"1":"YC"},N:{"2":"_A"},O:{"1":"bC"},P:{"1":"_U","2":"J"},Q:{"1":"JE"},R:{"1":"KE"},S:{"1":"ME","2":"LE"}},B:1,C:"Minimum length attribute for input fields",D:true};
@@ -0,0 +1 @@
{"version":3,"file":"create-visual-element.mjs","sources":["../../../../src/render/dom/create-visual-element.ts"],"sourcesContent":["import { HTMLVisualElement, SVGVisualElement } from \"motion-dom\"\nimport { ComponentType, Fragment } from \"react\"\nimport { CreateVisualElement, VisualElementOptions } from \"../types\"\nimport { isSVGComponent } from \"./utils/is-svg-component\"\n\nexport const createDomVisualElement: CreateVisualElement = (\n Component: string | ComponentType<React.PropsWithChildren<unknown>>,\n options: VisualElementOptions<HTMLElement | SVGElement>\n) => {\n /**\n * Use explicit isSVG override if provided, otherwise auto-detect\n */\n const isSVG = options.isSVG ?? isSVGComponent(Component)\n\n return isSVG\n ? new SVGVisualElement(options)\n : new HTMLVisualElement(options, {\n allowProjection: Component !== Fragment,\n })\n}\n"],"names":[],"mappings":";;;;MAKa,sBAAsB,GAAwB,CACvD,SAAmE,EACnE,OAAuD,KACvD;AACA;;AAEG;IACH,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,cAAc,CAAC,SAAS,CAAC;AAExD,IAAA,OAAO;AACH,UAAE,IAAI,gBAAgB,CAAC,OAAO;AAC9B,UAAE,IAAI,iBAAiB,CAAC,OAAO,EAAE;YAC3B,eAAe,EAAE,SAAS,KAAK,QAAQ;AAC1C,SAAA,CAAC;AACZ;;;;"}
@@ -0,0 +1,23 @@
(The MIT License)
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
Copyright (c) 2014-2015 Douglas Christopher Wilson <doug@somethingdoug.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,55 @@
import Benchmark from "benchmark";
import { z } from "zod/v3";
const SUITE_NAME = "z.string";
const suite = new Benchmark.Suite(SUITE_NAME);
const empty = "";
const short = "short";
const long = "long".repeat(256);
const manual = (str: unknown) => {
if (typeof str !== "string") {
throw new Error("Not a string");
}
return str;
};
const stringSchema = z.string();
const optionalStringSchema = z.string().optional();
const optionalNullableStringSchema = z.string().optional().nullable();
suite
.add("empty string", () => {
stringSchema.parse(empty);
})
.add("short string", () => {
stringSchema.parse(short);
})
.add("long string", () => {
stringSchema.parse(long);
})
.add("optional string", () => {
optionalStringSchema.parse(long);
})
.add("nullable string", () => {
optionalNullableStringSchema.parse(long);
})
.add("nullable (null) string", () => {
optionalNullableStringSchema.parse(null);
})
.add("invalid: null", () => {
try {
stringSchema.parse(null);
} catch (_err) {}
})
.add("manual parser: long", () => {
manual(long);
})
.on("cycle", (e: Benchmark.Event) => {
console.log(`${SUITE_NAME}: ${e.target}`);
});
export default {
suites: [suite],
};
@@ -0,0 +1,88 @@
/**
* @license React
* use-sync-external-store-shim.native.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
"use strict";
"production" !== process.env.NODE_ENV &&
(function () {
function is(x, y) {
return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
}
function useSyncExternalStore$1(subscribe, getSnapshot) {
didWarnOld18Alpha ||
void 0 === React.startTransition ||
((didWarnOld18Alpha = !0),
console.error(
"You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."
));
var value = getSnapshot();
if (!didWarnUncachedGetSnapshot) {
var cachedValue = getSnapshot();
objectIs(value, cachedValue) ||
(console.error(
"The result of getSnapshot should be cached to avoid an infinite loop"
),
(didWarnUncachedGetSnapshot = !0));
}
cachedValue = useState({
inst: { value: value, getSnapshot: getSnapshot }
});
var inst = cachedValue[0].inst,
forceUpdate = cachedValue[1];
useLayoutEffect(
function () {
inst.value = value;
inst.getSnapshot = getSnapshot;
checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
},
[subscribe, value, getSnapshot]
);
useEffect(
function () {
checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
return subscribe(function () {
checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
});
},
[subscribe]
);
useDebugValue(value);
return value;
}
function checkIfSnapshotChanged(inst) {
var latestGetSnapshot = inst.getSnapshot;
inst = inst.value;
try {
var nextValue = latestGetSnapshot();
return !objectIs(inst, nextValue);
} catch (error) {
return !0;
}
}
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
"function" ===
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
var React = require("react"),
objectIs = "function" === typeof Object.is ? Object.is : is,
useState = React.useState,
useEffect = React.useEffect,
useLayoutEffect = React.useLayoutEffect,
useDebugValue = React.useDebugValue,
didWarnOld18Alpha = !1,
didWarnUncachedGetSnapshot = !1;
exports.useSyncExternalStore =
void 0 !== React.useSyncExternalStore
? React.useSyncExternalStore
: useSyncExternalStore$1;
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
"function" ===
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
})();
@@ -0,0 +1,582 @@
import { expect, expectTypeOf, test } from "vitest";
import { en } from "zod/locales";
import * as z from "zod/mini";
z.config(en());
const isoDateCodec = z.codec(
z.iso.datetime(), // Input: ISO string (validates to string)
z.date(), // Output: Date object
{
decode: (isoString) => new Date(isoString), // Forward: ISO string → Date
encode: (date) => date.toISOString(), // Backward: Date → ISO string
}
);
test("instanceof", () => {
expect(isoDateCodec instanceof z.ZodMiniCodec).toBe(true);
expect(isoDateCodec instanceof z.ZodMiniPipe).toBe(true);
expect(isoDateCodec instanceof z.ZodMiniType).toBe(true);
expect(isoDateCodec instanceof z.core.$ZodCodec).toBe(true);
expect(isoDateCodec instanceof z.core.$ZodPipe).toBe(true);
expect(isoDateCodec instanceof z.core.$ZodType).toBe(true);
expectTypeOf(isoDateCodec.def).toEqualTypeOf<z.core.$ZodCodecDef<z.ZodMiniISODateTime, z.ZodMiniDate<Date>>>();
});
test("codec basic functionality", () => {
// ISO string -> Date codec using z.iso.datetime() for input validation
const testIsoString = "2024-01-15T10:30:00.000Z";
const testDate = new Date("2024-01-15T10:30:00.000Z");
// Forward decoding (ISO string -> Date)
const decodedResult = z.decode(isoDateCodec, testIsoString);
expect(decodedResult).toBeInstanceOf(Date);
expect(decodedResult.toISOString()).toMatchInlineSnapshot(`"2024-01-15T10:30:00.000Z"`);
// Backward encoding (Date -> ISO string)
const encodedResult = z.encode(isoDateCodec, testDate);
expect(typeof encodedResult).toBe("string");
expect(encodedResult).toMatchInlineSnapshot(`"2024-01-15T10:30:00.000Z"`);
});
test("codec round trip", () => {
const isoDateCodec = z.codec(z.iso.datetime(), z.date(), {
decode: (isoString) => new Date(isoString),
encode: (date) => date.toISOString(),
});
const original = "2024-12-25T15:45:30.123Z";
const toDate = z.decode(isoDateCodec, original);
const backToString = z.encode(isoDateCodec, toDate);
expect(backToString).toMatchInlineSnapshot(`"2024-12-25T15:45:30.123Z"`);
expect(toDate).toBeInstanceOf(Date);
expect(toDate.getTime()).toMatchInlineSnapshot(`1735141530123`);
});
test("codec with refinement", () => {
const isoDateCodec = z
.codec(z.iso.datetime(), z.date(), {
decode: (isoString) => new Date(isoString),
encode: (date) => date.toISOString(),
})
.check(z.refine((val) => val.getFullYear() === 2024, { error: "Year must be 2024" }));
// Valid 2024 date
const validDate = z.decode(isoDateCodec, "2024-01-15T10:30:00.000Z");
expect(validDate.getFullYear()).toMatchInlineSnapshot(`2024`);
expect(validDate.getTime()).toMatchInlineSnapshot(`1705314600000`);
// Invalid year should fail safely
const invalidYearResult = z.safeDecode(isoDateCodec, "2023-01-15T10:30:00.000Z");
expect(invalidYearResult.success).toBe(false);
if (!invalidYearResult.success) {
expect(invalidYearResult.error.issues).toMatchInlineSnapshot(`
[
{
"code": "custom",
"message": "Year must be 2024",
"path": [],
},
]
`);
}
});
test("safe codec operations", () => {
const isoDateCodec = z.codec(z.iso.datetime(), z.date(), {
decode: (isoString) => new Date(isoString),
encode: (date) => date.toISOString(),
});
// Safe decode with invalid input
const safeDecodeResult = z.safeDecode(isoDateCodec, "invalid-date");
expect(safeDecodeResult.success).toBe(false);
if (!safeDecodeResult.success) {
expect(safeDecodeResult.error.issues).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "datetime",
"message": "Invalid ISO datetime",
"origin": "string",
"path": [],
"pattern": "/^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$/",
},
]
`);
}
// Safe decode with valid input
const safeDecodeValid = z.safeDecode(isoDateCodec, "2024-01-15T10:30:00.000Z");
expect(safeDecodeValid.success).toBe(true);
if (safeDecodeValid.success) {
expect(safeDecodeValid.data).toBeInstanceOf(Date);
expect(safeDecodeValid.data.getTime()).toMatchInlineSnapshot(`1705314600000`);
}
// Safe encode with valid input
const safeEncodeResult = z.safeEncode(isoDateCodec, new Date("2024-01-01"));
expect(safeEncodeResult.success).toBe(true);
if (safeEncodeResult.success) {
expect(safeEncodeResult.data).toMatchInlineSnapshot(`"2024-01-01T00:00:00.000Z"`);
}
});
test("codec with different types", () => {
// String -> Number codec
const stringNumberCodec = z.codec(z.string(), z.number(), {
decode: (str) => Number.parseFloat(str),
encode: (num) => num.toString(),
});
const decodedNumber = z.decode(stringNumberCodec, "42.5");
expect(decodedNumber).toMatchInlineSnapshot(`42.5`);
expect(typeof decodedNumber).toBe("number");
const encodedString = z.encode(stringNumberCodec, 42.5);
expect(encodedString).toMatchInlineSnapshot(`"42.5"`);
expect(typeof encodedString).toBe("string");
});
test("async codec operations", async () => {
const isoDateCodec = z.codec(z.iso.datetime(), z.date(), {
decode: (isoString) => new Date(isoString),
encode: (date) => date.toISOString(),
});
// Async decode
const decodedResult = await z.decodeAsync(isoDateCodec, "2024-01-15T10:30:00.000Z");
expect(decodedResult).toBeInstanceOf(Date);
expect(decodedResult.getTime()).toMatchInlineSnapshot(`1705314600000`);
// Async encode
const encodedResult = await z.encodeAsync(isoDateCodec, new Date("2024-01-15T10:30:00.000Z"));
expect(typeof encodedResult).toBe("string");
expect(encodedResult).toMatchInlineSnapshot(`"2024-01-15T10:30:00.000Z"`);
// Safe async operations
const safeDecodeResult = await z.safeDecodeAsync(isoDateCodec, "2024-01-15T10:30:00.000Z");
expect(safeDecodeResult.success).toBe(true);
if (safeDecodeResult.success) {
expect(safeDecodeResult.data.getTime()).toMatchInlineSnapshot(`1705314600000`);
}
const safeEncodeResult = await z.safeEncodeAsync(isoDateCodec, new Date("2024-01-15T10:30:00.000Z"));
expect(safeEncodeResult.success).toBe(true);
if (safeEncodeResult.success) {
expect(safeEncodeResult.data).toMatchInlineSnapshot(`"2024-01-15T10:30:00.000Z"`);
}
});
test("codec type inference", () => {
const codec = z.codec(z.string(), z.number(), {
decode: (str) => Number.parseInt(str),
encode: (num) => num.toString(),
});
// These should compile without type errors
const decoded: number = z.decode(codec, "123");
const encoded: string = z.encode(codec, 123);
expect(decoded).toMatchInlineSnapshot(`123`);
expect(encoded).toMatchInlineSnapshot(`"123"`);
});
test("nested codec with object containing codec property", () => {
// Nested schema: object containing a codec as one of its properties, with refinements at all levels
const waypointSchema = z
.object({
name: z.string().check(z.minLength(1, "Waypoint name required")),
difficulty: z.enum(["easy", "medium", "hard"]),
coordinate: z
.codec(
z
.string()
.check(z.regex(/^-?\d+,-?\d+$/, "Must be 'x,y' format")), // Input: coordinate string
z
.object({ x: z.number(), y: z.number() })
.check(z.refine((coord) => coord.x >= 0 && coord.y >= 0, { error: "Coordinates must be non-negative" })), // Output: coordinate object
{
decode: (coordString: string) => {
const [x, y] = coordString.split(",").map(Number);
return { x, y };
},
encode: (coord: { x: number; y: number }) => `${coord.x},${coord.y}`,
}
)
.check(z.refine((coord) => coord.x <= 1000 && coord.y <= 1000, { error: "Coordinates must be within bounds" })),
})
.check(
z.refine((waypoint) => waypoint.difficulty !== "hard" || waypoint.coordinate.x >= 100, {
error: "Hard waypoints must be at least 100 units from origin",
})
);
// Test data
const inputWaypoint = {
name: "Summit Point",
difficulty: "medium" as const,
coordinate: "150,200",
};
// Forward decoding (object with string coordinate -> object with coordinate object)
const decodedWaypoint = z.decode(waypointSchema, inputWaypoint);
expect(decodedWaypoint).toMatchInlineSnapshot(`
{
"coordinate": {
"x": 150,
"y": 200,
},
"difficulty": "medium",
"name": "Summit Point",
}
`);
// Backward encoding (object with coordinate object -> object with string coordinate)
const encodedWaypoint = z.encode(waypointSchema, decodedWaypoint);
expect(encodedWaypoint).toMatchInlineSnapshot(`
{
"coordinate": "150,200",
"difficulty": "medium",
"name": "Summit Point",
}
`);
// Test refinements at all levels
// String validation (empty waypoint name)
const emptyNameResult = z.safeDecode(waypointSchema, {
name: "",
difficulty: "easy",
coordinate: "10,20",
});
expect(emptyNameResult.success).toBe(false);
if (!emptyNameResult.success) {
expect(emptyNameResult.error.issues).toMatchInlineSnapshot(`
[
{
"code": "too_small",
"inclusive": true,
"message": "Waypoint name required",
"minimum": 1,
"origin": "string",
"path": [
"name",
],
},
]
`);
}
// Enum validation (invalid difficulty)
const invalidDifficultyResult = z.safeDecode(waypointSchema, {
name: "Test Point",
difficulty: "impossible" as any,
coordinate: "10,20",
});
expect(invalidDifficultyResult.success).toBe(false);
if (!invalidDifficultyResult.success) {
expect(invalidDifficultyResult.error.issues).toMatchInlineSnapshot(`
[
{
"code": "invalid_value",
"message": "Invalid option: expected one of "easy"|"medium"|"hard"",
"path": [
"difficulty",
],
"values": [
"easy",
"medium",
"hard",
],
},
]
`);
}
// Codec string format validation (invalid coordinate format)
const invalidFormatResult = z.safeDecode(waypointSchema, {
name: "Test Point",
difficulty: "easy",
coordinate: "invalid",
});
expect(invalidFormatResult.success).toBe(false);
if (!invalidFormatResult.success) {
expect(invalidFormatResult.error.issues).toMatchInlineSnapshot(`
[
{
"code": "invalid_format",
"format": "regex",
"message": "Must be 'x,y' format",
"origin": "string",
"path": [
"coordinate",
],
"pattern": "/^-?\\d+,-?\\d+$/",
},
]
`);
}
// Codec object refinement (negative coordinates)
const negativeCoordResult = z.safeDecode(waypointSchema, {
name: "Test Point",
difficulty: "easy",
coordinate: "-5,10",
});
expect(negativeCoordResult.success).toBe(false);
if (!negativeCoordResult.success) {
expect(negativeCoordResult.error.issues).toMatchInlineSnapshot(`
[
{
"code": "custom",
"message": "Coordinates must be non-negative",
"path": [
"coordinate",
],
},
]
`);
}
// Codec-level refinement (coordinates out of bounds)
const outOfBoundsResult = z.safeDecode(waypointSchema, {
name: "Test Point",
difficulty: "easy",
coordinate: "1500,2000",
});
expect(outOfBoundsResult.success).toBe(false);
if (!outOfBoundsResult.success) {
expect(outOfBoundsResult.error.issues).toMatchInlineSnapshot(`
[
{
"code": "custom",
"message": "Coordinates must be within bounds",
"path": [
"coordinate",
],
},
]
`);
}
// Object-level refinement (hard waypoint too close to origin)
const hardWaypointResult = z.safeDecode(waypointSchema, {
name: "Expert Point",
difficulty: "hard",
coordinate: "50,60", // x < 100, but hard waypoints need x >= 100
});
expect(hardWaypointResult.success).toBe(false);
if (!hardWaypointResult.success) {
expect(hardWaypointResult.error.issues).toMatchInlineSnapshot(`
[
{
"code": "custom",
"message": "Hard waypoints must be at least 100 units from origin",
"path": [],
},
]
`);
}
// Round trip test
const roundTripResult = z.encode(waypointSchema, z.decode(waypointSchema, inputWaypoint));
expect(roundTripResult).toMatchInlineSnapshot(`
{
"coordinate": "150,200",
"difficulty": "medium",
"name": "Summit Point",
}
`);
});
test("mutating refinements", () => {
const A = z.codec(z.string(), z.string().check(z.trim()), {
decode: (val) => val,
encode: (val) => val,
});
expect(z.decode(A, " asdf ")).toMatchInlineSnapshot(`"asdf"`);
expect(z.encode(A, " asdf ")).toMatchInlineSnapshot(`"asdf"`);
});
test("codec type enforcement - correct encode/decode signatures", () => {
// Test that codec functions have correct type signatures
const stringToNumberCodec = z.codec(z.string(), z.number(), {
decode: (value: string) => Number(value), // core.output<A> -> core.input<B>
encode: (value: number) => String(value), // core.input<B> -> core.output<A>
});
// These should compile without errors - correct types (async support)
expectTypeOf<(value: string, payload: z.core.ParsePayload<string>) => z.core.util.MaybeAsync<number>>(
stringToNumberCodec.def.transform
).toBeFunction();
expectTypeOf<(value: number, payload: z.core.ParsePayload<number>) => z.core.util.MaybeAsync<string>>(
stringToNumberCodec.def.reverseTransform
).toBeFunction();
// Test that decode parameter type is core.output<A> (string)
const validDecode = (value: string) => Number(value);
expectTypeOf(validDecode).toMatchTypeOf<(value: string) => number>();
// Test that encode parameter type is core.input<B> (number)
const validEncode = (value: number) => String(value);
expectTypeOf(validEncode).toMatchTypeOf<(value: number) => string>();
z.codec(z.string(), z.number(), {
// @ts-expect-error - decode should NOT accept core.input<A> as parameter
decode: (value: never, _payload) => Number(value), // Wrong: should be string, not unknown
encode: (value: number, _payload) => String(value),
});
z.codec(z.string(), z.number(), {
decode: (value: string) => Number(value),
// @ts-expect-error - encode should NOT accept core.output<B> as parameter
encode: (value: never) => String(value), // Wrong: should be number, not unknown
});
z.codec(z.string(), z.number(), {
// @ts-expect-error - decode return type should be core.input<B>
decode: (value: string) => String(value), // Wrong: should return number, not string
encode: (value: number) => String(value),
});
z.codec(z.string(), z.number(), {
decode: (value: string) => Number(value),
// @ts-expect-error - encode return type should be core.output<A>
encode: (value: number) => Number(value), // Wrong: should return string, not number
});
});
test("async codec functionality", async () => {
// Test that async encode/decode functions work properly
const asyncCodec = z.codec(z.string(), z.number(), {
decode: async (str) => {
await new Promise((resolve) => setTimeout(resolve, 1)); // Simulate async work
return Number.parseFloat(str);
},
encode: async (num) => {
await new Promise((resolve) => setTimeout(resolve, 1)); // Simulate async work
return num.toString();
},
});
// Test async decode/encode
const decoded = await z.decodeAsync(asyncCodec, "42.5");
expect(decoded).toBe(42.5);
const encoded = await z.encodeAsync(asyncCodec, 42.5);
expect(encoded).toBe("42.5");
// Test that both sync and async work
const mixedCodec = z.codec(z.string(), z.number(), {
decode: async (str) => Number.parseFloat(str),
encode: (num) => num.toString(), // sync encode
});
const mixedResult = await z.decodeAsync(mixedCodec, "123");
expect(mixedResult).toBe(123);
});
test("codec type enforcement - complex types", () => {
type User = { id: number; name: string };
type UserInput = { id: string; name: string };
const userCodec = z.codec(
z.object({ id: z.string(), name: z.string() }),
z.object({ id: z.number(), name: z.string() }),
{
decode: (input: UserInput) => ({ id: Number(input.id), name: input.name }),
encode: (user: User) => ({ id: String(user.id), name: user.name }),
}
);
// Verify correct types are inferred (async support)
expectTypeOf<(input: UserInput, payload: z.core.ParsePayload<UserInput>) => z.core.util.MaybeAsync<User>>(
userCodec.def.transform
).toBeFunction();
expectTypeOf<(user: User, payload: z.core.ParsePayload<User>) => z.core.util.MaybeAsync<UserInput>>(
userCodec.def.reverseTransform
).toBeFunction();
z.codec(
z.object({
id: z.string(),
name: z.string(),
}),
z.object({ id: z.number(), name: z.string() }),
{
// @ts-expect-error - decode parameter should be UserInput, not User
decode: (input: User) => ({ id: Number(input.id), name: input.name }), // Wrong type
encode: (user: User) => ({ id: String(user.id), name: user.name }),
}
);
z.codec(
z.object({
id: z.string(),
name: z.string(),
}),
z.object({ id: z.number(), name: z.string() }),
{
decode: (input: UserInput) => ({ id: Number(input.id), name: input.name }),
// @ts-expect-error - encode parameter should be User, not UserInput
encode: (user: UserInput) => ({ id: String(user.id), name: user.name }), // Wrong type
}
);
});
test("invertCodec", () => {
const inverted = z.invertCodec(isoDateCodec);
type InvIn = z.input<typeof inverted>;
type InvOut = z.output<typeof inverted>;
expectTypeOf<InvIn>().toEqualTypeOf<Date>();
expectTypeOf<InvOut>().toEqualTypeOf<string>();
const testDate = new Date("2024-01-15T10:30:00.000Z");
expect(z.decode(inverted, testDate)).toBe("2024-01-15T10:30:00.000Z");
const encoded = z.encode(inverted, "2024-01-15T10:30:00.000Z");
expect(encoded).toBeInstanceOf(Date);
expect(encoded.toISOString()).toBe("2024-01-15T10:30:00.000Z");
const doubleInverted = z.invertCodec(z.invertCodec(isoDateCodec));
expect(z.decode(doubleInverted, "2024-01-15T10:30:00.000Z")).toBeInstanceOf(Date);
});
test("z.output carries checks attached to a pipe", () => {
const c = z
.codec(z.string(), z.number(), { decode: Number, encode: String })
.check(z.refine((n) => n > 10, { error: "gt10" }));
expect(z.output(c).parse(50)).toBe(50);
expect(() => z.output(c).parse(5)).toThrow("gt10");
// The input side drops it: the check constrains a value that side never produces.
expect(z.input(c).parse("5")).toBe("5");
});
test("z.input resolves past a transform piped into a schema", () => {
const p = z.pipe(
z.transform((v: unknown) => String(v)),
z.string().check(z.minLength(5))
);
expect(z.input(p).parse("abcde")).toBe("abcde");
expect(() => z.input(p).parse(1)).toThrow();
});
test("a wrapper's stored value survives only on the side it belongs to", () => {
const c = z.codec(z.string(), z.number(), { decode: Number, encode: String });
expect(z.input(z._default(c, 7)).parse(undefined)).toBe(undefined);
expect(z.output(z._default(c, 7)).parse(undefined)).toBe(7);
// A wrapper over a pipe-free schema keeps both its value and its identity.
const plain = z._default(z.string(), "x");
expect(z.input(plain)).toBe(plain);
expect(z.input(plain).parse(undefined)).toBe("x");
});
@@ -0,0 +1,10 @@
'use strict';
var _const = require('../../data/const.cjs');
var separatorMatcher = () => {
return _const.SEPERATOR_CHAR_COUNT;
};
module.exports = separatorMatcher;
//# sourceMappingURL=scoring.cjs.map
@@ -0,0 +1,38 @@
import { AnyRouter } from './router.js';
import { ParsedLocation } from './location.js';
import { NonNullableUpdater } from './utils.js';
export type ScrollRestorationEntry = {
scrollX: number;
scrollY: number;
};
type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>;
type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>;
type ScrollRestorationCache = {
readonly state: ScrollRestorationByKey;
set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void;
persist: () => void;
};
export type ScrollRestorationOptions = {
getKey?: (location: ParsedLocation) => string;
scrollBehavior?: ScrollToOptions['behavior'];
};
export declare const storageKey = "tsr-scroll-restoration-v1_3";
export declare const scrollRestorationCache: ScrollRestorationCache | null;
/**
* The default `getKey` function for `useScrollRestoration`.
* It returns the `key` from the location state or the `href` of the location.
*
* The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.
*/
export declare const defaultGetScrollRestorationKey: (location: ParsedLocation) => string;
export declare function getElementScrollRestorationEntry(router: AnyRouter, options: ({
id: string;
getElement?: () => Window | Element | undefined | null;
} | {
id?: string;
getElement: () => Window | Element | undefined | null;
}) & {
getKey?: (location: ParsedLocation) => string;
}): ScrollRestorationEntry | undefined;
export declare function setupScrollRestoration(router: AnyRouter, force?: boolean): void;
export {};
@@ -0,0 +1,207 @@
[![npm version](https://img.shields.io/npm/v/eslint-scope.svg)](https://www.npmjs.com/package/eslint-scope)
[![Downloads](https://img.shields.io/npm/dm/eslint-scope.svg)](https://www.npmjs.com/package/eslint-scope)
[![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/eslint/js/actions)
# ESLint Scope
ESLint Scope is the [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) scope analyzer used in ESLint. It is a fork of [escope](http://github.com/estools/escope).
## Install
```
npm i eslint-scope --save
```
## 📖 Usage
To use in an ESM file:
```js
import * as eslintScope from "eslint-scope";
```
To use in a CommonJS file:
```js
const eslintScope = require("eslint-scope");
```
In order to analyze scope, you'll need to have an [ESTree](https://github.com/estree/estree) compliant AST structure to run it on. The primary method is `eslintScope.analyze()`, which takes two arguments:
1. `ast` - the ESTree-compliant AST structure to analyze.
2. `options` (optional) - Options to adjust how the scope is analyzed, including:
- `ignoreEval` (default: `false`) - Set to `true` to ignore all `eval()` calls (which would normally create scopes).
- `nodejsScope` (default: `false`) - Set to `true` to create a top-level function scope needed for CommonJS evaluation.
- `impliedStrict` (default: `false`) - Set to `true` to evaluate the code in strict mode even outside of modules and without `"use strict"`.
- `ecmaVersion` (default: `5`) - The version of ECMAScript to use to evaluate the code.
- `sourceType` (default: `"script"`) - The type of JavaScript file to evaluate. Change to `"module"` for ECMAScript module code.
- `childVisitorKeys` (default: `null`) - An object with visitor key information (like [`eslint-visitor-keys`](https://github.com/eslint/js/tree/main/packages/eslint-visitor-keys)). Without this, `eslint-scope` finds child nodes to visit algorithmically. Providing this option is a performance enhancement.
- `fallback` (default: `"iteration"`) - The strategy to use when `childVisitorKeys` is not specified. May be a function.
- `optimistic` (default: `false`) - Set to `true` to enable optimistic scope analysis.
- `jsx` (default: `false`) - Enables the tracking of JSX components as variable references.
Example:
```js
import * as eslintScope from "eslint-scope";
import * as espree from "espree";
import estraverse from "estraverse";
const options = {
ecmaVersion: 2022,
sourceType: "module",
};
const ast = espree.parse(code, { range: true, ...options });
const scopeManager = eslintScope.analyze(ast, options);
const currentScope = scopeManager.acquire(ast); // global scope
estraverse.traverse(ast, {
enter(node, parent) {
// do stuff
if (/Function/.test(node.type)) {
currentScope = scopeManager.acquire(node); // get current function scope
}
},
leave(node, parent) {
if (/Function/.test(node.type)) {
currentScope = currentScope.upper; // set to parent scope
}
// do stuff
},
});
```
## API
The following section describes the API for this package. You can also read [the docs](https://eslint.org/docs/latest/extend/scope-manager-interface).
### ScopeManager
The `ScopeManager` class is at the core of eslint-scope and is returned when you call `eslintScope.analyze()`. It manages all scopes in a given AST.
#### Properties
- `scopes` - An array of all scopes.
- `globalScope` - Reference to the global scope.
#### Methods
- **`addGlobals(names)`**
Adds variables to the global scope and resolves references to them.
- `names` - An array of strings, the names of variables to add to the global scope.
- Returns: `undefined`.
- **`acquire(node, inner)`**
Acquires the appropriate scope for a given node.
- `node` - The AST node to acquire the scope from.
- `inner` - Optional boolean. When `true`, returns the innermost scope, otherwise returns the outermost scope. Default is `false`.
- Returns: The acquired scope or `null` if no scope is found.
- **`acquireAll(node)` (Deprecated)**
Acquires all scopes for a given node.
- `node` - The AST node to acquire scopes from.
- Returns: An array of scopes or `undefined` if none are found.
- **`release(node, inner)`**
Returns the upper scope for a given node.
- `node` - The AST node to release.
- `inner` - Optional boolean. When `true`, returns the innermost upper scope, otherwise returns the outermost upper scope. Default is `false`.
- Returns: The upper scope or `null` if no upper scope exists.
- **`getDeclaredVariables(node)`**
Get variables that are declared by the node.
- `node` - The AST node to get declarations from.
- Returns: An array of variable objects declared by the node. If the node doesn't declare any variables, it returns an empty array.
- **`isGlobalReturn()`**
Determines if the global return statement should be allowed.
- Returns: `true` if the global return is enabled.
- **`isModule()` (Deprecated)**
Checks if the code should be handled as an ECMAScript module.
- Returns: `true` if the sourceType is "module".
- **`isImpliedStrict()` (Deprecated)**
Checks if implied strict mode is enabled.
- Returns: `true` if implied strict mode is enabled.
- **`isStrictModeSupported()` (Deprecated)**
Checks if strict mode is supported based on ECMAScript version.
- Returns: `true` if the ECMAScript version supports strict mode.
### Scope Objects
Scopes returned by the ScopeManager methods have the following properties:
- `type` - The type of scope (e.g., `"function"`, `"block"`, `"global"`).
- `isStrict` - `true` if this scope is in strict mode.
- `variables` - Array of variables declared in this scope.
- `set` - A Map of variable names to Variable objects for variables declared in this scope.
- `references` - Array of references in this scope.
- `through` - Array of references in this scope and its child scopes that aren't resolved in this scope or its child scopes.
- `functionExpressionScope` - `true` if this is a `"function-expression-name"` scope.
- `variableScope` - Reference to the closest variable scope.
- `upper` - Reference to the parent scope.
- `childScopes` - Array of child scopes.
- `block` - The AST node that created this scope.
### GlobalScope
The `GlobalScope` class is a specialized scope representing the global execution context. It extends the base `Scope` class with additional functionality for handling implicitly defined global variables.
#### Properties
- **`implicit`** - Tracks implicitly defined global variables (those used without declaration).
- `set` - A Map of variable names to Variable objects for implicitly defined globals.
- `variables` - Array of implicit global Variable objects.
- `left` - Array of References that need to be linked to the variable they refer to.
### Variable Objects
Each variable object has the following properties:
- `name` - The variable name.
- `identifiers` - Array of identifier nodes declaring this variable.
- `references` - Array of references to this variable.
- `defs` - Array of definition objects for this variable.
- `scope` - The scope object where this variable is defined.
## Contributing
Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/js/issues).
## Security Policy
We work hard to ensure that ESLint Scope is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md).
## Build Commands
- `npm test` - run all linting and tests
- `npm run lint` - run all linting
## License
ESLint Scope is licensed under a permissive BSD 2-clause license.
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart-->
## Sponsors
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
<h3>Platinum Sponsors</h3>
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a></p><h3>Gold Sponsors</h3>
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/d472863/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/2d6c3b6/logo.png" alt="Liftoff" height="64"></a> <a href="https://stackblitz.com"><img src="https://avatars.githubusercontent.com/u/28635252" alt="StackBlitz" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://opensource.sap.com"><img src="https://avatars.githubusercontent.com/u/2531208" alt="SAP" height="32"></a> <a href="https://www.crawljobs.com/"><img src="https://images.opencollective.com/crawljobs-poland/fa43a17/logo.png" alt="CrawlJobs" height="32"></a> <a href="https://depot.dev"><img src="https://images.opencollective.com/depot/39125a1/logo.png" alt="Depot" height="32"></a> <a href="https://www.n-ix.com/"><img src="https://images.opencollective.com/n-ix-ltd/575a7a5/logo.png" alt="N-iX Ltd" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://www.lambdatest.com"><img src="https://avatars.githubusercontent.com/u/171592363" alt="TestMu AI Open Source Office (Formerly LambdaTest)" height="32"></a></p>
<h3>Technology Sponsors</h3>
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
<!--sponsorsend-->
@@ -0,0 +1,665 @@
import MagicString from 'magic-string';
import { e as esmWalker } from './chunk-automock.js';
// AST walker module for ESTree compatible trees
function makeTest(test) {
if (typeof test === "string")
{ return function (type) { return type === test; } }
else if (!test)
{ return function () { return true; } }
else
{ return test }
}
var Found = function Found(node, state) { this.node = node; this.state = state; };
// Find the innermost node of a given type that contains the given
// position. Interface similar to findNodeAt.
function findNodeAround(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
try {
(function c(node, st, override) {
var type = override || node.type;
if (node.start > pos || node.end < pos) { return }
visitNode(baseVisitor, type, node, st, c);
if (test(type, node)) { throw new Found(node, st) }
})(node, state);
} catch (e) {
if (e instanceof Found) { return e }
throw e
}
}
function skipThrough(node, st, c) { c(node, st); }
function ignore(_node, _st, _c) {}
function visitNode(baseVisitor, type, node, st, c) {
if (baseVisitor[type] == null) { throw new Error(("No walker function defined for node type " + type)) }
baseVisitor[type](node, st, c);
}
// Node walkers.
var base = {};
base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) {
for (var i = 0, list = node.body; i < list.length; i += 1)
{
var stmt = list[i];
c(stmt, st, "Statement");
}
};
base.Statement = skipThrough;
base.EmptyStatement = ignore;
base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
function (node, st, c) { return c(node.expression, st, "Expression"); };
base.IfStatement = function (node, st, c) {
c(node.test, st, "Expression");
c(node.consequent, st, "Statement");
if (node.alternate) { c(node.alternate, st, "Statement"); }
};
base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
base.BreakStatement = base.ContinueStatement = ignore;
base.WithStatement = function (node, st, c) {
c(node.object, st, "Expression");
c(node.body, st, "Statement");
};
base.SwitchStatement = function (node, st, c) {
c(node.discriminant, st, "Expression");
for (var i = 0, list = node.cases; i < list.length; i += 1) {
var cs = list[i];
c(cs, st);
}
};
base.SwitchCase = function (node, st, c) {
if (node.test) { c(node.test, st, "Expression"); }
for (var i = 0, list = node.consequent; i < list.length; i += 1)
{
var cons = list[i];
c(cons, st, "Statement");
}
};
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
if (node.argument) { c(node.argument, st, "Expression"); }
};
base.ThrowStatement = base.SpreadElement =
function (node, st, c) { return c(node.argument, st, "Expression"); };
base.TryStatement = function (node, st, c) {
c(node.block, st, "Statement");
if (node.handler) { c(node.handler, st); }
if (node.finalizer) { c(node.finalizer, st, "Statement"); }
};
base.CatchClause = function (node, st, c) {
if (node.param) { c(node.param, st, "Pattern"); }
c(node.body, st, "Statement");
};
base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
c(node.test, st, "Expression");
c(node.body, st, "Statement");
};
base.ForStatement = function (node, st, c) {
if (node.init) { c(node.init, st, "ForInit"); }
if (node.test) { c(node.test, st, "Expression"); }
if (node.update) { c(node.update, st, "Expression"); }
c(node.body, st, "Statement");
};
base.ForInStatement = base.ForOfStatement = function (node, st, c) {
c(node.left, st, "ForInit");
c(node.right, st, "Expression");
c(node.body, st, "Statement");
};
base.ForInit = function (node, st, c) {
if (node.type === "VariableDeclaration") { c(node, st); }
else { c(node, st, "Expression"); }
};
base.DebuggerStatement = ignore;
base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
base.VariableDeclaration = function (node, st, c) {
for (var i = 0, list = node.declarations; i < list.length; i += 1)
{
var decl = list[i];
c(decl, st);
}
};
base.VariableDeclarator = function (node, st, c) {
c(node.id, st, "Pattern");
if (node.init) { c(node.init, st, "Expression"); }
};
base.Function = function (node, st, c) {
if (node.id) { c(node.id, st, "Pattern"); }
for (var i = 0, list = node.params; i < list.length; i += 1)
{
var param = list[i];
c(param, st, "Pattern");
}
c(node.body, st, node.expression ? "Expression" : "Statement");
};
base.Pattern = function (node, st, c) {
if (node.type === "Identifier")
{ c(node, st, "VariablePattern"); }
else if (node.type === "MemberExpression")
{ c(node, st, "MemberPattern"); }
else
{ c(node, st); }
};
base.VariablePattern = ignore;
base.MemberPattern = skipThrough;
base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
base.ArrayPattern = function (node, st, c) {
for (var i = 0, list = node.elements; i < list.length; i += 1) {
var elt = list[i];
if (elt) { c(elt, st, "Pattern"); }
}
};
base.ObjectPattern = function (node, st, c) {
for (var i = 0, list = node.properties; i < list.length; i += 1) {
var prop = list[i];
if (prop.type === "Property") {
if (prop.computed) { c(prop.key, st, "Expression"); }
c(prop.value, st, "Pattern");
} else if (prop.type === "RestElement") {
c(prop.argument, st, "Pattern");
}
}
};
base.Expression = skipThrough;
base.ThisExpression = base.Super = base.MetaProperty = ignore;
base.ArrayExpression = function (node, st, c) {
for (var i = 0, list = node.elements; i < list.length; i += 1) {
var elt = list[i];
if (elt) { c(elt, st, "Expression"); }
}
};
base.ObjectExpression = function (node, st, c) {
for (var i = 0, list = node.properties; i < list.length; i += 1)
{
var prop = list[i];
c(prop, st);
}
};
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
base.SequenceExpression = function (node, st, c) {
for (var i = 0, list = node.expressions; i < list.length; i += 1)
{
var expr = list[i];
c(expr, st, "Expression");
}
};
base.TemplateLiteral = function (node, st, c) {
for (var i = 0, list = node.quasis; i < list.length; i += 1)
{
var quasi = list[i];
c(quasi, st);
}
for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
{
var expr = list$1[i$1];
c(expr, st, "Expression");
}
};
base.TemplateElement = ignore;
base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
c(node.argument, st, "Expression");
};
base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
c(node.left, st, "Expression");
c(node.right, st, "Expression");
};
base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
c(node.left, st, "Pattern");
c(node.right, st, "Expression");
};
base.ConditionalExpression = function (node, st, c) {
c(node.test, st, "Expression");
c(node.consequent, st, "Expression");
c(node.alternate, st, "Expression");
};
base.NewExpression = base.CallExpression = function (node, st, c) {
c(node.callee, st, "Expression");
if (node.arguments)
{ for (var i = 0, list = node.arguments; i < list.length; i += 1)
{
var arg = list[i];
c(arg, st, "Expression");
} }
};
base.MemberExpression = function (node, st, c) {
c(node.object, st, "Expression");
if (node.computed) { c(node.property, st, "Expression"); }
};
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
if (node.declaration)
{ c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
if (node.source) { c(node.source, st, "Expression"); }
if (node.attributes)
{ for (var i = 0, list = node.attributes; i < list.length; i += 1)
{
var attr = list[i];
c(attr, st);
} }
};
base.ExportAllDeclaration = function (node, st, c) {
if (node.exported)
{ c(node.exported, st); }
c(node.source, st, "Expression");
if (node.attributes)
{ for (var i = 0, list = node.attributes; i < list.length; i += 1)
{
var attr = list[i];
c(attr, st);
} }
};
base.ImportAttribute = function (node, st, c) {
c(node.value, st, "Expression");
};
base.ImportDeclaration = function (node, st, c) {
for (var i = 0, list = node.specifiers; i < list.length; i += 1)
{
var spec = list[i];
c(spec, st);
}
c(node.source, st, "Expression");
if (node.attributes)
{ for (var i$1 = 0, list$1 = node.attributes; i$1 < list$1.length; i$1 += 1)
{
var attr = list$1[i$1];
c(attr, st);
} }
};
base.ImportExpression = function (node, st, c) {
c(node.source, st, "Expression");
if (node.options) { c(node.options, st, "Expression"); }
};
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
base.TaggedTemplateExpression = function (node, st, c) {
c(node.tag, st, "Expression");
c(node.quasi, st, "Expression");
};
base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
base.Class = function (node, st, c) {
if (node.id) { c(node.id, st, "Pattern"); }
if (node.superClass) { c(node.superClass, st, "Expression"); }
c(node.body, st);
};
base.ClassBody = function (node, st, c) {
for (var i = 0, list = node.body; i < list.length; i += 1)
{
var elt = list[i];
c(elt, st);
}
};
base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
if (node.computed) { c(node.key, st, "Expression"); }
if (node.value) { c(node.value, st, "Expression"); }
};
const API_NOT_FOUND_ERROR = `There are some problems in resolving the mocks API.
You may encounter this issue when importing the mocks API from another module other than 'vitest'.
To fix this issue you can either:
- import the mocks API directly from 'vitest'
- enable the 'globals' option`;
function API_NOT_FOUND_CHECK(names) {
return `\nif (${names.map((name) => `typeof globalThis["${name}"] === "undefined"`).join(" && ")}) ` + `{ throw new Error(${JSON.stringify(API_NOT_FOUND_ERROR)}) }\n`;
}
function isIdentifier(node) {
return node.type === "Identifier";
}
function getNodeTail(code, node) {
let end = node.end;
if (code[node.end] === ";") {
end += 1;
}
if (code[node.end] === "\n") {
return end + 1;
}
if (code[node.end + 1] === "\n") {
end += 1;
}
return end;
}
const regexpHoistable = /\b(?:vi|vitest)\s*\.\s*(?:mock|unmock|hoisted|doMock|doUnmock)\s*\(/;
const hashbangRE = /^#!.*\n/;
// Public redistributions of Vitest that re-export its mocking API (`vi`)
// verbatim under their own specifier. Imports from these are treated as the
// hoisted module so `vi.mock()` is hoisted for e.g.
// `import { vi } from 'vite-plus/test'`, exactly as it is for `vitest`.
const REDISTRIBUTED_HOISTED_MODULES = ["vite-plus/test"];
// this is a fork of Vite SSR transform
function hoistMocks(code, id, parse, options = {}) {
const needHoisting = (options.regexpHoistable || regexpHoistable).test(code);
if (!needHoisting) {
return;
}
const s = options.magicString?.() || new MagicString(code);
let ast;
try {
ast = parse(code);
} catch (err) {
console.error(`Cannot parse ${id}:\n${err.message}.`);
return;
}
const { hoistableMockMethodNames = ["mock", "unmock"], dynamicImportMockMethodNames = [
"mock",
"unmock",
"doMock",
"doUnmock"
], hoistedMethodNames = ["hoisted"], utilsObjectNames = ["vi", "vitest"], hoistedModule = "vitest" } = options;
// hoist at the start of the file, after the hashbang
const hashbangEnd = hashbangRE.exec(code)?.[0].length ?? 0;
let hoistIndex = hashbangEnd;
let hoistedModuleImported = false;
let uid = 0;
const idToImportMap = new Map();
const imports = [];
// this will transform import statements into dynamic ones, if there are imports
// it will keep the import as is, if we don't need to mock anything
// in browser environment it will wrap the module value with "vitest_wrap_module" function
// that returns a proxy to the module so that named exports can be mocked
function defineImport(importNode) {
const source = importNode.source.value;
// always hoist vitest import to top of the file, so
// "vi" helpers can access it. Vitest redistributions that re-export the
// mocking API under their own specifier are recognized the same way.
if (hoistedModule === source || REDISTRIBUTED_HOISTED_MODULES.includes(source)) {
hoistedModuleImported = true;
return;
}
const importId = `__vi_import_${uid++}__`;
imports.push({
id: importId,
node: importNode
});
return importId;
}
// 1. check all import statements and record id -> importName map
for (const node of ast.body) {
// import foo from 'foo' --> foo -> __import_foo__.default
// import { baz } from 'foo' --> baz -> __import_foo__.baz
// import * as ok from 'foo' --> ok -> __import_foo__
if (node.type === "ImportDeclaration") {
const importId = defineImport(node);
if (!importId) {
continue;
}
for (const spec of node.specifiers) {
if (spec.type === "ImportSpecifier") {
if (spec.imported.type === "Identifier") {
idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`);
} else {
idToImportMap.set(spec.local.name, `${importId}[${JSON.stringify(spec.imported.value)}]`);
}
} else if (spec.type === "ImportDefaultSpecifier") {
idToImportMap.set(spec.local.name, `${importId}.default`);
} else {
// namespace specifier
idToImportMap.set(spec.local.name, importId);
}
}
}
}
const declaredConst = new Set();
const hoistedNodes = new Set();
function createSyntaxError(node, message) {
const _error = new SyntaxError(message);
Error.captureStackTrace(_error, createSyntaxError);
const serializedError = {
name: "SyntaxError",
message: _error.message,
stack: _error.stack
};
if (options.codeFrameGenerator) {
serializedError.frame = options.codeFrameGenerator(node, id, code);
}
return serializedError;
}
function assertNotDefaultExport(node, error) {
const defaultExport = findNodeAround(ast, node.start, "ExportDefaultDeclaration")?.node;
if (defaultExport?.declaration === node || defaultExport?.declaration.type === "AwaitExpression" && defaultExport.declaration.argument === node) {
throw createSyntaxError(defaultExport, error);
}
}
function assertNotNamedExport(node, error) {
const nodeExported = findNodeAround(ast, node.start, "ExportNamedDeclaration")?.node;
if (nodeExported?.declaration === node) {
throw createSyntaxError(nodeExported, error);
}
}
function getVariableDeclaration(node) {
const declarationNode = findNodeAround(ast, node.start, "VariableDeclaration")?.node;
const init = declarationNode?.declarations[0]?.init;
if (init && (init === node || init.type === "AwaitExpression" && init.argument === node)) {
return declarationNode;
}
}
const usedUtilityExports = new Set();
let hasImportMetaVitest = false;
esmWalker(ast, {
onImportMeta(node) {
const property = code.slice(node.end, node.end + 7);
if (property === ".vitest") {
hasImportMetaVitest = true;
}
},
onIdentifier(id, info, parentStack) {
const binding = idToImportMap.get(id.name);
if (!binding) {
return;
}
if (info.hasBindingShortcut) {
s.appendLeft(id.end, `: ${binding}`);
} else if (info.classDeclaration) {
if (!declaredConst.has(id.name)) {
declaredConst.add(id.name);
// locate the top-most node containing the class declaration
const topNode = parentStack[parentStack.length - 2];
s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`);
}
} else if (!info.classExpression) {
s.update(id.start, id.end, binding);
}
},
onDynamicImport(_node) {
// TODO: vi.mock(import) breaks it, and vi.mock('', () => import) also does,
// only move imports that are outside of vi.mock
// backwards compat, don't do if not passed
// if (!options.globalThisAccessor) {
// return
// }
// const globalThisAccessor = options.globalThisAccessor
// const replaceString = `globalThis[${globalThisAccessor}].wrapDynamicImport(() => import(`
// const importSubstring = code.substring(node.start, node.end)
// const hasIgnore = importSubstring.includes('/* @vite-ignore */')
// s.overwrite(
// node.start,
// (node.source as Positioned<Expression>).start,
// replaceString + (hasIgnore ? '/* @vite-ignore */ ' : ''),
// )
// s.overwrite(node.end - 1, node.end, '))')
},
onCallExpression(node) {
if (node.callee.type === "MemberExpression" && isIdentifier(node.callee.object) && utilsObjectNames.includes(node.callee.object.name) && isIdentifier(node.callee.property)) {
const methodName = node.callee.property.name;
usedUtilityExports.add(node.callee.object.name);
if (hoistableMockMethodNames.includes(methodName)) {
const method = `${node.callee.object.name}.${methodName}`;
assertNotDefaultExport(node, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`);
const declarationNode = getVariableDeclaration(node);
if (declarationNode) {
assertNotNamedExport(declarationNode, `Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`);
}
// rewrite vi.mock(import('..')) into vi.mock('..')
if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && dynamicImportMockMethodNames.includes(node.callee.property.name)) {
const moduleInfo = node.arguments[0];
// vi.mock(import('./path')) -> vi.mock('./path')
if (moduleInfo.type === "ImportExpression") {
const source = moduleInfo.source;
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
}
// vi.mock(await import('./path')) -> vi.mock('./path')
if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") {
const source = moduleInfo.argument.source;
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
}
}
hoistedNodes.add(node);
} else if (dynamicImportMockMethodNames.includes(methodName)) {
const moduleInfo = node.arguments[0];
let source = null;
if (moduleInfo.type === "ImportExpression") {
source = moduleInfo.source;
}
if (moduleInfo.type === "AwaitExpression" && moduleInfo.argument.type === "ImportExpression") {
source = moduleInfo.argument.source;
}
if (source) {
s.overwrite(moduleInfo.start, moduleInfo.end, s.slice(source.start, source.end));
}
}
if (hoistedMethodNames.includes(methodName)) {
assertNotDefaultExport(node, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.");
const declarationNode = getVariableDeclaration(node);
if (declarationNode) {
assertNotNamedExport(declarationNode, "Cannot export hoisted variable. You can control hoisting behavior by placing the import from this file first.");
// hoist "const variable = vi.hoisted(() => {})"
hoistedNodes.add(declarationNode);
} else {
const awaitedExpression = findNodeAround(ast, node.start, "AwaitExpression")?.node;
// hoist "await vi.hoisted(async () => {})" or "vi.hoisted(() => {})"
const moveNode = awaitedExpression?.argument === node ? awaitedExpression : node;
hoistedNodes.add(moveNode);
}
}
}
}
});
function getNodeName(node) {
const callee = node.callee || {};
if (callee.type === "MemberExpression" && isIdentifier(callee.property) && isIdentifier(callee.object)) {
const argument = node.arguments[0];
const argStr = argument.type === "Literal" || argument.type === "ImportExpression" ? code.slice(argument.start, argument.end) : "";
return `${callee.object.name}.${callee.property.name}(${argStr})`;
}
return "\"hoisted method\"";
}
function getNodeCall(node) {
if (node.type === "CallExpression") {
return node;
}
if (node.type === "VariableDeclaration") {
const { declarations } = node;
const init = declarations[0].init;
if (init) {
return getNodeCall(init);
}
}
if (node.type === "AwaitExpression") {
const { argument } = node;
if (argument.type === "CallExpression") {
return getNodeCall(argument);
}
}
return node;
}
function createError(outsideNode, insideNode) {
const outsideCall = getNodeCall(outsideNode);
const insideCall = getNodeCall(insideNode);
throw createSyntaxError(insideCall, `Cannot call ${getNodeName(insideCall)} inside ${getNodeName(outsideCall)}: both methods are hoisted to the top of the file and not actually called inside each other.`);
}
// validate hoistedNodes doesn't have nodes inside other nodes
const arrayNodes = Array.from(hoistedNodes);
for (let i = 0; i < arrayNodes.length; i++) {
const node = arrayNodes[i];
for (let j = i + 1; j < arrayNodes.length; j++) {
const otherNode = arrayNodes[j];
if (node.start >= otherNode.start && node.end <= otherNode.end) {
throw createError(otherNode, node);
}
if (otherNode.start >= node.start && otherNode.end <= node.end) {
throw createError(node, otherNode);
}
}
}
// validate that hoisted nodes are defined on the top level
// ignore `import.meta.vitest` because it needs to be inside an IfStatement
// and it can be used anywhere in the code (inside methods too)
if (!hasImportMetaVitest) {
for (const node of ast.body) {
hoistedNodes.delete(node);
if (node.type === "ExpressionStatement") {
hoistedNodes.delete(node.expression);
}
}
for (const invalidNode of hoistedNodes) {
console.warn(`Warning: A ${getNodeName(getNodeCall(invalidNode))} call in "${id}" is not at the top level of the module. ` + `Although it appears nested, it will be hoisted and executed before any tests run. ` + `Move it to the top level to reflect its actual execution order. This will become an error in a future version.\n` + `See: https://vitest.dev/guide/mocking/modules#how-it-works`);
}
}
// hoist vi.mock/vi.hoisted
for (const node of arrayNodes) {
const end = getNodeTail(code, node);
// don't hoist into itself if it's already at the top
if (hoistIndex === end || hoistIndex === node.start) {
hoistIndex = end;
} else {
s.move(node.start, end, hoistIndex);
}
}
// hoist actual dynamic imports last so they are inserted after all hoisted mocks
for (const { node: importNode, id: importId } of imports) {
const source = importNode.source.value;
const sourceString = JSON.stringify(source);
let importLine = `const ${importId} = await `;
if (options.globalThisAccessor) {
importLine += `globalThis[${options.globalThisAccessor}].wrapDynamicImport(() => import(${sourceString}));\n`;
} else {
importLine += `import(${sourceString});\n`;
}
s.update(importNode.start, importNode.end, importLine);
if (importNode.start === hoistIndex) {
// no need to hoist, but update hoistIndex to keep the order
hoistIndex = importNode.end;
} else {
// There will be an error if the module is called before it is imported,
// so the module import statement is hoisted to the top
s.move(importNode.start, importNode.end, hoistIndex);
}
}
if (!hoistedModuleImported && arrayNodes.length > 0) {
const utilityImports = [...usedUtilityExports];
// "vi" or "vitest" is imported from a module other than "vitest"
if (utilityImports.some((name) => idToImportMap.has(name))) {
s.appendLeft(hashbangEnd, API_NOT_FOUND_CHECK(utilityImports));
} else if (utilityImports.length) {
s.appendLeft(hashbangEnd, `import { ${[...usedUtilityExports].join(", ")} } from ${JSON.stringify(hoistedModule)}\n`);
}
}
return s;
}
export { hoistMocks as h };
@@ -0,0 +1,2 @@
import type { LibDefinition } from '../variable';
export declare const es2018: LibDefinition;
@@ -0,0 +1,3 @@
import { n as AjvJsonSchemaValidator, r as addFormats, t as Ajv } from "../ajvProvider-97rDpkRx.mjs";
export { Ajv, AjvJsonSchemaValidator, addFormats };
@@ -0,0 +1,29 @@
## istanbul-lib-coverage
[![Greenkeeper badge](https://badges.greenkeeper.io/istanbuljs/istanbul-lib-coverage.svg)](https://greenkeeper.io/)
[![Build Status](https://travis-ci.org/istanbuljs/istanbul-lib-coverage.svg?branch=master)](https://travis-ci.org/istanbuljs/istanbul-lib-coverage)
An API that provides a read-only view of coverage information with the ability
to merge and summarize coverage info.
Supersedes `object-utils` and `collector` from the v0 istanbul API.
See the docs for the full API.
```js
var libCoverage = require('istanbul-lib-coverage');
var map = libCoverage.createCoverageMap(globalCoverageVar);
var summary = libCoverage.createCoverageSummary();
// merge another coverage map into the one we created
map.merge(otherCoverageMap);
// inspect and summarize all file coverage objects in the map
map.files().forEach(function(f) {
var fc = map.fileCoverageFor(f),
s = fc.toSummary();
summary.merge(s);
});
console.log('Global summary', summary);
```
@@ -0,0 +1,75 @@
{
"name": "@radix-ui/react-tabs",
"version": "1.1.13",
"license": "MIT",
"source": "./src/index.ts",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"files": [
"dist",
"README.md"
],
"sideEffects": false,
"dependencies": {
"@radix-ui/primitive": "1.1.3",
"@radix-ui/react-direction": "1.1.1",
"@radix-ui/react-id": "1.1.1",
"@radix-ui/react-primitive": "2.1.3",
"@radix-ui/react-presence": "1.1.5",
"@radix-ui/react-context": "1.1.2",
"@radix-ui/react-roving-focus": "1.1.11",
"@radix-ui/react-use-controllable-state": "1.2.2"
},
"devDependencies": {
"@types/react": "^19.0.7",
"@types/react-dom": "^19.0.3",
"eslint": "^9.18.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"typescript": "^5.7.3",
"@repo/builder": "0.0.0",
"@repo/eslint-config": "0.0.0",
"@repo/typescript-config": "0.0.0"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
},
"homepage": "https://radix-ui.com/primitives",
"repository": {
"type": "git",
"url": "git+https://github.com/radix-ui/primitives.git"
},
"bugs": {
"url": "https://github.com/radix-ui/primitives/issues"
},
"scripts": {
"lint": "eslint --max-warnings 0 src",
"clean": "rm -rf dist",
"typecheck": "tsc --noEmit",
"build": "radix-build"
},
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
}
}
}
@@ -0,0 +1,6 @@
"use strict";
const addHours = require("./addHours.js");
function subHours(date, hours) {
return addHours(date, -hours);
}
module.exports = subHours;
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Ethan Arrowood
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,181 @@
import { $ as warnDeprecation, f as createRule, g as import_ast_utils } from "../utils.js";
function createRules(options) {
const globals = {
...options?.before !== void 0 ? { before: options.before } : {},
...options?.after !== void 0 ? { after: options.after } : {}
};
const override = options?.overrides ?? {};
const colon = {
before: false,
after: true,
...globals,
...override?.colon
};
const arrow = typeof override.arrow === "string" ? override.arrow : {
before: true,
after: true,
...globals,
...override?.arrow
};
if (Object.hasOwn(override, "arrow") && override.arrow !== "ignore") warnDeprecation("options(\"overrides.arrow\")", "\"arrow-spacing\"", "type-annotation-spacing");
return {
colon,
arrow,
variable: {
...colon,
...override?.variable
},
property: {
...colon,
...override?.property
},
parameter: {
...colon,
...override?.parameter
},
returnType: {
...colon,
...override?.returnType
}
};
}
function getIdentifierRules(rules, node) {
const scope = node?.parent;
if ((0, import_ast_utils.isVariableDeclarator)(scope)) return rules.variable;
else if ((0, import_ast_utils.isFunctionOrFunctionType)(scope)) return rules.parameter;
return rules.colon;
}
function getRules(rules, node) {
const scope = node?.parent?.parent;
if ((0, import_ast_utils.isTSFunctionType)(scope) || (0, import_ast_utils.isTSConstructorType)(scope)) return rules.arrow;
else if ((0, import_ast_utils.isIdentifier)(scope)) return getIdentifierRules(rules, scope);
else if ((0, import_ast_utils.isClassOrTypeElement)(scope)) return rules.property;
else if ((0, import_ast_utils.isFunction)(scope)) return rules.returnType;
return rules.colon;
}
var type_annotation_spacing_default = createRule({
name: "type-annotation-spacing",
meta: {
type: "layout",
docs: { description: "Require consistent spacing around type annotations" },
fixable: "whitespace",
schema: [{
$defs: { spacingConfig: {
type: "object",
properties: {
before: { type: "boolean" },
after: { type: "boolean" }
},
additionalProperties: false
} },
type: "object",
properties: {
before: { type: "boolean" },
after: { type: "boolean" },
overrides: {
type: "object",
properties: {
colon: { $ref: "#/items/0/$defs/spacingConfig" },
arrow: { oneOf: [{
type: "string",
enum: ["ignore"]
}, { $ref: "#/items/0/$defs/spacingConfig" }] },
variable: { $ref: "#/items/0/$defs/spacingConfig" },
parameter: { $ref: "#/items/0/$defs/spacingConfig" },
property: { $ref: "#/items/0/$defs/spacingConfig" },
returnType: { $ref: "#/items/0/$defs/spacingConfig" }
},
additionalProperties: false
}
},
additionalProperties: false
}],
defaultOptions: [{}],
messages: {
expectedSpaceAfter: "Expected a space after the '{{type}}'.",
expectedSpaceBefore: "Expected a space before the '{{type}}'.",
unexpectedSpaceAfter: "Unexpected space after the '{{type}}'.",
unexpectedSpaceBefore: "Unexpected space before the '{{type}}'.",
unexpectedSpaceBetween: "Unexpected space between the '{{previousToken}}' and the '{{type}}'."
}
},
create(context, [options]) {
const punctuators = [":", "=>"];
const sourceCode = context.sourceCode;
const ruleSet = createRules(options);
function checkTypeAnnotationSpacing(typeAnnotation) {
const punctuatorTokenEnd = sourceCode.getTokenBefore(typeAnnotation, import_ast_utils.isNotOpeningParenToken);
let punctuatorTokenStart = punctuatorTokenEnd;
let previousToken = sourceCode.getTokenBefore(punctuatorTokenEnd);
let type = punctuatorTokenEnd.value;
if (!punctuators.includes(type)) return;
const config = getRules(ruleSet, typeAnnotation);
if (config === "ignore") return;
const { before, after } = config;
if (type === ":" && previousToken.value === "?") {
if (sourceCode.isSpaceBetween(previousToken, punctuatorTokenStart)) context.report({
node: punctuatorTokenStart,
messageId: "unexpectedSpaceBetween",
data: {
type,
previousToken: previousToken.value
},
fix(fixer) {
return fixer.removeRange([previousToken.range[1], punctuatorTokenStart.range[0]]);
}
});
type = "?:";
punctuatorTokenStart = previousToken;
previousToken = sourceCode.getTokenBefore(previousToken);
if (previousToken.value === "+" || previousToken.value === "-") {
type = `${previousToken.value}?:`;
punctuatorTokenStart = previousToken;
previousToken = sourceCode.getTokenBefore(previousToken);
}
}
const hasNextSpace = sourceCode.isSpaceBetween(punctuatorTokenEnd, typeAnnotation);
if (after && !hasNextSpace) context.report({
node: punctuatorTokenEnd,
messageId: "expectedSpaceAfter",
data: { type },
fix(fixer) {
return fixer.insertTextAfter(punctuatorTokenEnd, " ");
}
});
else if (!after && hasNextSpace) context.report({
node: punctuatorTokenEnd,
messageId: "unexpectedSpaceAfter",
data: { type },
fix(fixer) {
return fixer.removeRange([punctuatorTokenEnd.range[1], typeAnnotation.range[0]]);
}
});
const hasPrevSpace = sourceCode.isSpaceBetween(previousToken, punctuatorTokenStart);
if (before && !hasPrevSpace) context.report({
node: punctuatorTokenStart,
messageId: "expectedSpaceBefore",
data: { type },
fix(fixer) {
return fixer.insertTextAfter(previousToken, " ");
}
});
else if (!before && hasPrevSpace) context.report({
node: punctuatorTokenStart,
messageId: "unexpectedSpaceBefore",
data: { type },
fix(fixer) {
return fixer.removeRange([previousToken.range[1], punctuatorTokenStart.range[0]]);
}
});
}
return {
TSMappedType(node) {
if (node.typeAnnotation) checkTypeAnnotationSpacing(node.typeAnnotation);
},
TSTypeAnnotation(node) {
checkTypeAnnotationSpacing(node.typeAnnotation);
}
};
}
});
export { type_annotation_spacing_default as t };
@@ -0,0 +1,256 @@
# Socks5ProxyAgent
<!--introduced_in=v7.23.0-->
<!--type=module-->
<!-- source_link=lib/dispatcher/socks5-proxy-agent.js -->
> Stability: 1 - Experimental
A [`Dispatcher`][] implementation that routes requests through a [SOCKS5][]
proxy server. It tunnels both HTTP and HTTPS traffic over the proxy, supports
optional username/password authentication, and pools connections per origin so
that subsequent requests to the same host reuse the established tunnel.
DNS resolution is delegated to the proxy: target host names are sent to the
proxy as domain names rather than being resolved locally. For HTTPS targets the
TLS session is negotiated end-to-end through the tunnel, so the proxy only sees
encrypted bytes.
Import it from `'undici'`:
```mjs
import { Socks5ProxyAgent } from 'undici'
```
Constructing the agent emits a one-time `ExperimentalWarning`, reflecting the
experimental status of SOCKS5 support.
## Class: `Socks5ProxyAgent`
<!-- YAML
added: v7.23.0
-->
> Stability: 1 - Experimental
* Extends: {Dispatcher}
Routes dispatched requests through a SOCKS5 proxy. Register an instance as the
global dispatcher with [`setGlobalDispatcher()`][], or pass it per request via
the `dispatcher` option.
### `new Socks5ProxyAgent(proxyUrl[, options])`
<!-- YAML
added: v7.23.0
-->
> Stability: 1 - Experimental
* `proxyUrl` {string|URL} The SOCKS5 proxy server URL. Must use the `socks5:` or
`socks:` protocol. Credentials may be embedded in the URL userinfo (for
example `socks5://user:pass@host:1080`).
* `options` {Object} (optional) Extends {PoolOptions}; the pool options are
applied to the per-origin pools created behind the tunnel.
* `headers` {Object} Additional headers to send with the proxy connection.
**Default:** `{}`.
* `username` {string} Username for SOCKS5 authentication. Takes precedence over
a username embedded in `proxyUrl`. **Default:** the URL username, if any.
* `password` {string} Password for SOCKS5 authentication. Takes precedence over
a password embedded in `proxyUrl`. **Default:** the URL password, if any.
* `connect` {Function} Custom connector used to open the socket to the proxy.
**Default:** a connector built from `proxyTls`.
* `connectTimeout` {number} Maximum time in milliseconds for each proxy
connection, SOCKS5 negotiation, and target TLS negotiation stage. A value of
`0` disables these stage timeouts. `proxyTls.timeout` and
`requestTls.timeout` override it for their respective TLS stages.
**Default:** `5000`.
* `proxyTls` {BuildOptions} TLS options for the connection to the proxy itself
(SOCKS5 over TLS). When set, the proxy connection is established over TLS and
`servername` defaults to the proxy host name.
* `requestTls` {BuildOptions} TLS options applied to the end-to-end connection
to an HTTPS target through the tunnel, such as `ca`, `cert`, `key`,
`rejectUnauthorized`, and `servername`. `servername` defaults to the target
host name.
Throws an `InvalidArgumentError` if `proxyUrl` is missing or does not use the
`socks5:` or `socks:` protocol, or if `connectTimeout`, `proxyTls.timeout`, or
`requestTls.timeout` is not a finite, non-negative number.
```mjs
import { Socks5ProxyAgent } from 'undici'
// Without authentication.
const agent = new Socks5ProxyAgent('socks5://localhost:1080')
// With credentials in the URL.
const authAgent = new Socks5ProxyAgent('socks5://user:pass@localhost:1080')
// With credentials and pool options.
const configuredAgent = new Socks5ProxyAgent('socks5://localhost:1080', {
username: 'user',
password: 'pass',
connections: 10
})
```
Using the agent as the global dispatcher:
```mjs
import { setGlobalDispatcher, request, Socks5ProxyAgent } from 'undici'
const agent = new Socks5ProxyAgent('socks5://localhost:1080')
setGlobalDispatcher(agent)
const { statusCode, body } = await request('http://localhost:3000/foo')
console.log('response received', statusCode)
for await (const data of body) {
console.log('data', data.toString('utf8'))
}
```
Using the agent per request:
```mjs
import { request, Socks5ProxyAgent } from 'undici'
const agent = new Socks5ProxyAgent('socks5://localhost:1080')
const { statusCode, body } = await request('http://localhost:3000/foo', {
dispatcher: agent
})
console.log('response received', statusCode)
```
HTTPS targets are tunnelled and encrypted end-to-end:
```mjs
import { request, Socks5ProxyAgent } from 'undici'
const agent = new Socks5ProxyAgent('socks5://localhost:1080')
const { statusCode, body } = await request('https://api.example.com/data', {
dispatcher: agent
})
console.log('Response status:', statusCode)
console.log('Response data:', await body.json())
```
### `socks5ProxyAgent.close()`
<!-- YAML
added: v7.23.0
-->
> Stability: 1 - Experimental
* Returns: {Promise<void>} Resolves once every per-origin pool has been closed.
Gracefully closes the agent, waiting for all underlying pools and their
connections to drain and close before resolving.
```mjs
import { setGlobalDispatcher, Socks5ProxyAgent } from 'undici'
const agent = new Socks5ProxyAgent('socks5://localhost:1080')
setGlobalDispatcher(agent)
// ... make requests ...
await agent.close()
```
### `socks5ProxyAgent.destroy([err])`
<!-- YAML
added: v7.23.0
-->
> Stability: 1 - Experimental
* `err` {Error} (optional) The error to reject in-flight requests with.
* Returns: {Promise<void>} Resolves once every per-origin pool has been
destroyed.
Forcibly destroys the agent and all underlying connections immediately, without
waiting for in-flight requests to complete.
```mjs
import { Socks5ProxyAgent } from 'undici'
const agent = new Socks5ProxyAgent('socks5://localhost:1080')
await agent.destroy()
```
### `socks5ProxyAgent.dispatch(options, handlers)`
<!-- YAML
added: v7.23.0
-->
> Stability: 1 - Experimental
* `options` {DispatchOptions}
* `handlers` {DispatchHandler}
* Returns: {boolean} `false` if the dispatcher is busy and the request should be
retried later, otherwise `true`.
Routes a request through the SOCKS5 tunnel. The agent maintains a [`Pool`][] per
target origin; the first request to a given origin establishes the tunnel and
upgrades to TLS when the target is HTTPS, and later requests reuse the pool.
This is the lower-level entry point implementing
[`Dispatcher.dispatch(options, handlers)`][]. Prefer
[`socks5ProxyAgent.request()`][] for most use cases.
### `socks5ProxyAgent.request(options[, callback])`
<!-- YAML
added: v7.23.0
-->
> Stability: 1 - Experimental
* `options` {DispatchOptions}
* `callback` {Function} (optional)
* Returns: {Promise|void} A promise resolving to the response when `callback` is
omitted.
Performs a request through the SOCKS5 proxy. Inherited from
[`Dispatcher.request(options[, callback])`][]; see that method for the full set
of options and the shape of the resolved response.
```mjs
import { fetch, Socks5ProxyAgent } from 'undici'
const agent = new Socks5ProxyAgent('socks5://localhost:1080')
const response = await fetch('http://localhost:3000/api/users', {
dispatcher: agent
})
console.log('Response status:', response.status)
console.log('Response data:', await response.text())
```
## Debugging
SOCKS5 proxy activity can be traced with the `undici:socks5-proxy` debug scope:
```bash
NODE_DEBUG=undici:socks5-proxy node script.js
```
This logs the SOCKS5 handshake, authentication, and tunnel establishment steps.
[SOCKS5]: https://www.rfc-editor.org/rfc/rfc1928
[`Dispatcher.dispatch(options, handlers)`]: Dispatcher.md#dispatcherdispatchoptions-handler
[`Dispatcher.request(options[, callback])`]: Dispatcher.md#dispatcherrequestoptions-callback
[`Dispatcher`]: Dispatcher.md#class-dispatcher
[`Pool`]: Pool.md#class-pool
[`setGlobalDispatcher()`]: Dispatcher.md#setglobaldispatcherdispatcher
[`socks5ProxyAgent.request()`]: #socks5proxyagentrequestoptions-callback
@@ -0,0 +1,12 @@
import type * as ts from 'typescript';
export declare enum AnyType {
Any = 0,
PromiseAny = 1,
AnyArray = 2,
Safe = 3
}
/**
* @returns `AnyType.Any` if the type is `any`, `AnyType.AnyArray` if the type is `any[]` or `readonly any[]`, `AnyType.PromiseAny` if the type is `Promise<any>`,
* otherwise it returns `AnyType.Safe`.
*/
export declare function discriminateAnyType(type: ts.Type, checker: ts.TypeChecker, program: ts.Program, tsNode: ts.Node): AnyType;
@@ -0,0 +1,107 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = cloneNode;
var _index = require("../definitions/index.js");
var _index2 = require("../validators/generated/index.js");
const {
hasOwn
} = {
hasOwn: Function.call.bind(Object.prototype.hasOwnProperty)
};
function cloneIfNode(obj, deep, withoutLoc, commentsCache) {
if (obj && typeof obj.type === "string") {
return cloneNodeInternal(obj, deep, withoutLoc, commentsCache);
}
return obj;
}
function cloneIfNodeOrArray(obj, deep, withoutLoc, commentsCache) {
if (Array.isArray(obj)) {
return obj.map(node => cloneIfNode(node, deep, withoutLoc, commentsCache));
}
return cloneIfNode(obj, deep, withoutLoc, commentsCache);
}
function cloneNode(node, deep = true, withoutLoc = false) {
return cloneNodeInternal(node, deep, withoutLoc, new Map());
}
function cloneNodeInternal(node, deep = true, withoutLoc = false, commentsCache) {
if (!node) return node;
const {
type
} = node;
const newNode = {
type: node.type
};
if ((0, _index2.isIdentifier)(node)) {
newNode.name = node.name;
if (hasOwn(node, "optional") && typeof node.optional === "boolean") {
newNode.optional = node.optional;
}
if (hasOwn(node, "typeAnnotation")) {
newNode.typeAnnotation = deep ? cloneIfNodeOrArray(node.typeAnnotation, true, withoutLoc, commentsCache) : node.typeAnnotation;
}
if (hasOwn(node, "decorators")) {
newNode.decorators = deep ? cloneIfNodeOrArray(node.decorators, true, withoutLoc, commentsCache) : node.decorators;
}
} else if (!hasOwn(_index.NODE_FIELDS, type)) {
throw new Error(`Unknown node type: "${type}"`);
} else {
for (const field of Object.keys(_index.NODE_FIELDS[type])) {
if (hasOwn(node, field)) {
if (deep) {
newNode[field] = (0, _index2.isFile)(node) && field === "comments" ? maybeCloneComments(node.comments, deep, withoutLoc, commentsCache) : cloneIfNodeOrArray(node[field], true, withoutLoc, commentsCache);
} else {
newNode[field] = node[field];
}
}
}
}
if (hasOwn(node, "loc")) {
if (withoutLoc) {
newNode.loc = null;
} else {
newNode.loc = node.loc;
}
}
if (hasOwn(node, "leadingComments")) {
newNode.leadingComments = maybeCloneComments(node.leadingComments, deep, withoutLoc, commentsCache);
}
if (hasOwn(node, "innerComments")) {
newNode.innerComments = maybeCloneComments(node.innerComments, deep, withoutLoc, commentsCache);
}
if (hasOwn(node, "trailingComments")) {
newNode.trailingComments = maybeCloneComments(node.trailingComments, deep, withoutLoc, commentsCache);
}
if (hasOwn(node, "extra")) {
newNode.extra = Object.assign({}, node.extra);
}
return newNode;
}
function maybeCloneComments(comments, deep, withoutLoc, commentsCache) {
if (!comments || !deep) {
return comments;
}
return comments.map(comment => {
const cache = commentsCache.get(comment);
if (cache) return cache;
const {
type,
value,
loc
} = comment;
const ret = {
type,
value,
loc
};
if (withoutLoc) {
ret.loc = null;
}
commentsCache.set(comment, ret);
return ret;
});
}
//# sourceMappingURL=cloneNode.js.map
@@ -0,0 +1,134 @@
<p align="center">
<a href="https://gulpjs.com">
<img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png">
</a>
</p>
# glob-parent
[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Coveralls Status][coveralls-image]][coveralls-url]
Extract the non-magic parent path from a glob string.
## Usage
```js
var globParent = require('glob-parent');
globParent('path/to/*.js'); // 'path/to'
globParent('/root/path/to/*.js'); // '/root/path/to'
globParent('/*.js'); // '/'
globParent('*.js'); // '.'
globParent('**/*.js'); // '.'
globParent('path/{to,from}'); // 'path'
globParent('path/!(to|from)'); // 'path'
globParent('path/?(to|from)'); // 'path'
globParent('path/+(to|from)'); // 'path'
globParent('path/*(to|from)'); // 'path'
globParent('path/@(to|from)'); // 'path'
globParent('path/**/*'); // 'path'
// if provided a non-glob path, returns the nearest dir
globParent('path/foo/bar.js'); // 'path/foo'
globParent('path/foo/'); // 'path/foo'
globParent('path/foo'); // 'path' (see issue #3 for details)
```
## API
### `globParent(maybeGlobString, [options])`
Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below.
#### options
```js
{
// Disables the automatic conversion of slashes for Windows
flipBackslashes: true;
}
```
## Escaping
The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters:
- `?` (question mark) unless used as a path segment alone
- `*` (asterisk)
- `|` (pipe)
- `(` (opening parenthesis)
- `)` (closing parenthesis)
- `{` (opening curly brace)
- `}` (closing curly brace)
- `[` (opening bracket)
- `]` (closing bracket)
**Example**
```js
globParent('foo/[bar]/'); // 'foo'
globParent('foo/\\[bar]/'); // 'foo/[bar]'
```
## Limitations
### Braces & Brackets
This library attempts a quick and imperfect method of determining which path
parts have glob magic without fully parsing/lexing the pattern. There are some
advanced use cases that can trip it up, such as nested braces where the outer
pair is escaped and the inner one contains a path separator. If you find
yourself in the unlikely circumstance of being affected by this or need to
ensure higher-fidelity glob handling in your library, it is recommended that you
pre-process your input with [expand-braces] and/or [expand-brackets].
### Windows
Backslashes are not valid path separators for globs. If a path with backslashes
is provided anyway, for simple cases, glob-parent will replace the path
separator for you and return the non-glob parent path (now with
forward-slashes, which are still valid as Windows path separators).
This cannot be used in conjunction with escape characters.
```js
// BAD
globParent('C:\\Program Files \\(x86\\)\\*.ext'); // 'C:/Program Files /(x86/)'
// GOOD
globParent('C:/Program Files\\(x86\\)/*.ext'); // 'C:/Program Files (x86)'
```
If you are using escape characters for a pattern without path parts (i.e.
relative to `cwd`), prefix with `./` to avoid confusing glob-parent.
```js
// BAD
globParent('foo \\[bar]'); // 'foo '
globParent('foo \\[bar]*'); // 'foo '
// GOOD
globParent('./foo \\[bar]'); // 'foo [bar]'
globParent('./foo \\[bar]*'); // '.'
```
## License
ISC
<!-- prettier-ignore-start -->
[downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg?style=flat-square
[npm-url]: https://www.npmjs.com/package/glob-parent
[npm-image]: https://img.shields.io/npm/v/glob-parent.svg?style=flat-square
[ci-url]: https://github.com/gulpjs/glob-parent/actions?query=workflow:dev
[ci-image]: https://img.shields.io/github/workflow/status/gulpjs/glob-parent/dev?style=flat-square
[coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent
[coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg?style=flat-square
<!-- prettier-ignore-end -->
<!-- prettier-ignore-start -->
[expand-braces]: https://github.com/jonschlinkert/expand-braces
[expand-brackets]: https://github.com/jonschlinkert/expand-brackets
<!-- prettier-ignore-end -->
@@ -0,0 +1 @@
{"version":3,"file":"size-rollup-waapi-animate.js","sources":["../../motion-utils/dist/es/errors.mjs","../../motion-utils/dist/es/format-error-message.mjs","../../motion-utils/dist/es/noop.mjs","../../motion-utils/dist/es/time-conversion.mjs","../../motion-dom/dist/es/animation/keyframes/get-final.mjs","../../motion-dom/dist/es/animation/utils/WithPromise.mjs","../../motion-dom/dist/es/animation/keyframes/utils/fill-wildcards.mjs","../../motion-dom/dist/es/render/dom/is-css-var.mjs","../../motion-dom/dist/es/utils/supports/flags.mjs","../../motion-dom/dist/es/utils/supports/memo.mjs","../../motion-utils/dist/es/memo.mjs","../../motion-dom/dist/es/utils/supports/scroll-timeline.mjs","../../motion-dom/dist/es/utils/supports/linear-easing.mjs","../../motion-dom/dist/es/animation/waapi/easing/cubic-bezier.mjs","../../motion-dom/dist/es/animation/waapi/easing/supported.mjs","../../motion-dom/dist/es/animation/waapi/easing/map-easing.mjs","../../motion-dom/dist/es/animation/waapi/utils/linear.mjs","../../motion-utils/dist/es/easing/utils/is-bezier-definition.mjs","../../motion-dom/dist/es/animation/NativeAnimation.mjs","../../motion-dom/dist/es/animation/waapi/utils/apply-generator.mjs","../../motion-dom/dist/es/animation/generators/utils/is-generator.mjs","../../motion-dom/dist/es/animation/waapi/start-waapi-animation.mjs","../../motion-dom/dist/es/render/dom/style-set.mjs","../../motion-dom/dist/es/animation/GroupAnimation.mjs","../../motion-dom/dist/es/animation/GroupAnimationWithThen.mjs","../../motion-dom/dist/es/animation/utils/active-animations.mjs","../../motion-dom/dist/es/animation/utils/get-value-transition.mjs","../../motion-dom/dist/es/animation/utils/resolve-transition.mjs","../../motion-dom/dist/es/animation/waapi/utils/px-values.mjs","../../motion-dom/dist/es/animation/keyframes/utils/apply-px-defaults.mjs","../../motion-dom/dist/es/render/dom/style-computed.mjs","../lib/animation/animators/waapi/animate-elements.js","../../motion-dom/dist/es/utils/resolve-elements.mjs","../lib/animation/animators/waapi/animate-style.js"],"sourcesContent":["import { formatErrorMessage } from './format-error-message.mjs';\n\nlet warning = () => { };\nlet invariant = () => { };\nif (typeof process !== \"undefined\" &&\n process.env?.NODE_ENV !== \"production\") {\n warning = (check, message, errorCode) => {\n if (!check && typeof console !== \"undefined\") {\n console.warn(formatErrorMessage(message, errorCode));\n }\n };\n invariant = (check, message, errorCode) => {\n if (!check) {\n throw new Error(formatErrorMessage(message, errorCode));\n }\n };\n}\n\nexport { invariant, warning };\n//# sourceMappingURL=errors.mjs.map\n","function formatErrorMessage(message, errorCode) {\n return errorCode\n ? `${message}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${errorCode}`\n : message;\n}\n\nexport { formatErrorMessage };\n//# sourceMappingURL=format-error-message.mjs.map\n","/*#__NO_SIDE_EFFECTS__*/\nconst noop = (any) => any;\n\nexport { noop };\n//# sourceMappingURL=noop.mjs.map\n","/**\n * Converts seconds to milliseconds\n *\n * @param seconds - Time in seconds.\n * @return milliseconds - Converted time in milliseconds.\n */\n/*#__NO_SIDE_EFFECTS__*/\nconst secondsToMilliseconds = (seconds) => seconds * 1000;\n/*#__NO_SIDE_EFFECTS__*/\nconst millisecondsToSeconds = (milliseconds) => milliseconds / 1000;\n\nexport { millisecondsToSeconds, secondsToMilliseconds };\n//# sourceMappingURL=time-conversion.mjs.map\n","const isNotNull = (value) => value !== null;\nfunction getFinalKeyframe(keyframes, { repeat, repeatType = \"loop\" }, finalKeyframe, speed = 1) {\n const resolvedKeyframes = keyframes.filter(isNotNull);\n const useFirstKeyframe = speed < 0 || (repeat && repeatType !== \"loop\" && repeat % 2 === 1);\n const index = useFirstKeyframe ? 0 : resolvedKeyframes.length - 1;\n return !index || finalKeyframe === undefined\n ? resolvedKeyframes[index]\n : finalKeyframe;\n}\n\nexport { getFinalKeyframe };\n//# sourceMappingURL=get-final.mjs.map\n","class WithPromise {\n constructor() {\n this.updateFinished();\n }\n get finished() {\n return this._finished;\n }\n updateFinished() {\n this._finished = new Promise((resolve) => {\n this.resolve = resolve;\n });\n }\n notifyFinished() {\n this.resolve();\n }\n /**\n * Allows the animation to be awaited.\n *\n * @deprecated Use `finished` instead.\n */\n then(onResolve, onReject) {\n return this.finished.then(onResolve, onReject);\n }\n}\n\nexport { WithPromise };\n//# sourceMappingURL=WithPromise.mjs.map\n","function fillWildcards(keyframes) {\n for (let i = 1; i < keyframes.length; i++) {\n keyframes[i] ?? (keyframes[i] = keyframes[i - 1]);\n }\n}\n\nexport { fillWildcards };\n//# sourceMappingURL=fill-wildcards.mLine truncated
@@ -0,0 +1,32 @@
import { alpha, scale } from '../numbers/index.mjs';
import { px, progressPercentage, degrees } from '../numbers/units.mjs';
const transformValueTypes = {
rotate: degrees,
rotateX: degrees,
rotateY: degrees,
rotateZ: degrees,
scale,
scaleX: scale,
scaleY: scale,
scaleZ: scale,
skew: degrees,
skewX: degrees,
skewY: degrees,
distance: px,
translateX: px,
translateY: px,
translateZ: px,
x: px,
y: px,
z: px,
perspective: px,
transformPerspective: px,
opacity: alpha,
originX: progressPercentage,
originY: progressPercentage,
originZ: px,
};
export { transformValueTypes };
//# sourceMappingURL=transform.mjs.map
@@ -0,0 +1,226 @@
# proc-log
Emits events on the process object which a listener can consume and print to the terminal or log file.
This is used by various modules within the npm CLI stack in order to send log events that can be consumed by a listener on the process object.
Currently emits `log`, `output`, `input`, and `time` events.
## API
```js
const { log, output, input, time } = require('proc-log')
```
#### output
* `output.standard(...args)` calls `process.emit('output', 'standard', ...args)`
This is for general standard output. Consumers will typically show this on stdout (after optionally formatting or filtering it).
* `output.error(...args)` calls `process.emit('output', 'error', ...args)`
This is for general error output. Consumers will typically show this on stderr (after optionally formatting or filtering it).
* `output.buffer(...args)` calls `process.emit('output', 'buffer', ...args)`
This is for buffered output. Consumers will typically buffer this until they are ready to display.
* `output.flush(...args)` calls `process.emit('output', 'flush', ...args)`
This is to indicate that the output buffer should be flushed.
* `output.LEVELS` an array of strings of all output method names
#### log
* `log.error(...args)` calls `process.emit('log', 'error', ...args)`
The highest log level. For printing extremely serious errors that indicate something went wrong.
* `log.warn(...args)` calls `process.emit('log', 'warn', ...args)`
A fairly high log level. Things that the user needs to be aware of, but which won't necessarily cause improper functioning of the system.
* `log.notice(...args)` calls `process.emit('log', 'notice', ...args)`
Notices which are important, but not necessarily dangerous or a cause for excess concern.
* `log.info(...args)` calls `process.emit('log', 'info', ...args)`
Informative messages that may benefit the user, but aren't particularly important.
* `log.verbose(...args)` calls `process.emit('log', 'verbose', ...args)`
Noisy output that is more detail that most users will care about.
* `log.silly(...args)` calls `process.emit('log', 'silly', ...args)`
Extremely noisy excessive logging messages that are typically only useful for debugging.
* `log.http(...args)` calls `process.emit('log', 'http', ...args)`
Information about HTTP requests made and/or completed.
* `log.timing(...args)` calls `process.emit('log', 'timing', ...args)`
Timing information.
* `log.pause()` calls `process.emit('log', 'pause')`
Used to tell the consumer to stop printing messages.
* `log.resume()` calls `process.emit('log', 'resume')`
Used to tell the consumer that it is ok to print messages again.
* `log.LEVELS` an array of strings of all log method names
#### input
* `input.start(...args)` calls `process.emit('input', 'start', ...args)`
Used to tell the consumer that the terminal is going to begin reading user input. Returns a function that will call `input.end(...args)` for convenience.
If the first argument is a function, it will be used as a callback which runs `input.end()` on its completion. If the callback returns a `Promise` then `input.end(...args)` will be run during `finally()`.
* `input.end(...args)` calls `process.emit('input', 'end', ...args)`
Used to tell the consumer that the terminal has stopped reading user input.
* `input.read(...args): Promise` calls `process.emit('input', 'read', resolve, reject, ...args)`
Used to tell the consumer that the terminal is reading user input and returns a `Promise` that the producer can `await` until the consumer has finished its async action.
This emits `resolve` and `reject` functions (in addition to all passed in arguments) which the consumer must use to resolve the returned `Promise`.
#### time
* `time.start(timerName, fn?)` calls `process.emit('time', 'start', 'timerName')`
Used to start a timer with the specified name. Returns a function that will call `time.end()` for convenience.
This also takes an optional callback which will run `time.end()` on its completion. If the callback returns a `Promise` then `time.end()` will be run during `finally()`.
* `time.end(timerName)` calls `process.emit('time', 'end', timeName)`
Used to tell the consumer to stop a timer with the specified name.
## Examples
### log
Every `log` method calls `process.emit('log', level, ...otherArgs)` internally. So in order to consume those events you need to do `process.on('log', fn)`.
#### Colorize based on level
Here's an example of how to consume `proc-log` log events and colorize them based on level:
```js
const chalk = require('chalk')
process.on('log', (level, ...args) => {
if (level === 'error') {
console.log(chalk.red(level), ...args)
} else {
console.log(chalk.blue(level), ...args)
}
})
```
#### Pause and resume
`log.pause` and `log.resume` are included so you have the ability to tell your consumer that you want to pause or resume your display of logs. In the npm CLI we use this to buffer all logs on init until we know the correct loglevel to display. But we also setup a second handler that writes everything to a file even if paused.
```js
let paused = true
const buffer = []
// this handler will buffer and replay logs only after `procLog.resume()` is called
process.on('log', (level, ...args) => {
if (level === 'resume') {
buffer.forEach((item) => console.log(...item))
paused = false
return
} 
if (paused) {
buffer.push([level, ...args])
} else {
console.log(level, ...args)
}
})
// this handler will write everything to a file
process.on('log', (...args) => {
fs.appendFileSync('debug.log', args.join(' '))
})
```
### input
### `start` and `end`
**producer.js**
```js
const { output, input } = require('proc-log')
const { readFromUserInput } = require('./my-read')
// Using callback passed to `start`
try {
const res = await input.start(
readFromUserInput({ prompt: 'OK?', default: 'y' })
)
output.standard(`User said ${res}`)
} catch (err) {
output.error(`User cancelled: ${err}`)
}
// Manually calling `start` and `end`
try {
input.start()
const res = await readFromUserInput({ prompt: 'OK?', default: 'y' })
output.standard(`User said ${res}`)
} catch (err) {
output.error(`User cancelled: ${err}`)
} finally {
input.end()
}
```
**consumer.js**
```js
const { read } = require('read')
process.on('input', (level) => {
if (level === 'start') {
// Hide UI to make room for user input being read
} else if (level === 'end') {
// Restore UI now that reading is ended
}
})
```
### Using `read` to call `read()`
**producer.js**
```js
const { output, input } = require('proc-log')
try {
const res = await input.read({ prompt: 'OK?', default: 'y' })
output.standard(`User said ${res}`)
} catch (err) {
output.error(`User cancelled: ${err}`)
}
```
**consumer.js**
```js
const { read } = require('read')
process.on('input', (level, ...args) => {
if (level === 'read') {
const [res, rej, opts] = args
read(opts).then(res).catch(rej)
}
})
```
@@ -0,0 +1,85 @@
import { t as require_binding } from "./binding-TuFFIE_J.mjs";
//#region src/types/sourcemap.ts
function bindingifySourcemap(map) {
if (map == null) return;
return { inner: typeof map === "string" ? map : {
file: map.file ?? void 0,
mappings: map.mappings,
sourceRoot: "sourceRoot" in map ? map.sourceRoot ?? void 0 : void 0,
sources: map.sources?.map((s) => s ?? void 0),
sourcesContent: map.sourcesContent?.map((s) => s ?? void 0),
names: map.names,
x_google_ignoreList: map.x_google_ignoreList,
debugId: "debugId" in map ? map.debugId : void 0
} };
}
require_binding();
function unwrapBindingResult(container) {
if (typeof container === "object" && container !== null && "isBindingErrors" in container && container.isBindingErrors) throw aggregateBindingErrorsIntoJsError(container.errors);
return container;
}
function normalizeBindingResult(container) {
if (typeof container === "object" && container !== null && "isBindingErrors" in container && container.isBindingErrors) return aggregateBindingErrorsIntoJsError(container.errors);
return container;
}
function normalizeBindingError(e) {
return e.type === "JsError" ? e.field0 : Object.assign(/* @__PURE__ */ new Error(), {
code: e.field0.kind,
kind: e.field0.kind,
message: e.field0.message,
id: e.field0.id,
exporter: e.field0.exporter,
loc: e.field0.loc,
pos: e.field0.pos,
stack: void 0
});
}
function aggregateBindingErrorsIntoJsError(rawErrors) {
const errors = rawErrors.map(normalizeBindingError);
let summary = `Build failed with ${errors.length} error${errors.length < 2 ? "" : "s"}:\n`;
for (let i = 0; i < errors.length; i++) {
summary += "\n";
if (i >= 5) {
summary += "...";
break;
}
summary += getErrorMessage(errors[i]);
}
const wrapper = new Error(summary);
Object.defineProperty(wrapper, "errors", {
configurable: true,
enumerable: true,
get: () => errors,
set: (value) => Object.defineProperty(wrapper, "errors", {
configurable: true,
enumerable: true,
value
})
});
return wrapper;
}
function getErrorMessage(e) {
if (Object.hasOwn(e, "kind")) return e.message;
let s = "";
if (e.plugin) s += `[plugin ${e.plugin}]`;
const id = e.id ?? e.loc?.file;
if (id) {
s += " " + id;
if (e.loc) s += `:${e.loc.line}:${e.loc.column}`;
}
if (s) s += "\n";
const message = `${e.name ?? "Error"}: ${e.message}`;
s += message;
if (e.frame) s = joinNewLine(s, e.frame);
if (e.stack) s = joinNewLine(s, e.stack.replace(message, ""));
if (e.cause) {
s = joinNewLine(s, "Caused by:");
s = joinNewLine(s, getErrorMessage(e.cause).split("\n").map((line) => " " + line).join("\n"));
}
return s;
}
function joinNewLine(s1, s2) {
return s1.replace(/\n+$/, "") + "\n" + s2.replace(/^\n+/, "");
}
//#endregion
export { bindingifySourcemap as a, unwrapBindingResult as i, normalizeBindingError as n, normalizeBindingResult as r, aggregateBindingErrorsIntoJsError as t };
@@ -0,0 +1,3 @@
export * from './index.cjs';
export { notFound, isNotFound, redirect, isRedirect, rootRouteId, } from '@tanstack/router-core';
export type { NotFoundError } from '@tanstack/router-core';
@@ -0,0 +1,15 @@
(The MIT License)
Copyright (c) 2012-2015, JP Richardson <jprichardson@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
(the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,162 @@
<h1 align=center>
<a href="http://chaijs.com" title="Chai Documentation">
<img alt="ChaiJS" src="http://chaijs.com/img/chai-logo.png">
</a>
<br>
chai
</h1>
<p align=center>
Chai is a BDD / TDD assertion library for <a href="http://nodejs.org">node</a> and the browser that can be delightfully paired with any javascript testing framework.
</p>
<p align=center>
<a href="https://www.npmjs.com/package/chai">
<img
alt="downloads:?"
src="https://img.shields.io/npm/dm/chai.svg?style=flat-square"
/>
</a>
<a href="https://www.npmjs.com/package/chai">
<img
alt="node:?"
src="https://img.shields.io/badge/node-%3E=18.0-blue.svg?style=flat-square"
/>
</a>
<br/>
<a href="https://chai-slack.herokuapp.com/">
<img
alt="Join the Slack chat"
src="https://img.shields.io/badge/slack-join%20chat-E2206F.svg?style=flat-square"
/>
</a>
<a href="https://gitter.im/chaijs/chai">
<img
alt="Join the Gitter chat"
src="https://img.shields.io/badge/gitter-join%20chat-D0104D.svg?style=flat-square"
/>
</a>
<a href="https://opencollective.com/chaijs">
<img
alt="OpenCollective Backers"
src="https://opencollective.com/chaijs/backers/badge.svg?style=flat-square"
/>
</a>
</p>
For more information or to download plugins, view the [documentation](http://chaijs.com).
## What is Chai?
Chai is an _assertion library_, similar to Node's built-in `assert`. It makes testing much easier by giving you lots of assertions you can run against your code.
## Installation
### Node.js
`chai` is available on [npm](http://npmjs.org). To install it, type:
$ npm install --save-dev chai
### Browsers
You can also use it within the browser; install via npm and use the `index.js` file found within the download. For example:
```html
<script src="./node_modules/chai/index.js" type="module"></script>
```
## Usage
Import the library in your code, and then pick one of the styles you'd like to use - either `assert`, `expect` or `should`:
```js
import { assert } from 'chai'; // Using Assert style
import { expect } from 'chai'; // Using Expect style
import { should } from 'chai'; // Using Should style
```
### Register the chai testing style globally
```js
import 'chai/register-assert'; // Using Assert style
import 'chai/register-expect'; // Using Expect style
import 'chai/register-should'; // Using Should style
```
### Import assertion styles as local variables
```js
import { assert } from 'chai'; // Using Assert style
import { expect } from 'chai'; // Using Expect style
import { should } from 'chai'; // Using Should style
should(); // Modifies `Object.prototype`
import { expect, use } from 'chai'; // Creates local variables `expect` and `use`; useful for plugin use
```
### Usage with Mocha
```bash
mocha spec.js --require chai/register-assert.js # Using Assert style
mocha spec.js --require chai/register-expect.js # Using Expect style
mocha spec.js --require chai/register-should.js # Using Should style
```
[Read more about these styles in our docs](http://chaijs.com/guide/styles/).
## Plugins
Chai offers a robust Plugin architecture for extending Chai's assertions and interfaces.
- Need a plugin? View the [official plugin list](http://chaijs.com/plugins).
- Want to build a plugin? Read the [plugin api documentation](http://chaijs.com/guide/plugins/).
- Have a plugin and want it listed? Simply add the following keywords to your package.json:
- `chai-plugin`
- `browser` if your plugin works in the browser as well as Node.js
- `browser-only` if your plugin does not work with Node.js
### Related Projects
- [chaijs / chai-docs](https://github.com/chaijs/chai-docs): The chaijs.com website source code.
- [chaijs / assertion-error](https://github.com/chaijs/assertion-error): Custom `Error` constructor thrown upon an assertion failing.
- [chaijs / deep-eql](https://github.com/chaijs/deep-eql): Improved deep equality testing for Node.js and the browser.
- [chaijs / check-error](https://github.com/chaijs/check-error): Error comparison and information related utility for Node.js and the browser.
- [chaijs / loupe](https://github.com/chaijs/loupe): Inspect utility for Node.js and browsers.
- [chaijs / pathval](https://github.com/chaijs/pathval): Object value retrieval given a string path.
### Contributing
Thank you very much for considering to contribute!
Please make sure you follow our [Code Of Conduct](https://github.com/chaijs/chai/blob/master/CODE_OF_CONDUCT.md) and we also strongly recommend reading our [Contributing Guide](https://github.com/chaijs/chai/blob/master/CONTRIBUTING.md).
Here are a few issues other contributors frequently ran into when opening pull requests:
- Please do not commit changes to the `chai.js` build. We do it once per release.
- Before pushing your commits, please make sure you [rebase](https://github.com/chaijs/chai/blob/master/CONTRIBUTING.md#pull-requests) them.
### Contributors
Please see the full
[Contributors Graph](https://github.com/chaijs/chai/graphs/contributors) for our
list of contributors.
### Core Contributors
Feel free to reach out to any of the core contributors with your questions or
concerns. We will do our best to respond in a timely manner.
[![Keith Cirkel](https://avatars3.githubusercontent.com/u/118266?v=3&s=50)](https://github.com/keithamus)
[![James Garbutt](https://avatars3.githubusercontent.com/u/5677153?v=3&s=50)](https://github.com/43081j)
[![Kristján Oddsson](https://avatars3.githubusercontent.com/u/318208?v=3&s=50)](https://github.com/koddsson)
### Core Contributor Alumni
This project would not be what it is without the contributions from our prior
core contributors, for whom we are forever grateful:
[![Jake Luer](https://avatars3.githubusercontent.com/u/58988?v=3&s=50)](https://github.com/logicalparadox)
[![Veselin Todorov](https://avatars3.githubusercontent.com/u/330048?v=3&s=50)](https://github.com/vesln)
[![Lucas Fernandes da Costa](https://avatars3.githubusercontent.com/u/6868147?v=3&s=50)](https://github.com/lucasfcosta)
[![Grant Snodgrass](https://avatars3.githubusercontent.com/u/17260989?v=3&s=50)](https://github.com/meeber)
@@ -0,0 +1,17 @@
/**
* @license lucide-react v0.469.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const SearchSlash = createLucideIcon("SearchSlash", [
["path", { d: "m13.5 8.5-5 5", key: "1cs55j" }],
["circle", { cx: "11", cy: "11", r: "8", key: "4ej97u" }],
["path", { d: "m21 21-4.3-4.3", key: "1qie3q" }]
]);
export { SearchSlash as default };
//# sourceMappingURL=search-slash.js.map
@@ -0,0 +1,160 @@
'use strict'
const {
wellknownHeaderNames,
headerNameLowerCasedRecord
} = require('./constants')
class TstNode {
/** @type {any} */
value = null
/** @type {null | TstNode} */
left = null
/** @type {null | TstNode} */
middle = null
/** @type {null | TstNode} */
right = null
/** @type {number} */
code
/**
* @param {string} key
* @param {any} value
* @param {number} index
*/
constructor (key, value, index) {
if (index === undefined || index >= key.length) {
throw new TypeError('Unreachable')
}
const code = this.code = key.charCodeAt(index)
// check code is ascii string
if (code > 0x7F) {
throw new TypeError('key must be ascii string')
}
if (key.length !== ++index) {
this.middle = new TstNode(key, value, index)
} else {
this.value = value
}
}
/**
* @param {string} key
* @param {any} value
* @returns {void}
*/
add (key, value) {
const length = key.length
if (length === 0) {
throw new TypeError('Unreachable')
}
let index = 0
/**
* @type {TstNode}
*/
let node = this
while (true) {
const code = key.charCodeAt(index)
// check code is ascii string
if (code > 0x7F) {
throw new TypeError('key must be ascii string')
}
if (node.code === code) {
if (length === ++index) {
node.value = value
break
} else if (node.middle !== null) {
node = node.middle
} else {
node.middle = new TstNode(key, value, index)
break
}
} else if (node.code < code) {
if (node.left !== null) {
node = node.left
} else {
node.left = new TstNode(key, value, index)
break
}
} else if (node.right !== null) {
node = node.right
} else {
node.right = new TstNode(key, value, index)
break
}
}
}
/**
* @param {Uint8Array} key
* @returns {TstNode | null}
*/
search (key) {
const keylength = key.length
let index = 0
/**
* @type {TstNode|null}
*/
let node = this
while (node !== null && index < keylength) {
let code = key[index]
// A-Z
// First check if it is bigger than 0x5a.
// Lowercase letters have higher char codes than uppercase ones.
// Also we assume that headers will mostly contain lowercase characters.
if (code <= 0x5a && code >= 0x41) {
// Lowercase for uppercase.
code |= 32
}
while (node !== null) {
if (code === node.code) {
if (keylength === ++index) {
// Returns Node since it is the last key.
return node
}
node = node.middle
break
}
node = node.code < code ? node.left : node.right
}
}
return null
}
}
class TernarySearchTree {
/** @type {TstNode | null} */
node = null
/**
* @param {string} key
* @param {any} value
* @returns {void}
* */
insert (key, value) {
if (this.node === null) {
this.node = new TstNode(key, value, 0)
} else {
this.node.add(key, value)
}
}
/**
* @param {Uint8Array} key
* @returns {any}
*/
lookup (key) {
return this.node?.search(key)?.value ?? null
}
}
const tree = new TernarySearchTree()
for (let i = 0; i < wellknownHeaderNames.length; ++i) {
const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]]
tree.insert(key, key)
}
module.exports = {
TernarySearchTree,
tree
}
@@ -0,0 +1,362 @@
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "tsup",
"version": 1.1,
"anyOf": [
{
"type": "object",
"required": ["tsup"],
"additionalProperties": true,
"properties": {
"tsup": {
"type": ["object", "array"],
"oneOf": [
{
"type": "object",
"additionalProperties": false,
"$ref": "#/definitions/options"
},
{
"type": "array",
"items": {
"additionalProperties": false,
"$ref": "#/definitions/options"
}
}
]
}
}
},
{
"type": ["object", "array"],
"oneOf": [
{
"type": "object",
"$ref": "#/definitions/options"
},
{
"type": "array",
"items": {
"$ref": "#/definitions/options"
}
}
]
}
],
"definitions": {
"options": {
"type": "object",
"markdownDescription": "Configuration options for [tsup](https://tsup.egoist.dev)",
"properties": {
"entry": {
"markdownDescription": "Files that each serve as an input to the bundling algorithm.\n\n---\nReferences:\n- [Entry Points](https://esbuild.github.io/api/#entry-points) - esbuild\n - [Multiple Entrypoints](https://tsup.egoist.dev/#multiple-entrypoints) - tsup",
"oneOf": [
{
"type": "array",
"items": {
"type": "string"
}
},
{
"type": "object"
}
]
},
"treeshake": {
"markdownDescription": "By default esbuild already does treeshaking but this option allow you to perform additional treeshaking with Rollup and result in smaller bundle size.",
"oneOf": [
{
"type": "boolean"
},
{
"type": "string",
"enum": ["smallest", "safest", "recommended"]
}
]
},
"name": {
"type": "string",
"description": "Optional config name to show in CLI output"
},
"legacyOutput": {
"type": "boolean",
"description": "Output different formats to different folder instead of using different extension"
},
"target": {
"markdownDescription": "This sets the target environment for the generated code\n\n---\nReferences:\n- [Target](https://esbuild.github.io/api/#target) - esbuild",
"default": "node14",
"oneOf": [
{
"type": "string"
},
{
"type": "array",
"items": {
"type": "string"
}
}
]
},
"minify": {
"description": "When enabled, the generated code will be minified instead of pretty-printed.",
"oneOf": [
{
"type": "boolean"
},
{
"type": "string",
"enum": ["terser"]
}
]
},
"minifyWhitespace": {
"type": "boolean"
},
"minifyIdentifiers": {
"type": "boolean"
},
"minifySyntax": {
"type": "boolean"
},
"keepNames": {
"type": "boolean"
},
"watch": {
"oneOf": [
{
"type": "boolean"
},
{
"type": "string",
"items": {
"type": "string"
}
},
{
"type": "array",
"items": {
"type": ["string", "boolean"]
}
}
]
},
"ignoreWatch": {
"oneOf": [
{
"type": "string"
},
{
"type": "array",
"items": {
"type": "string"
}
}
]
},
"onSuccess": {
"type": "string"
},
"jsxFactory": {
"type": "string"
},
"jsxFragment": {
"type": "string"
},
"outDir": {
"type": "string"
},
"format": {
"oneOf": [
{
"enum": ["cjs", "iife", "esm"],
"type": "string"
},
{
"type": "array",
"uniqueItems": true,
"items": {
"type": "string",
"enum": ["cjs", "iife", "esm"]
}
}
]
},
"swc": {
"type": "object"
},
"globalName": {
"type": "string"
},
"env": {
"type": "object"
},
"define": {
"type": "object"
},
"dts": {
"markdownDescription": "This will emit `./dist/index.js` and `./dist/index.d.ts`.\n\nIf you have multiple entry files, each entry will get a corresponding `.d.ts` file. So when you only want to generate declaration file for a single entry, use `--dts <entry>` format, e.g. `--dts src/index.ts`.\n\n**Note** that `--dts` does not resolve external (aka in node_modules) types used in the `.d.ts file`, if that's somehow a requirement, try the experimental `--dts-resolve` flag instead.",
"oneOf": [
{
"type": "boolean"
},
{
"type": "string"
},
{
"type": "object",
"properties": {
"entry": {
"oneOf": [
{
"type": "string"
},
{
"type": "object"
},
{
"type": "array",
"items": {
"type": "string"
}
}
]
}
}
}
]
},
"sourcemap": {
"oneOf": [
{
"type": "boolean"
},
{
"enum": ["inline"]
}
]
},
"noExternal": {
"type": "array",
"items": {
"type": "string"
},
"description": "Always bundle modules matching given patterns"
},
"external": {
"description": "Don't bundle these modules",
"type": "array",
"items": {
"type": "string"
}
},
"replaceNodeEnv": {
"type": "boolean",
"markdownDescription": "Replace `process.env.NODE_ENV` with `production` or `development` `production` when the bundled is minified, `development` otherwise"
},
"splitting": {
"type": "boolean",
"default": true,
"markdownDescription": "You may want to disable code splitting sometimes: [`#255`](https://github.com/egoist/tsup/issues/255)"
},
"clean": {
"description": "Clean output directory before each buil",
"oneOf": [
{
"type": "boolean"
},
{
"type": "array",
"items": {
"type": "string"
}
}
]
},
"silent": {
"type": "boolean",
"description": "Suppress non-error logs (excluding \"onSuccess\" process output)"
},
"skipNodeModulesBundle": {
"type": "boolean",
"description": "Skip node_modules bundling"
},
"pure": {
"markdownDescription": "See:\n- [Pure](https://esbuild.github.io/api/#pure) - esbuild",
"oneOf": [
{
"type": "boolean"
},
{
"type": "array",
"items": {
"type": "string"
}
}
]
},
"bundle": {
"default": true,
"type": "boolean",
"description": "Disable bundling, default to true"
},
"inject": {
"markdownDescription": "This option allows you to automatically replace a global variable with an import from another file.\n\n---\nSee:\n- [Inject](https://esbuild.github.io/api/#inject) - esbuild",
"type": "array",
"items": {
"type": "string"
}
},
"metafile": {
"type": "boolean",
"markdownDescription": "Emit esbuild metafile.\n\n---\nSee:\n- [Metafile](https://esbuild.github.io/api/#metafile) - esbuild"
},
"footer": {
"type": "object",
"properties": {
"js": {
"type": "string"
},
"css": {
"type": "string"
}
}
},
"banner": {
"type": "object",
"properties": {
"js": {
"type": "string"
},
"css": {
"type": "string"
}
}
},
"platform": {
"description": "Target platform",
"type": "string",
"default": "node",
"enum": ["node", "browser", "neutral"]
},
"config": {
"markdownDescription": "Disable config file with `false` or pass a custom config filename",
"type": ["boolean", "string"]
},
"tsconfig": {
"type": "string",
"description": " Use a custom tsconfig"
},
"injectStyle": {
"type": "boolean",
"default": false,
"description": "Inject CSS as style tags to document head"
},
"shims": {
"type": "boolean",
"default": false,
"description": "Inject cjs and esm shims if needed"
}
}
}
}
}
@@ -0,0 +1,268 @@
/**
* @fileoverview Rule to require object keys to be sorted
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils"),
naturalCompare = require("natural-compare");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Gets the property name of the given `Property` node.
*
* - If the property's key is an `Identifier` node, this returns the key's name
* whether it's a computed property or not.
* - If the property has a static name, this returns the static name.
* - Otherwise, this returns null.
* @param {ASTNode} node The `Property` node to get.
* @returns {string|null} The property name or null.
* @private
*/
function getPropertyName(node) {
const staticName = astUtils.getStaticPropertyName(node);
if (staticName !== null) {
return staticName;
}
return node.key.name || null;
}
/**
* Functions which check that the given 2 names are in specific order.
*
* Postfix `I` is meant insensitive.
* Postfix `N` is meant natural.
* @private
*/
const isValidOrders = {
asc(a, b) {
return a <= b;
},
ascI(a, b) {
return a.toLowerCase() <= b.toLowerCase();
},
ascN(a, b) {
return naturalCompare(a, b) <= 0;
},
ascIN(a, b) {
return naturalCompare(a.toLowerCase(), b.toLowerCase()) <= 0;
},
desc(a, b) {
return isValidOrders.asc(b, a);
},
descI(a, b) {
return isValidOrders.ascI(b, a);
},
descN(a, b) {
return isValidOrders.ascN(b, a);
},
descIN(a, b) {
return isValidOrders.ascIN(b, a);
},
};
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
defaultOptions: [
"asc",
{
allowLineSeparatedGroups: false,
caseSensitive: true,
ignoreComputedKeys: false,
minKeys: 2,
natural: false,
},
],
docs: {
description: "Require object keys to be sorted",
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/sort-keys",
},
schema: [
{
enum: ["asc", "desc"],
},
{
type: "object",
properties: {
caseSensitive: {
type: "boolean",
},
natural: {
type: "boolean",
},
minKeys: {
type: "integer",
minimum: 2,
},
allowLineSeparatedGroups: {
type: "boolean",
},
ignoreComputedKeys: {
type: "boolean",
},
},
additionalProperties: false,
},
],
messages: {
sortKeys:
"Expected object keys to be in {{natural}}{{insensitive}}{{order}}ending order. '{{thisName}}' should be before '{{prevName}}'.",
},
},
create(context) {
const [
order,
{
caseSensitive,
natural,
minKeys,
allowLineSeparatedGroups,
ignoreComputedKeys,
},
] = context.options;
const insensitive = !caseSensitive;
const isValidOrder =
isValidOrders[
order + (insensitive ? "I" : "") + (natural ? "N" : "")
];
// The stack to save the previous property's name for each object literals.
let stack = null;
const sourceCode = context.sourceCode;
return {
ObjectExpression(node) {
stack = {
upper: stack,
prevNode: null,
prevBlankLine: false,
prevName: null,
numKeys: node.properties.length,
};
},
"ObjectExpression:exit"() {
stack = stack.upper;
},
SpreadElement(node) {
if (node.parent.type === "ObjectExpression") {
stack.prevName = null;
}
},
Property(node) {
if (node.parent.type === "ObjectPattern") {
return;
}
if (ignoreComputedKeys && node.computed) {
stack.prevName = null; // reset sort
return;
}
const prevName = stack.prevName;
const numKeys = stack.numKeys;
const thisName = getPropertyName(node);
// Get tokens between current node and previous node
const tokens =
stack.prevNode &&
sourceCode.getTokensBetween(stack.prevNode, node, {
includeComments: true,
});
let isBlankLineBetweenNodes = stack.prevBlankLine;
if (tokens) {
// check blank line between tokens
tokens.forEach((token, index) => {
const previousToken = tokens[index - 1];
if (
previousToken &&
token.loc.start.line - previousToken.loc.end.line >
1
) {
isBlankLineBetweenNodes = true;
}
});
// check blank line between the current node and the last token
if (
!isBlankLineBetweenNodes &&
node.loc.start.line - tokens.at(-1).loc.end.line > 1
) {
isBlankLineBetweenNodes = true;
}
// check blank line between the first token and the previous node
if (
!isBlankLineBetweenNodes &&
tokens[0].loc.start.line - stack.prevNode.loc.end.line >
1
) {
isBlankLineBetweenNodes = true;
}
}
stack.prevNode = node;
if (thisName !== null) {
stack.prevName = thisName;
}
if (allowLineSeparatedGroups && isBlankLineBetweenNodes) {
stack.prevBlankLine = thisName === null;
return;
}
if (
prevName === null ||
thisName === null ||
numKeys < minKeys
) {
return;
}
if (!isValidOrder(prevName, thisName)) {
context.report({
node,
loc: node.key.loc,
messageId: "sortKeys",
data: {
thisName,
prevName,
order,
insensitive: insensitive ? "insensitive " : "",
natural: natural ? "natural " : "",
},
});
}
},
};
},
};