@remotex-labs/xjet 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/shared.js CHANGED
@@ -1,74 +1,8 @@
1
- var $i=Object.create;var De=Object.defineProperty;var Ii=Object.getOwnPropertyDescriptor;var ht=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),ne=t=>{throw TypeError(t)};var Ci=(t,e,r)=>e in t?De(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var o=(t,e)=>De(t,"name",{value:e,configurable:!0});var de=t=>[,,,$i(t?.[ht("metadata")]??null)],pt=["class","method","getter","setter","accessor","field","value","get","set"],ie=t=>t!==void 0&&typeof t!="function"?ne("Function expected"):t,Ri=(t,e,r,i,n)=>({kind:pt[t],name:e,metadata:i,addInitializer:s=>r._?ne("Already initialized"):n.push(ie(s||null))}),Li=(t,e)=>Ci(e,ht("metadata"),t[3]),me=(t,e,r,i)=>{for(var n=0,s=t[e>>1],a=s&&s.length;n<a;n++)e&1?s[n].call(r):i=s[n].call(r,i);return i},ye=(t,e,r,i,n,s)=>{var a,c,l,h,y,f=e&7,k=!!(e&8),g=!!(e&16),T=f>3?t.length+1:f?k?1:2:0,te=pt[f+5],re=f>3&&(t[T-1]=[]),Me=t[T]||(t[T]=[]),O=f&&(!g&&!k&&(n=n.prototype),f<5&&(f>3||!g)&&Ii(f<4?n:{get[r](){return lt(this,s)},set[r](C){return ut(this,s,C)}},r));f?g&&f<4&&o(s,(f>2?"set ":f>1?"get ":"")+r):o(n,r);for(var Fe=i.length-1;Fe>=0;Fe--)h=Ri(f,r,l={},t[3],Me),f&&(h.static=k,h.private=g,y=h.access={has:g?C=>Oi(n,C):C=>r in C},f^3&&(y.get=g?C=>(f^1?lt:ji)(C,n,f^4?s:O.get):C=>C[r]),f>2&&(y.set=g?(C,Ne)=>ut(C,n,Ne,f^4?s:O.set):(C,Ne)=>C[r]=Ne)),c=(0,i[Fe])(f?f<4?g?s:O[te]:f>4?void 0:{get:O.get,set:O.set}:n,h),l._=1,f^4||c===void 0?ie(c)&&(f>4?re.unshift(c):f?g?s=c:O[te]=c:n=c):typeof c!="object"||c===null?ne("Object expected"):(ie(a=c.get)&&(O.get=a),ie(a=c.set)&&(O.set=a),ie(a=c.init)&&re.unshift(a));return f||Li(t,n),O&&De(n,r,O),g?f^4?s:O:n};var ze=(t,e,r)=>e.has(t)||ne("Cannot "+r),Oi=(t,e)=>Object(e)!==e?ne('Cannot use the "in" operator on this value'):t.has(e),lt=(t,e,r)=>(ze(t,e,"read from private field"),r?r.call(t):e.get(t));var ut=(t,e,r,i)=>(ze(t,e,"write to private field"),i?i.call(t,r):e.set(t,r),r),ji=(t,e,r)=>(ze(t,e,"access private method"),r);var Bi={dim:[2,22],bold:[1,22],reset:[0,0],hidden:[8,28],inverse:[7,27]},Pi={red:[31,39],gray:[90,39],blue:[34,39],cyan:[36,39],black:[30,39],white:[37,39],green:[32,39],yellow:[33,39],magenta:[35,39],redBright:[91,39],blueBright:[94,39],cyanBright:[96,39],whiteBright:[97,39],greenBright:[92,39],blackBright:[90,39],yellowBright:[93,39],magentaBright:[95,39],darkGray:["38;5;238",39],lightGray:["38;5;252",39],lightCyan:["38;5;81",39],lightCoral:["38;5;203",39],oliveGreen:["38;5;149",39],deepOrange:["38;5;166",39],brightPink:["38;5;197",39],lightOrange:["38;5;215",39],burntOrange:["38;5;208",39],lightYellow:["38;5;230",39],canaryYellow:["38;5;227",39],lightGoldenrodYellow:["38;5;221",39]},Mi={bgRed:[41,49],bgBlue:[44,49],bgCyan:[46,49],bgGray:[100,49],bgBlack:[40,49],bgGreen:[42,49],bgWhite:[47,49],bgYellow:[43,49],bgMagenta:[45,49],bgRedBright:[101,49],bgBlueBright:[104,49],bgCyanBright:[106,49],bgBlackBright:[100,49],bgWhiteBright:[107,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgMagentaBright:[105,49]},ft={...Bi,...Pi,...Mi},ge="\x1B[",ve="m";function dt(t,e){if(globalThis.NO_COLOR)return e;let r=t.length;if(r===0)return e;if(r===1)return`${ge}${t[0][0]}${ve}${e}${ge}${t[0][1]}${ve}`;let i=new Array(r),n=new Array(r);for(let s=0;s<r;s++)n[s]=`${ge}${t[s][0]}${ve}`,i[r-s-1]=`${ge}${t[s][1]}${ve}`;return n.concat(e,i).join("")}o(dt,"I");function be(t,e,r,i){if(typeof e!="number"||typeof r!="number"||typeof i!="number")throw new Error(`RGB values must be numbers, received: r=${typeof e}, g=${typeof r}, b=${typeof i}`);let n=t==="fg"?38:48,s=t==="fg"?39:49;return[`${n};2;${e};${r};${i}`,s]}o(be,"d");function mt(t){let e=t.replace(/^#/,"").toLowerCase();if(!/^([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(e))throw new Error(`Invalid hex color format: "${t}". Expected 3 or 6 hex digits.`);if(e.length===3){let s=parseInt(e[0]+e[0],16),a=parseInt(e[1]+e[1],16),c=parseInt(e[2]+e[2],16);return[s,a,c]}let r=parseInt(e.slice(0,2),16),i=parseInt(e.slice(2,4),16),n=parseInt(e.slice(4,6),16);return[r,i,n]}o(mt,"_");function G(t=[]){let e=o((...i)=>{if(Array.isArray(i[0])&&"raw"in i[0]){let[n,...s]=i,a=n.reduce((c,l,h)=>c+l+(h<s.length?String(s[h]??""):""),"");return dt(t,a)}return dt(t,i.join(" "))},"e"),r={rgb:o((i,n,s)=>G([...t,be("fg",i,n,s)]),"rgb"),bgRgb:o((i,n,s)=>G([...t,be("bg",i,n,s)]),"bgRgb"),hex:o(i=>G([...t,be("fg",...mt(i))]),"hex"),bgHex:o(i=>G([...t,be("bg",...mt(i))]),"bgHex")};return new Proxy(e,{get(i,n){if(typeof n!="string")throw new Error(`Invalid property: ${String(n)}`);return n in ft?G([...t,ft[n]]):n in r?r[n]:Reflect.get(i,n)}})}o(G,"g");var F=G();var Fi=Object.defineProperty,u=o((t,e)=>Fi(t,"name",{value:e,configurable:!0}),"o");function kt(t,e){return e!=null&&(e.constructor===t||typeof e=="function")}o(kt,"nt");u(kt,"isA");function Ee(t,e){return t==null||typeof t!="object"&&typeof t!="function"?!1:e in t||Object.prototype.hasOwnProperty.call(t,e)}o(Ee,"X");u(Ee,"hasKey");function I(t){return!!t&&Ee(t,"expectedLabel")&&kt(Function,t.matches)}o(I,"b");u(I,"isAsymmetric");function Ke(t,e){let r=I(t),i=I(e);if(!(r&&i)){if(r)return t.matches(e);if(i)return e.matches(t)}}o(Ke,"ce");u(Ke,"asymmetricMatch");function wt(t,e,r=!0){if(Array.isArray(t)&&Array.isArray(e))return r&&t.length!==e.length?!1:t.every((s,a)=>x(s,e[a],r));let i=Object.keys(t),n=Object.keys(e);if(r&&i.length!==n.length)return!1;for(let s of i)if(!Ee(e,s)||!x(t[s],e[s],r))return!1;return!0}o(wt,"it");u(wt,"deepEquals");function x(t,e,r=!0){if(t===e||Object.is(t,e))return!0;if(t===null||e===null)return!1;let i=Ke(t,e);return i!==void 0?i:t instanceof Date&&e instanceof Date?t.getTime()===e.getTime():t instanceof RegExp&&e instanceof RegExp?t.source===e.source&&t.flags===e.flags:globalThis.URL&&t instanceof globalThis.URL&&e instanceof globalThis.URL?t.href===e.href:typeof t=="object"&&typeof e=="object"?wt(t,e,r):!1}o(x,"g");u(x,"equals");function St(t){let e={};for(let r of Object.keys(t)){let i=t[r];i&&(e[r]=i)}return e.name=t.name,e.stack=t.stack,e.message=t.message,e}o(St,"de");u(St,"serializesError");function Z(t){return t!=null&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}o(Z,"me");u(Z,"isPromise");var At=" ";function $t(t){return typeof t=="string"?t.includes(`
2
- `)?null:`"${t}"`:typeof t=="number"?`${Number.isFinite(t)?t:t.toString()}`:typeof t=="boolean"?`${t}`:typeof t=="symbol"?`${t.toString()}`:typeof t=="bigint"?`${t}n`:typeof t=="function"?`[Function: ${t.name||"anonymous"}]`:t===null?"null":t===void 0?"undefined":I(t)?t.expectedLabel??t.constructor.name:t instanceof Date?`[Date: ${t.toISOString()}]`:t instanceof RegExp?t.toString():t instanceof Error?`[${t.name}: ${t.message}]`:t instanceof Promise?"[Promise <pending>]":t instanceof ArrayBuffer?`ArrayBuffer { byteLength: ${t.byteLength} }`:t instanceof DataView?`DataView { byteLength: ${t.byteLength}, byteOffset: ${t.byteOffset} }`:null}o($t,"st");u($t,"serializePrimitive");function It(t){return t===null?"null":t===void 0?"undefined":typeof t=="object"?Object.prototype.toString.call(t):JSON.stringify(t)}o(It,"ot");u(It,"serializeMapKey");function se(t,e,r,i,n=""){if(t.length===0)return;if(t.length<2){let a=`${n}${r}${t[t.length-1]}`;e.push(i?a:`${a},`);return}e.push(`${n}${r}${t[0]}`);for(let a=1;a<t.length-1;a++)e.push(n+t[a]);let s=`${n}${t[t.length-1]}`;e.push(i?s:`${s},`)}o(se,"Q");u(se,"appendLines");function Ct(t,e,r,i){if(t.size===0){e.push("Map {}");return}e.push("Map {");let n=Array.from(t.entries());n.forEach(([s,a],c)=>{let l=It(s),h=[];Q(a,h,r,i),se(h,e,`${l} => `,c===n.length-1,r)}),e.push("}")}o(Ct,"ct");u(Ct,"serializeMap");function Rt(t,e,r,i){if(t.length===0){e.push("[]");return}e.push("["),t.forEach((n,s)=>{let a=[];Q(n,a,r,i),se(a,e,"",s===t.length-1,r)}),e.push("]")}o(Rt,"at");u(Rt,"serializeArray");function Lt(t,e,r,i){if(t.size===0){e.push("Set {}");return}e.push("Set {");let n=Array.from(t);n.forEach((s,a)=>{let c=[];Q(s,c,r,i),se(c,e,"",a===n.length-1,r)}),e.push("}")}o(Lt,"ut");u(Lt,"serializeSet");function Ot(t,e,r){let i=Array.from(t);if(i.length===0){e.push("Buffer {}");return}e.push("Buffer {");for(let n=0;n<i.length;n++){let s=i[n],a=n===i.length-1?"":",";e.push(`${r}${s}${a}`)}e.push("}")}o(Ot,"ht");u(Ot,"serializeBuffer");function jt(t,e,r){let i=Object.prototype.toString.call(t).slice(8,-1),n=Array.from(t);if(n.length===0){e.push(`${i} []`);return}e.push(`${i} [`);for(let s=0;s<n.length;s++){let a=n[s],c=s===n.length-1?"":",";e.push(`${r}${a}${c}`)}e.push("]")}o(jt,"pt");u(jt,"serializeTypedArray");function He(t,e,r,i){let n=t.constructor&&t.constructor!==Object?t.constructor.name:"Object",s=Object.entries(t);if(s.length===0){e.push(`${n} {}`);return}e.push(`${n} {`),s.forEach(([a,c],l)=>{let h=[];Q(c,h,r,i),se(h,e,`${String(a)}: `,l===s.length-1,r)}),e.push("}")}o(He,"ye");u(He,"serializeObject");function Q(t,e,r=At,i){let n=$t(t);if(n!==null){e.push(n);return}if(typeof t=="string"){let s=t.split(`
3
- `);e.push('String "');for(let a of s)e.push(`${r}${a}`);e.push('"');return}if(typeof t=="object"&&t!==null){if(i.has(t)){e.push("[Circular]");return}i.add(t),t instanceof Map?Ct(t,e,r,i):Array.isArray(t)?Rt(t,e,r,i):t instanceof Set?Lt(t,e,r,i):t instanceof Buffer?Ot(t,e,r):ArrayBuffer.isView(t)&&!(t instanceof DataView)?jt(t,e,r):He(t,e,r,i);return}He(t,e,r,i)}o(Q,"B");u(Q,"serializeValue");function _(t){if(t&&typeof t=="object"){if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let e={};for(let[r,i]of Object.entries(t))i!==void 0&&(e[r]=i);return e.name=t?.name??e.name,e.message=t?.message??e.message,e.stack=t?.stack??e.stack,e}return t}o(_,"ae");u(_,"serializeError");function w(t,e=At){let r=[];return Q(t,r,e,new WeakSet),r}o(w,"v");u(w,"serialize");var Ni=(t=>(t[t.DELETE=-1]="DELETE",t[t.EQUAL=0]="EQUAL",t[t.INSERT=1]="INSERT",t))(Ni||{});function Bt(){let t=0;for(;this.aStart+t<this.aEnd&&this.bStart+t<this.bEnd&&this.isMatch(this.aStart+t,this.bStart+t);)t++;return t}o(Bt,"lt");u(Bt,"countCommonForward");function Pt(){let t=0;for(;this.aEnd-1-t>=this.aStart&&this.bEnd-1-t>=this.bStart&&this.isMatch(this.aEnd-1-t,this.bEnd-1-t);)t++;return t}o(Pt,"ft");u(Pt,"countCommonBackward");function Mt(t,e,r){let i=this.aEnd-this.aStart,n=this.bEnd-this.bStart,s=[];for(let a=r;a>0;a--){let c=t[a-1],l=i-n,h,y=c[l-1+e],f=c[l+1+e];l===-a||l!==a&&y<f?h=l+1:h=l-1;let k=h+e,g=c[k],T=g-h;for(;i>g&&n>T;)--i,--n,s.push([1,this.aStart+i,this.bStart+n]);i===g?s.push([0,this.aStart+g,this.bStart+T]):s.push([0,this.aStart+g,this.bStart+T]),i=g,n=T}for(let a of s.reverse())this.foundSubsequence(...a)}o(Mt,"dt");u(Mt,"backtrackFlat");function Ft(){let t=this.aEnd-this.aStart,e=this.bEnd-this.bStart,r=t+e,i=0,n=new Array(2*r+1).fill(0),s=[];for(let a=0;a<=r;a++){let c=new Array(2*r+1);s[a]=c;for(let l=-a;l<=a;l+=2){let h=l+r,y;l===-a||l!==a&&n[l-1+r]<n[l+1+r]?y=n[l+1+r]:y=n[l-1+r]+1;let f=y-l;for(;y<t&&f<e&&this.isMatch(this.aStart+y,this.bStart+f);)y++,f++;if(n[h]=y,c[h]=y,y>=t&&f>=e)return i=a,Mt.call(this,s,r,i)}}}o(Ft,"mt");u(Ft,"findMiddleSnake");function Nt(){let t=Bt.call(this),e=this.aStart+t>=this.aEnd&&this.bStart+t>=this.bEnd;if(t>0&&(this.foundSubsequence(t,this.aStart,this.bStart),e))return;this.aStart+=t,this.bStart+=t;let r=Pt.call(this);this.aEnd-=r,this.bEnd-=r,(this.aStart<this.aEnd||this.bStart<this.bEnd)&&Ft.call(this),r>0&&this.foundSubsequence(r,this.aEnd,this.bEnd)}o(Nt,"yt");u(Nt,"diffSequence");function Ue(t,e,r,i){let n={aStart:0,bStart:0,aEnd:t,bEnd:e,isMatch:r,foundSubsequence:i};Nt.call(n)}o(Ue,"ve");u(Ue,"createDiff");function Je(t,e){let r=0,i=0,n="",s="",a=[];function c(l,h){let y=a[a.length-1];y&&y[0]===l?y[1]+=h:a.push([l,h])}return o(c,"a"),u(c,"pushDiff"),Ue(t.length,e.length,(l,h)=>t[l]===e[h],(l,h,y)=>{r!==h&&(s+=t.slice(r,h)),i!==y&&(n+=e.slice(i,y)),l>0&&(s&&(c(-1,s),s=""),n&&(c(1,n),n=""),c(0,e.slice(y,y+l))),r=h+l,i=y+l}),r!==t.length&&(s+=t.slice(r)),i!==e.length&&(n+=e.slice(i)),s&&a.push([-1,s]),n&&a.push([1,n]),a}o(Je,"G");u(Je,"diffStringsRaw");function Ve(t,e){let r=0,i=0,n=[];for(Ue(t.length,e.length,(s,a)=>{let c=t[s].trimEnd().endsWith(","),l=e[a].trimEnd().endsWith(",");return c&&!l?e[a]+=",":!c&&l&&(t[s]+=","),t[s]===e[a]},(s,a,c)=>{for(;r!==a;r+=1)n.push([-1,t[r]]);for(;i!==c;i+=1)n.push([1,e[i]]);for(;s!==0;s-=1,r+=1,i+=1)n.push([0,e[i]])});r!==t.length;r+=1)n.push([-1,t[r]]);for(;i!==e.length;i+=1)n.push([1,e[i]]);return n}o(Ve,"Z");u(Ve,"diffLinesRaw");function We(t){let e=[],r=[],i=[],n=u(()=>{e.length&&(i.push([-1,e.join("")]),e=[]),r.length&&(i.push([1,r.join("")]),r=[])},"flushBuffers");for(let s=0;s<t.length;s++){let[a,c]=t[s];if(a===0){if(c.length<=1){let l=s>0?t[s-1][0]:null,h=s+1<t.length?t[s+1][0]:null,y=u(f=>f===-1||f===1,"isEdit");if(y(l)&&y(h)){for(let f of c)e.push(f),r.push(f);continue}}n(),i.push([0,c])}else if(a===-1)for(let l of c)e.push(l);else if(a===1)for(let l of c)r.push(l);else n(),i.push([a,c])}return n(),i}o(We,"_");u(We,"cleanupSemantic");var P=F.dim,Di=F.lightOrange,p=F.lightCoral,m=F.oliveGreen,Dt=F.cyan,N=F.inverse,Dn=F.whiteBright;function j(t){return t===null?"null":t===!0?"true":t===!1?"false":t&&typeof t=="object"?t.constructor?.name??"Object":typeof t}o(j,"k");u(j,"getType");function zt(t,e,r=!0){let i="",n="",s=Je(t||" ",e||" ");r&&(s=We(s));for(let[a,c]of s)a===0?(i+=c,n+=c):a===-1?i+=N(c):a===1&&(n+=N(c));return[i,n]}o(zt,"gt");u(zt,"normalizeStrings");function Ht(t,e){let r=[...t],i=[...e],n=Math.max(t.length,e.length);for(let s=0;s<n;s++)[r[s],i[s]]=oe(t[s],e[s]);return[r,i]}o(Ht,"vt");u(Ht,"normalizeArrays");function _t(t,e){let r={...t},i={...e},n=new Set([...Object.keys(t),...Object.keys(e)]);for(let s of n)s in t&&s in e&&([r[s],i[s]]=oe(t[s],e[s]));return[r,i]}o(_t,"Et");u(_t,"normalizeObjects");function oe(t,e,r=!0){if(t===e)return[t,e];let i=typeof t,n=typeof e;return Ke(t,e)===!0?(I(t)&&(t=e),I(e)&&(e=t),[t,e]):i==="string"&&n==="string"?zt(t,e,r):!t||!e||i!=="object"||n!=="object"?[t,e]:Array.isArray(t)&&Array.isArray(e)?Ht(t,e):_t(t,e)}o(oe,"ee");u(oe,"normalizeAsymmetric");function Kt(t,e,r,i=!0){let n=t.split(`
4
- `),s=e.split(`
5
- `);r.push(Dt(`
6
- @@ -1,${n.length} +1,${s.length} @@
7
- `));let a=Math.max(n.length,s.length);for(let c=0;c<a;c++){let l=n[c],h=s[c];if(l===h){l&&r.push(P(` ${l}`));continue}let y=[],f=[];if(l!==void 0&&h!==void 0){let k=Je(l||" ",h||" ");i&&(k=We(k));for(let[g,T]of k)g===0?(y.push(T),f.push(T)):g===-1?y.push(N(T)):g===1&&f.push(N(T))}l===void 0&&f.push(h),!h===void 0&&y.push(l),y.length>0&&r.push(m(`- ${y.join("")}`)),f.length>0&&r.push(p(`+ ${f.join("")}`))}return r.join(`
8
- `)}o(Kt,"bt");u(Kt,"diffStrings");function xe(t,e){let r=[];[t,e]=oe(t,e,!0);let i=w(t,""),n=w(e,""),s=Ve(i,n);for(let[a,c]of s){let l=c,h="";l.endsWith(",")&&(l=l.slice(0,-1),h=","),a===0?r.push(P(l)+h):a===1&&r.push(p(l)+h)}return r}o(xe,"te");u(xe,"diffArgs");function ke(t,e,r=!0){let i=j(t),n=j(e),s=[];if(i!==n&&(s.push("Expected type: "+m(i)),s.push("Received type: "+p(n))),i==="string"&&n==="string")return Kt(t,e,s,r);let[a,c]=oe(t,e,r),l=w(a),h=w(c);s.push(Dt(`
9
- @@ -1,${l.length} +1,${h.length} @@
10
- `));let y=Ve(l,h);for(let[f,k]of y)f===0?s.push(P(` ${k}`)):f===-1?s.push(m(`- ${k}`)):f===1&&s.push(p(`+ ${k}`));return s.join(`
11
- `)}o(ke,"D");u(ke,"diffComponent");var qe=class extends Error{static{o(this,"C")}static{u(this,"xJetBaseError")}constructor(t,e="xJetError"){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=e,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toJSON(){return St(this)}};function we(t){let{comment:e,assertionChain:r,expectedLabels:i=[],receivedLabeled:n="received"}=t;if(!r.length)throw new Error('Expected non-empty matcher chain (e.g., ["toEqual"]). Received an empty array.');let s=[P("expect("),p(n),P(")"),".",r.join(".")];return i.length>0?(s.push("("),s.push(i.map(a=>m(a)).join(", ")),s.push(")")):s.push("()"),e&&s.push(P(" // "+e)),s.join("")}o(we,"O");u(we,"composeStatement");var K=class extends qe{static{o(this,"w")}static{u(this,"xJetTypeError")}constructor(t){let e=[`${we(t)}
12
- `,`Matcher error: ${t.message}
13
- `];t.expected&&(t.expected.type&&e.push(`Expected has type: ${t.expected.type}`),e.push(`Expected has value: ${m(w(t.expected.value).join(`
14
- `))}`)),t.received&&(t.received.type&&e.push(`Received has type: ${t.received.type}`),e.push(`Received has value: ${p(w(t.received.value).join(`
15
- `))}`)),super(e.join(`
16
- `),"xJetTypeError")}},zi=class extends qe{static{o(this,"re")}static{u(this,"xJetExpectError")}matcherResult;constructor(t){let e=[`${we(t)}
17
- `];t.info&&e.push(...t.info),super(e.join(`
18
- `),"xJetExpectError"),t.assertion&&(this.matcherResult=t.assertion,this.matcherResult.message=this.message)}};function S(t,e,r,i=[]){let n=j(t);if(!e.includes(n)&&!e.includes(typeof t))throw new K({expectedLabels:i,assertionChain:this.assertionChain,message:`${(r==="Received"?p:m)(r)} value must be a ${e.join(" or ")}`,[r==="Expected"?"expected":"received"]:{value:t,type:n}})}o(S,"E");u(S,"ensureType");function Ye(t,e,r=[]){if(t==null)throw new K({expectedLabels:r,assertionChain:this.assertionChain,message:`${(e==="Received"?p:m)(e)} value must not be null nor undefined`,[e==="Expected"?"expected":"received"]:{value:t}})}o(Ye,"he");u(Ye,"ensureNotNullish");function d(t){return w(t,"").join(" ")}o(d,"l");u(d,"serializeOneLine");function b(t){let{pass:e}=t;if(!(e&&this.notModifier||!e&&!this.notModifier))return;let r=[],i={pass:e,name:this.macherName,received:this.received,expected:t.expected};throw this.notModifier?t.handleNot?.call(this,r):t.handleInfo?.call(this,r),new zi({info:r,assertion:i,...t,assertionChain:this.assertionChain})}o(b,"y");u(b,"handleFailure");function M(t){b.call(this,{...t,handleNot(e){e.push(`Expected: not ${m(d(this.received))}`)},handleInfo(e){t.note&&e.push(P(t.note),""),e.push(ke(t.expected,this.received,!0))}})}o(M,"M");u(M,"handleDiffFailure");function Ut(t,e){let r=" ".repeat(e.length);b.call(this,{...t,handleNot(i){i.push(`Expected: not ${e} ${m(d(t.expected))}`),i.push(`Received: ${r} ${p(d(this.received))}`)},handleInfo(i){i.push(`Expected: ${e} ${m(d(t.expected))}`),i.push(`Received: ${r} ${p(d(this.received))}`)}})}o(Ut,"be");u(Ut,"handleComparisonFailure");function _e(t){let e=t,r=e!=null&&typeof e.message=="string",i=r&&typeof e.name=="string"&&typeof e.stack=="string";return{isError:i,value:t,message:String(r?e.message:t),hasMessage:i?!0:r,serializedError:_(t)}}o(_e,"xe");u(_e,"getThrown");function ae(t,e,r,i=!1){return[u(n=>{n.push(`Expected ${t}: not ${m(e)}`),r?.hasMessage?n.push(`Received message: ${p(d(i?r.message:N(r.message)))}
19
- `):n.push(`Received value: ${p(d(r?.value))}`)},"handleNot"),u(n=>{n.push(`Expected ${t}: ${m(e)}`),r?.hasMessage?(i&&n.push(`Received name: ${p(d(r.value?.name))}`),n.push(`Received message: ${p(d(r.message))}
20
- `)):n.push(`Received value: ${p(d(r?.value))}`)},"handleInfo")]}o(ae,"ne");u(ae,"buildInfo");function Jt(t,e){let r=e!=null&&e.value instanceof t,[i,n]=ae("constructor",t.name,e);return[r,i,n]}o(Jt,"xt");u(Jt,"toThrowExpectedClass");function Vt(t,e){let r=e!=null&&e.message.includes(t),[i,n]=ae("substring",`"${t}"`,e);return[r,i,n]}o(Vt,"St");u(Vt,"toThrowExpectedString");function Wt(t,e){let r=e!=null&&t.test(e.message),[i,n]=ae("pattern",d(t),e);return[r,i,n]}o(Wt,"Tt");u(Wt,"toThrowExpectedRegExp");function qt(t,e){let r=e!=null&&t.matches(e.value),[i,n]=ae("asymmetric",d(t),e,!0);return[r,i,n]}o(qt,"wt");u(qt,"toThrowExpectedAsymmetric");function Yt(t,e){return[e!=null&&x(_(t),e.serializedError),u(r=>{r.push(`Expected: not ${m(d(e.serializedError))}`)},"handleNot"),u(r=>{r.push(ke(t,e.serializedError,!0))},"handleInfo")]}o(Yt,"$t");u(Yt,"toThrowExpectedObject");function Gt(t){let e=null,r=t?["expected"]:[];if(this.rejectsModifier)e=_e(this.received);else if(typeof this.received=="function")try{this.received()}catch(a){e=_e(a)}else S.call(this,this.received,["function"],"Received",r);let i=!1,n,s;t?typeof t=="function"?[i,n,s]=Jt.call(this,t,e):typeof t=="string"?[i,n,s]=Vt.call(this,t,e):t instanceof RegExp?[i,n,s]=Wt.call(this,t,e):I(t)?[i,n,s]=qt.call(this,t,e):e!==null&&typeof t=="object"?[i,n,s]=Yt.call(this,t,e):S.call(this,t,["string","function","RegExp","object"],"Expected",r):(i=e!=null,n=u(a=>{e?.hasMessage?(a.push(`Error name: ${p(e.value?.name)}`),a.push(`Error message: ${p(d(e.message))}
21
- `)):a.push(`Error value: ${p(d(e?.value))}`)},"handleNot")),b.call(Object.assign({},this,{received:e?.serializedError}),{pass:i,expected:t,expectedLabels:r,handleNot(a){n?.call(this,a)},handleInfo(a){e?s?.call(this,a):a.push(`${p("Received")} function did not throw`)}})}o(Gt,"Se");u(Gt,"toThrow");function Xt(t){let e=["length"];if(S.call(this,t,["number","bigint"],"Expected",e),!Object.hasOwn(this.received,"length")||!Number.isSafeInteger(this.received.length))throw new K({expectedLabels:e,message:`${p("received")} value must have a length property whose value must be a number`,received:{value:this.received,type:j(this.received)},assertionChain:this.assertionChain});let r=this.received,i=r.length==t;b.call(this,{pass:i,expectedLabels:e,handleNot(n){n.push(`Expected length: not ${m(d(t))}`),n.push(`Received string: ${p(d(r))}`)},handleInfo(n){n.push(`Expected length: ${m(d(t))}`),n.push(`Received length: ${p(d(r.length))}`),n.push(`Received string: ${p(d(r))}`)}})}o(Xt,"Te");u(Xt,"toHaveLength");function Zt(t){let e=["expected"];S.call(this,this.received,["string"],"Received",e),S.call(this,t,["string","RegExp"],"Expected",e);let r=this.received,i=typeof t=="string"?r.includes(t):new RegExp(t).test(r);b.call(this,{pass:i,expectedLabels:e,handleNot(n){n.push(`Expected: not ${m(d(r))}`)},handleInfo(n){t instanceof RegExp?(n.push(`Expected pattern: ${m(d(t))}`),n.push(`Received string: ${p(d(r))}`)):n.push(ke(t,r,!0))}})}o(Zt,"we");u(Zt,"toMatch");function ce(t,e,r=[]){if(S.call(this,t,["number","bigint"],e,r),t<0)throw new K({expectedLabels:r,assertionChain:this.assertionChain,message:`${(e==="Received"?p:m)(e)} value must be positive number`,[e==="Received"?"received":"expected"]:{value:t,type:j(t)}})}o(ce,"z");u(ce,"ensurePositiveNumber");function le(t,e){let r=this.received,i=["Expected"];S.call(this,t,["number","bigint"],"Expected",i),S.call(this,r,["number","bigint"],"Received",i);let n;switch(e){case">":n=r>t;break;case">=":n=r>=t;break;case"<":n=r<t;break;case"<=":n=r<=t;break;default:n=!1}Ut.call(this,{pass:n,expectedLabels:i,expected:t},e)}o(le,"F");u(le,"handleNumericComparison");function Qt(t,e=2){let r=["expected","precision"];S.call(this,t,["number"],"Expected",r),S.call(this,this.received,["number"],"Received",r);let i=this.received,n=Math.abs(t-i),s=Math.pow(10,-e)/2,a=e<20?s.toFixed(e+1):s.toString(),c=this.notModifier?" ":" ",l=this.notModifier?"not < ":"< ",h=n<s,y=[`Expected precision: ${c}${m(e.toString())}`,`Expected difference: ${l}${m(a)}`,`Received difference: ${c}${p(n.toString())}`];b.call(this,{pass:h,expectedLabels:r,handleNot(f){f.push(`Expected: not ${m(d(t))}`),f.push(`Received: ${p(d(i))}
22
- `),f.push(...y)},handleInfo(f){f.push(`Expected: ${m(d(t))}`),f.push(`Received: ${p(d(i))}
23
- `),f.push(...y)}})}o(Qt,"$e");u(Qt,"toBeCloseTo");function er(t){le.call(this,t,">")}o(er,"ke");u(er,"toBeGreaterThan");function tr(t){le.call(this,t,">=")}o(tr,"Ae");u(tr,"toBeGreaterThanOrEqual");function rr(t){le.call(this,t,"<")}o(rr,"Re");u(rr,"toBeLessThan");function ir(t){le.call(this,t,"<=")}o(ir,"Me");u(ir,"toBeLessThanOrEqual");function B(t=[]){if(!this.received?.xJetMock||!this.received?.mock)throw new K({expectedLabels:t,assertionChain:this.assertionChain,message:`${p("Received")} value must be a mock or spy function`,received:{value:this.received}})}o(B,"I");u(B,"ensureMock");function z(t){return w(t,"").slice(1,-1).map(e=>m(e.replace(",",""))).join(", ")}o(z,"L");u(z,"serializeCallArgs");function Ge(t,e,r,i="->",n=!1,s=3){if(!e?.length)return"";let a=0,c=-1,l=e.length;r&&r>=1&&r<=l&&(c=r-1,a=Math.max(0,Math.min(c-1,l-(s-1))));let h=Math.min(a+s,l),y=String(h).length,f=" ".repeat(i.length+1),k=new Array(h-a);for(let g=a;g<h;g++){let T=e[g],te=String(g+1).padStart(y," "),re=g===c?`${i} `:f;if(n&&Array.isArray(T)&&T.length<1){k[g-a]=`${re}${te}: called with 0 arguments`;continue}let Me=n?xe(t,T).slice(1,-1):xe(t,T);k[g-a]=`${re}${te}: ${Me.join(" ")}`}return k.join(`
24
- `)}o(Ge,"Ie");u(Ge,"serializeList");function nr(t,e,r=[],i=3){if(!e?.length||!r.length)return"";let n=e.length,s=String(n).length+3,a=[];for(let c=0;c<r.length;c++){let l=r[c]-1;if(l<0||l>=n)continue;let h=xe(t,e[l]).slice(1,-1);if(a.push(`${String(l+1).padStart(s," ")}: ${h.join(" ")}`),a.length>=i)break}return a.join(`
25
- `)}o(nr,"Ce");u(nr,"serializeHighlightedCalls");function H(t,e,r,i){return Ge(t,e,r,i,!0)}o(H,"N");u(H,"serializeCallList");function X(t,e,r,i){return Ge(t,e,r,i,!1)}o(X,"P");u(X,"serializeReturnList");function sr(){B.call(this);let t=this.received.mock.calls,e=this.received.mock.calls.length;b.call(this,{pass:e>0,receivedLabeled:this.received.name,handleNot(r){r.push(`Expected calls: ${m("0")}`),r.push(`Received calls: ${p(e.toString())}
26
- `),r.push(H([],t))},handleInfo(r){r.push(`Expected calls: >= ${m("1")}`),r.push(`Received calls: ${p(e.toString())}
27
- `)}})}o(sr,"je");u(sr,"toHaveBeenCalled");function or(t){let e=["expected"];B.call(this,e),ce.call(this,t,"expected",e);let r=this.received.mock.calls.length;b.call(this,{expected:t,pass:r==t,expectedLabels:e,receivedLabeled:this.received.name,handleNot(i){i.push(`Expected calls: != ${m(t.toString())}`)},handleInfo(i){i.push(`Expected calls: ${m(t.toString())}`),i.push(`Received calls: ${p(r.toString())}
28
- `)}})}o(or,"Le");u(or,"toHaveBeenCalledTimes");function ar(...t){let e=["...args"];B.call(this,e);let r=this.received.mock.calls,i=this.received.mock.calls.length,n=[];r.forEach((a,c)=>{a.length===t.length&&x(t,a)&&n.push(c+1)});let s=n.length>0;b.call(this,{pass:s,expectedLabels:e,expected:t,receivedLabeled:this.received.name,handleNot(a){a.push(`Expected: not ${z(t)}`),a.push(`Received:
29
-
30
- ${nr(t,r,n)}
31
- `),a.push(`Calls: ${p(i.toString())}`)},handleInfo(a){a.push(`Expected: ${z(t)}`),a.push(`Received:
32
-
33
- ${H(t,r)}
34
- `),a.push(`Calls: ${p(i.toString())}`)}})}o(ar,"Ne");u(ar,"toHaveBeenCalledWith");function cr(...t){let e=["...args"];B.call(this,e);let r=this.received.mock.calls,i=r.length,n=this.received.mock.calls.at(-1),s=n!==void 0&&x(t,n);b.call(this,{pass:s,expectedLabels:e,expected:t,receivedLabeled:this.received.name,handleNot(a){a.push(`Expected: not ${z(t)}`),a.push(`Received:
35
-
36
- ${H(t,r,r.length)}
37
- `),a.push(`Calls: ${p(i.toString())}`)},handleInfo(a){a.push(`Expected: ${z(t)}`),a.push(`Received:
38
-
39
- ${H(t,r,r.length)}
40
- `),a.push(`Calls: ${p(i.toString())}`)}})}o(cr,"De");u(cr,"toHaveBeenLastCalledWith");function lr(t,...e){let r=["nthCall","...args"];B.call(this,r),ce.call(this,t,"nthCall",r);let i=this.received.mock.calls,n=i.length,s=this.received.mock.calls.at(t-1),a=s!==void 0&&x(e,s);b.call(this,{pass:a,expectedLabels:r,expected:e,receivedLabeled:this.received.name,handleNot(c){c.push(`nthCall: ${t}`),c.push(`Expected: not ${z(e)}`),c.push(`Received:
41
-
42
- ${H(e,i,t)}
43
- `),c.push(`Calls: ${p(n.toString())}`)},handleInfo(c){c.push(`nthCall: ${t}`),c.push(`Expected: ${z(e)}`),c.push(`Received:
44
-
45
- ${H(e,i,t)}
46
- `),c.push(`Calls: ${p(n.toString())}`)}})}o(lr,"Oe");u(lr,"toHaveBeenNthCalledWith");function ur(){B.call(this);let t=[],e=this.received.mock.calls.length,r=this.received.mock.results.reduce((i,n)=>n.type==="return"?(t.push(n.value),i+1):i,0);b.call(this,{pass:r>0,receivedLabeled:this.received.name,handleNot(i){i.push(`Expected returns: ${m("0")}`),i.push(`Received returns: ${p(r.toString())}
47
- `),i.push(X(void 0,t)),i.push(`
48
- Calls: ${p(e.toString())}`)},handleInfo(i){i.push(`Expected returns: >= ${m("1")}`),i.push(`Received returns: ${p(r.toString())}`),i.push(`Calls: ${p(e.toString())}`)}})}o(ur,"Pe");u(ur,"toHaveReturned");function hr(t){let e=["expected"];B.call(this,e),ce.call(this,t,"expected",e);let r=this.received.mock.calls.length,i=this.received.mock.results.reduce((n,s)=>s.type==="return"?n+1:n,0);b.call(this,{expectedLabels:e,pass:i==t,expected:t,receivedLabeled:this.received.name,handleNot(n){n.push(`Expected returns: != ${m(t.toString())}`),n.push(`Calls: ${p(r.toString())}`)},handleInfo(n){n.push(`Expected returns: ${m(t.toString())}`),n.push(`Received returns: ${p(i.toString())}`),n.push(`Calls: ${p(r.toString())}`)}})}o(hr,"Be");u(hr,"toHaveReturnedTimes");function pr(t){let e=["expected"];B.call(this,e);let r=[],i=this.received.mock.calls.length,n=this.received.mock.results.reduce((c,l)=>l.type==="return"?(r.push(l.value),c+1):c,0),s=r.at(-1),a=r.length>0&&x(t,s);b.call(this,{pass:a,expectedLabels:e,expected:t,receivedLabeled:this.received.name,handleNot(c){c.push(`Expected returns: not ${m(d(t))}`),c.push(`Received returns:
49
- `),c.push(X(t,r,n)),c.push(`
50
- Calls: ${p(i.toString())}`)},handleInfo(c){c.push(`Expected returns: ${m(d(t))}`),r.length>0&&(c.push(`Received returns:
51
- `),c.push(X(t,r,n))),c.push(`
52
- Returns: ${p(n.toString())}`),c.push(`Calls: ${p(i.toString())}`)}})}o(pr,"ze");u(pr,"toHaveLastReturnedWith");function fr(t,e){let r=["nthCall","expected"];B.call(this,r),ce.call(this,t,"nthCall",r);let i=[],n=this.received.mock.calls.length,s=this.received.mock.results.reduce((l,h)=>h.type==="return"?(i.push(h.value),l+1):l,0),a=i.at(t-1),c=t<=i.length&&x(e,a);b.call(this,{pass:c,expectedLabels:r,expected:e,receivedLabeled:this.received.name,handleNot(l){l.push(`nthCall: ${t}`),l.push(`Expected returns: not ${m(d(e))}`),l.push(`Received returns:
53
- `),l.push(X(e,i,t)),l.push(`
54
- Returns: ${p(s.toString())}`),l.push(`Calls: ${p(n.toString())}`)},handleInfo(l){l.push(`nthCall: ${t}`),l.push(`Expected returns: ${m(d(e))}`),l.push(`Received returns:
55
- `),l.push(X(e,i,t)),l.push(`
56
- Returns: ${p(s.toString())}`),l.push(`Calls: ${p(n.toString())}`)}})}o(fr,"Fe");u(fr,"toHaveNthReturnedWith");function dr(t){let e=I(t)?t.matches(this.received):Object.is(this.received,t),r=!e&&x(this.received,t)?'If it should pass with deep equality, replace "toBe" with "toEqual"':void 0;M.call(this,{note:r,pass:e,expected:t,comment:"Object.is equality",expectedLabels:["expected"]})}o(dr,"He");u(dr,"toBe");function mr(t){let e=x(this.received,t);M.call(this,{pass:e,expected:t,comment:"deep equality",expectedLabels:["expected"]})}o(mr,"qe");u(mr,"toEqual");function yr(){let t=this.received===null;M.call(this,{pass:t,expected:null})}o(yr,"Ve");u(yr,"toBeNull");function gr(){let t=this.received===void 0;M.call(this,{pass:t,expected:void 0})}o(gr,"We");u(gr,"toBeUndefined");function vr(){let t=Number.isNaN(this.received);M.call(this,{pass:t,expected:NaN})}o(vr,"Je");u(vr,"toBeNaN");function br(){let t=!!this.received;M.call(this,{pass:t,expected:!0})}o(br,"Ke");u(br,"toBeTruthy");function Tr(){let t=!this.received;M.call(this,{pass:t,expected:!1})}o(Tr,"Ue");u(Tr,"toBeFalsy");function xr(){let t=this.received!==void 0;b.call(this,{pass:t,expected:void 0,handleNot(e){e.push(`Expected: ${m(d(void 0))}`)},handleInfo(e){e.push(`Received: ${p(d(this.received))}`)}})}o(xr,"Xe");u(xr,"toBeDefined");function Er(t,e){let r=["path","value"];Ye.call(this,this.received,"Received",r),S.call(this,t,["string","Array"],"Expected path",r);let i=!0,n=this.received,s=[],a=typeof t=="string"?t.split(".").filter(Boolean):t;for(let c of a){if(!n||!Object.hasOwn(n,c)){i=!1;break}s.push(c),n=n[c]}i&&e!==void 0&&(i=x(n,e)),b.call(this,{pass:i,expectedLabels:r,handleNot(c){c.push(`Expected: not ${m(d(a))}
57
- `),e?c.push(`Expected value: ${m(d(e))}`):c.push(`Received value: ${p(d(n))}`)},handleInfo(c){c.push(`Expected path: ${m(d(a))}`),Object.is(s.join(""),a.join(""))||c.push(`Received path: ${p(d(s))}`),c.push(""),e&&c.push(`Expected value: ${m(d(e))}`),c.push(`Received value: ${p(d(n))}`)}})}o(Er,"Qe");u(Er,"toHaveProperty");function kr(t){let e=["expected"];S.call(this,t,["function"],"Received",e);let r=this.received,i=r instanceof t;b.call(this,{pass:i,expectedLabels:e,handleNot(n){n.push(`Expected constructor: not ${m(t.name)}
58
- `)},handleInfo(n){n.push(`Expected constructor: ${m(t.name)}`),r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)!==null&&"constructor"in r?n.push(`Received constructor: ${p(r.constructor.name)}`):(n.push(`
59
- Received value has no prototype`),n.push(`Received value: ${p(d(r))}`))}})}o(kr,"Ye");u(kr,"toBeInstanceOf");function wr(t){let e=["expected"];S.call(this,this.received,["string","Array"],"Received",e);let r=this.received,i=j(r);if(typeof r=="string"&&typeof t!="string")throw new K({expectedLabels:e,message:`${m("expected")} value must be a string if ${p("received")} value is a string`,expected:{value:t,type:j(t)},received:{value:r,type:i},assertionChain:this.assertionChain});let n=r.indexOf(t)!==-1;b.call(this,{pass:n,expectedLabels:e,comment:"indexOf",handleNot(s){i==="string"?(s.push(`Expected substring: not ${m(d(t))}`),s.push(`Received string: ${p(d(r)).replace(String(t),N(String(t)))}`)):(s.push(`Expected value: not ${m(d(t))}`),s.push(`Received array: ${p(d(r)).replace(d(t),N(d(t)))}`))},handleInfo(s){i==="string"?(s.push(`Expected substring: ${m(w(t,"").join(`
60
- `))}`),s.push(`Received string: ${p(w(i,"").join(`
61
- `))}`)):([...r].findIndex(a=>x(a,t))!==-1&&s.push(P(`Looks like you wanted to test for object/array equality with the stricter \`toContain\` matcher.
62
- You probably need to use \`${Di("toContainEqual")}\` instead.
63
- `)),s.push(`Expected value: ${m(d(t))}`),s.push(`Received array: ${p(d(i))}`))}})}o(wr,"Ge");u(wr,"toContain");function Sr(t){let e=["expected"];S.call(this,this.received,["string","Array"],"Received",e);let r=this.received,i=j(r),n=[...r].findIndex(s=>x(s,t))!==-1;b.call(this,{pass:n,expectedLabels:e,comment:"deep equality",handleNot(s){s.push(`Expected value: not ${m(d(t))}`),s.push(`Received array: ${p(d(r)).replace(d(t),N(d(t)))}`)},handleInfo(s){i==="string"&&typeof t=="string"&&r.indexOf(t)!==-1&&s.push(P("Looks like you wanted to test for string equality with the stricter `toContainEqual` matcher. You probably need to use `toContain` instead.\n")),s.push(`Expected: ${m(d(t))}`),s.push(`Received: ${p(d(r))}`)}})}o(Sr,"Ze");u(Sr,"toContainEqual");function Ar(t){let e=["expected"];Ye.call(this,this.received,"Received",e),S.call(this,this.received,["object"],"Received",e),S.call(this,t,["object"],"Expected",e);let r=this.received,i=x(t,r,!1);M.call(this,{pass:i,expected:t,expectedLabels:e})}o(Ar,"_e");u(Ar,"toMatchObject");var yt={toThrow:Gt,toMatch:Zt,toHaveLength:Xt,toContain:wr,toMatchObject:Ar,toHaveProperty:Er,toBeInstanceOf:kr,toContainEqual:Sr,toBe:dr,toEqual:mr,toBeNaN:vr,toBeNull:yr,toBeFalsy:Tr,toBeTruthy:br,toBeDefined:xr,toBeUndefined:gr,toBeCloseTo:Qt,toBeLessThan:rr,toBeGreaterThan:er,toBeLessThanOrEqual:ir,toBeGreaterThanOrEqual:tr,toHaveReturned:ur,toHaveBeenCalled:sr,toHaveReturnedTimes:hr,toHaveBeenCalledWith:ar,toHaveBeenCalledTimes:or,toHaveNthReturnedWith:fr,toHaveLastReturnedWith:pr,toHaveBeenNthCalledWith:lr,toHaveBeenLastCalledWith:cr},D=class{static{o(this,"T")}constructor(t,e=!1){this.name=t,this.isInverse=e}static{u(this,"AbstractPattern")}applyInverse(t){return this.isInverse?!t:t}},Hi=class Te extends D{static{o(this,"e")}constructor(e){super(`Any<${e.name}>`),this.expected=e}static{u(this,"AnyPattern")}static TYPE_CHECKS={String:u(e=>typeof e=="string"||e instanceof String,"String"),Number:u(e=>typeof e=="number"||e instanceof Number,"Number"),Function:u(e=>typeof e=="function"||e instanceof Function,"Function"),Boolean:u(e=>typeof e=="boolean"||e instanceof Boolean,"Boolean"),BigInt:u(e=>typeof e=="bigint"||e instanceof BigInt,"BigInt"),Symbol:u(e=>typeof e=="symbol"||e instanceof Symbol,"Symbol"),Object:u(e=>typeof e=="object","Object"),Array:Array.isArray};static create(e){if(e===void 0)throw new TypeError("any() expects to be passed a constructor function. Please pass one or use anything() to match any object.");return new Te(e)}get expectedLabel(){return`Any<${this.expected.name}>`}matches(e){return this.expected.name in Te.TYPE_CHECKS?Te.TYPE_CHECKS[this.expected.name](e):e instanceof this.expected}},gt=class $r extends D{static{o(this,"e")}constructor(e,r){super("ArrayOf",e),this.expected=r}static{u(this,"ArrayOfPattern")}static create(e,r){if(r===void 0)throw new TypeError("arrayOf() expects a matcher or value.");return new $r(e,r)}get expectedLabel(){return`${this.isInverse?"Not ":""}ArrayOf( ${this.describe(this.expected)} )`}matches(e){if(!Array.isArray(e))return this.applyInverse(!1);let r=e.every(i=>this.matchElement(i,this.expected));return this.applyInverse(r)}matchElement(e,r){return I(r)?r.matches(e):x(e,r)}describe(e){return I(e)?e.expectedLabel:typeof e=="string"?`"${e}"`:w(e,"").join(" ")}},vt=class Ir extends D{static{o(this,"e")}constructor(e,r,i=2){super("CloseTo",e),this.expected=r,this.precision=i}static{u(this,"CloseToPattern")}static create(e,r,i){return new Ir(e,r,i)}get expectedLabel(){let e=this.isInverse?"Not ":"",r=this.precision!==1?"s":"";return`${e}CloseTo(${this.expected}, ${this.precision} digit${r})`}matches(e){let r=this.expected;return typeof e!="number"||typeof r!="number"?this.applyInverse(!1):this.applyInverse(Math.abs(e-r)<Math.pow(10,-this.precision)/2)}},_i=class Cr extends D{static{o(this,"e")}static{u(this,"AnythingPattern")}constructor(){super("Anything")}static create(){return new Cr}get expectedLabel(){return"Anything"}matches(e){return e!=null}},bt=class Rr extends D{static{o(this,"e")}constructor(e,r){super("StringMatching",e),this.expected=r}static{u(this,"StringMatchingPattern")}static create(e,r){let i=typeof r;if(r==null)throw new TypeError("stringMatching() expects a string or RegExp.");if(i!=="string"&&!(r instanceof RegExp))throw new TypeError("stringMatching() expects a string or RegExp.");return new Rr(e,r)}get expectedLabel(){let e=this.isInverse?"Not ":"";return typeof this.expected=="string"?`${e}stringMatching("${this.expected}")`:`${e}stringMatching(${this.expected.toString()})`}matches(e){if(typeof e!="string")return this.applyInverse(!1);let r;return typeof this.expected=="string"?r=e.includes(this.expected):r=this.expected.test(e),this.applyInverse(r)}},Tt=class Lr extends D{static{o(this,"e")}constructor(e,r){super("ArrayContaining",e),this.expected=r}static{u(this,"ArrayContainingPattern")}static create(e,r){if(!Array.isArray(r))throw new TypeError("arrayContaining() expects an array.");return new Lr(e,r)}get expectedLabel(){return`${this.isInverse?"Not ":""}ArrayContaining(${this.describe(this.expected)})`}matches(e){if(!Array.isArray(e))return this.applyInverse(!1);let r=this.expected.every(i=>e.some(n=>this.matchElement(n,i)));return this.applyInverse(r)}matchElement(e,r){return I(r)?r.matches(e):x(e,r)}describe(e){return I(e)?e.expectedLabel:w(e,"").join(" ")}},xt=class Or extends D{static{o(this,"e")}constructor(e,r){super("ObjectContaining",e),this.expected=r}static{u(this,"ObjectContainingPattern")}static create(e,r){if(typeof r!="object"||r===null||Array.isArray(r))throw new TypeError("objectContaining() expects a plain object.");return new Or(e,r)}get expectedLabel(){return`${this.isInverse?"Not ":""}ObjectContaining(${this.describe(this.expected)})`}matches(e){if(typeof e!="object"||e===null)return this.applyInverse(!1);let r=Object.keys(this.expected).every(i=>Ee(e,i)?this.matchElement(e[i],this.expected[i]):!1);return this.applyInverse(r)}matchElement(e,r){return I(r)?r.matches(e):x(e,r)}describe(e){return I(e)?e.expectedLabel:w(e,"").join(" ")}},Et=class jr extends D{static{o(this,"e")}constructor(e,r){super("StringContaining",e),this.expected=r}static{u(this,"StringContainingPattern")}static create(e,r){if(typeof r!="string")throw new TypeError("stringContaining() expects a string.");return new jr(e,r)}get expectedLabel(){return`${this.isInverse?"Not ":""}stringContaining("${this.expected}")`}matches(e){return typeof e!="string"?this.applyInverse(!1):this.applyInverse(e.includes(this.expected))}},Ki={any:Hi.create,anything:_i.create,closeTo:vt.create.bind(null,!1),arrayOf:gt.create.bind(null,!1),stringMatching:bt.create.bind(null,!1),arrayContaining:Tt.create.bind(null,!1),objectContaining:xt.create.bind(null,!1),stringContaining:Et.create.bind(null,!1),not:{closeTo:vt.create.bind(null,!0),arrayOf:gt.create.bind(null,!0),stringMatching:bt.create.bind(null,!0),arrayContaining:Tt.create.bind(null,!0),objectContaining:xt.create.bind(null,!1),stringContaining:Et.create.bind(null,!0)}},Ui=class extends qe{static{o(this,"oe")}static{u(this,"xJetPromiseError")}constructor(t){let e=[`${we(t)}
64
- `,`Matcher error: ${t.message}`,`${t.promiseKind} to value: ${p(w(t.received,"").join(" "))}`];super(e.join(`
65
- `),"xJetPromiseError")}},Br=class{static{o(this,"U")}constructor(t){this.received=t}static{u(this,"MatcherService")}macherName="";promise;notModifier=!1;assertionChain=[];rejectsModifier=!1;resolvesModifier=!1;get not(){return this.notModifier=!0,this}get rejects(){if(this.resolvesModifier)throw new Error('Cannot use "rejects" modifier after "resolved" modifier.');return this.rejectsModifier=!0,this}get resolves(){if(this.rejectsModifier)throw new Error('Cannot use "resolved" modifier after "rejects" modifier.');return this.resolvesModifier=!0,this}invoke(t,e,r){return this.macherName=t,this.rejectsModifier||this.resolvesModifier?(this.pushToChain(t),this.promise=this.resolvesModifier?"resolves":"rejects",this.invokeAsync(e,r)):(this.pushToChain(t),e.call(this,...r))}async invokeAsync(t,e){let r=!1,i=typeof this.received=="function"?this.received():this.received;if(!Z(i))throw new K({message:`${p("received")} value must be a promise or a function returning a promise`,assertionChain:this.assertionChain,received:{type:j(i),value:i}});try{this.received=await i,r=!0}catch(n){this.resolvesModifier&&this.throwPromiseError("Rejected",n),this.received=n}return r&&this.rejectsModifier&&this.throwPromiseError("Resolved",this.received),t.call(this,...e)}pushToChain(t){this.promise&&this.assertionChain.push(this.promise),this.notModifier&&this.assertionChain.push("not"),this.assertionChain.push(t)}throwPromiseError(t,e){let r=t==="Resolved"?"resolved":"rejected",i=t==="Resolved"?"rejected":"resolved";throw new Ui({message:`${p("received")} promise ${r} instead of ${i}`,received:e,promiseKind:t,assertionChain:this.assertionChain})}};for(let t of Object.keys(yt)){let e=Br.prototype,r=yt[t];Object.defineProperty(e,t,{value:u(function(...i){return this.invoke(t,r,i)},"value")}),Object.defineProperty(e[t],"name",{value:t})}var Ji=u((t,...e)=>{if(e.length>0)throw new Error(`Expect takes at most one argument. Received ${e.length+1} arguments instead.`);return new Br(t)},"coreExpect"),Pr=Object.assign(Ji,Ki);var Vi="xJet.mock()",A=class t extends Function{static{o(this,"MockState")}static mocks=[];name;xJetMock=!0;state;restore;queuedImplementations=[];implementation;originalImplementation;constructor(e,r,i){return super(),this.name=i??Vi,this.state=this.initState(),this.implementation=e,this.restore=r,this.originalImplementation=e||(()=>{}),new Proxy(this,{apply:this.invokeFunction,construct:this.invokeClass})}getMockName(){return this.name}get mock(){return Object.freeze({...this.state})}get original(){return this.originalImplementation}mockClear(){return this.state=this.initState(),this}mockReset(){return this.mockClear(),this.queuedImplementations=[],this}mockRestore(){this.mockReset();let e=this.restore?.();typeof e=="function"?this.implementation=e:this.implementation=this.originalImplementation;let r=t.mocks.indexOf(this);return r!==-1&&t.mocks.splice(r,1),this}getMockImplementation(){return this.implementation}getNextImplementation(){return this.queuedImplementations.length?this.queuedImplementations.shift():this.implementation}mockImplementation(e){return this.implementation=e,this}mockImplementationOnce(e){return this.queuedImplementations.push(e),this}mockReturnValue(e){return this.mockImplementation(()=>e),this}mockResolvedValue(e){return this.mockImplementation(()=>Promise.resolve(e)),this}mockResolvedValueOnce(e){return this.mockImplementationOnce(()=>Promise.resolve(e)),this}mockReturnValueOnce(e){return this.mockImplementationOnce(()=>e),this}mockRejectedValue(e){return this.mockImplementation(()=>Promise.reject(e)),this}mockRejectedValueOnce(e){return this.mockImplementationOnce(()=>Promise.reject(e)),this}[Symbol.for("nodejs.util.inspect.custom")](){return`<Mock Constructor ${this.name}>`}initState(){return{calls:[],results:[],lastCall:void 0,contexts:[],instances:[],invocationCallOrder:[]}}invoke(e,r){let i=e,n=this.getNextImplementation(),s=r;typeof n=="function"&&(n.__boundArgs&&s.unshift(...n.__boundArgs),n.__boundThis&&(i=n.__boundThis)),this.state.calls.push(s),this.state.contexts.push(i),this.state.invocationCallOrder.push(this.state.invocationCallOrder.length+1);let a,c=this.state.results.push({value:void 0,type:"incomplete"})-1;if(n)try{a={type:"return",value:n.call(void 0,...r)}}catch(l){a={value:l,type:"throw"}}else a={type:"return",value:void 0};return this.state.lastCall=r,this.state.results[c]=a,a.value}invokeFunction(e,r,i){return e.state.instances.push(r),e.invoke.call(e,r,i)}invokeClass(e,r,i){let n=e.invoke.call(e,i,r),s=typeof n=="object"&&n!==null&&n.constructor;return e.state.instances.push(s?n:i),typeof n=="object"?n:i}};var Xe=new Map,Mr=new Map;function Se(t){return function(e){Mr.set(e,t||{})}}o(Se,"Injectable");function v(t,...e){if(Xe.has(t))return Xe.get(t);let r=Mr.get(t);if(!r)throw new Error(`Cannot inject ${t.name} \u2013 not marked @Injectable`);let i=r.factory?r.factory(...e):new t(...e);return r?.scope==="singleton"&&Xe.set(t,i),i}o(v,"inject");function Dr(t,e,r){let i=`${e}${r}`,n=t[i];if(!r)throw new Error(`Invalid type(${r}) parameter`);if(!(i in t))throw new Error(`Method "${i.toString()}" does not exist on Buffer`);return n.bind(t)}o(Dr,"b");function zr(t,e){return Dr(t,"read",e)}o(zr,"h");function Hr(t,e){return Dr(t,"write",e)}o(Hr,"d");function Ze(t,e,r=0){if(e<0)throw new Error("Split position cannot be negative");if(e>t.length)throw new Error("Split position cannot exceed buffer length");let i=t.subarray(0,e),n=e+r;return n>=t.length?[i,Buffer.alloc(0)]:[i,t.subarray(n)]}o(Ze,"f");function _r(t=0){let{position:e,type:r}=this.descriptor,i=this.offset+e+t;return r.toObject(this.buffer.subarray(i),n=>{this.offset+=n})}o(_r,"l");function Wi(){let t=[],{arraySize:e=0,size:r}=this.descriptor;t.length=e;for(let i=0;i<e;i++)t[i]=_r.call(this,i*r);return t}o(Wi,"U");function qi(){return"arraySize"in this.descriptor&&this.descriptor.arraySize?Wi.call(this):_r.call(this)}o(qi,"S");function Kr(t,e=0){t??={};let{position:r,type:i,size:n}=this.descriptor,s=i.toBuffer(t),a=this.offset+r+e,[c,l]=Ze(this.buffer,a,n);this.buffer=Buffer.concat([c,s,l]),s.length>n&&(this.offset+=s.length-n)}o(Kr,"T");function Yi(t){let{arraySize:e=0,size:r}=this.descriptor;for(let i=0;i<e;i++){let n=i<t.length?t[i]:{};Kr.call(this,n,i*r)}}o(Yi,"W");function Gi(t){return"arraySize"in this.descriptor&&this.descriptor.arraySize?Yi.call(this,Array.isArray(t)?t:[t]):Kr.call(this,Array.isArray(t)?t[0]||{}:t)}o(Gi,"I");var U={Int8:8,UInt8:8,Int16LE:16,Int16BE:16,UInt16LE:16,UInt16BE:16,FloatLE:32,FloatBE:32,Int32LE:32,Int32BE:32,UInt32LE:32,UInt32BE:32,DoubleLE:64,DoubleBE:64,BigInt64LE:64,BigInt64BE:64,BigUInt64LE:64,BigUInt64BE:64};function Xi(t,e=0){let r=/^([A-Za-z][A-Za-z0-9]*)(?:\[(\d+)\])?$/i,i=t.match(r);if(!i)throw new Error(`Invalid primitive descriptor: ${t}`);let n=U[i[1]];if(!n)throw new Error(`Invalid primitive type: ${i[1]}`);let s=i[1],a=i[2]?parseInt(i[2]):void 0;return{type:s,position:e,size:n/8,arraySize:a,kind:"primitive"}}o(Xi,"x");function Ur(t=0){let{position:e,type:r}=this.descriptor,i=this.offset+e+t;return zr(this.buffer,r)(i)}o(Ur,"z");function Zi(){let t=[],{arraySize:e=0,size:r}=this.descriptor;t.length=e;for(let i=0;i<e;i++)t[i]=Ur.call(this,i*r);return t}o(Zi,"N");function Qi(){return"arraySize"in this.descriptor&&this.descriptor.arraySize?Zi.call(this):Ur.call(this)}o(Qi,"w");function Jr(t,e=0){t??=0;let{position:r,type:i}=this.descriptor,n=i.includes("Big");if(n&&t===0&&(t=BigInt(0)),n&&typeof t!="bigint")throw new TypeError(`Expected a BigInt for field "${i}", but received ${t}`);if(!n&&typeof t!="number")throw new TypeError(`Expected a number for field "${i}", but received ${t}`);let s=this.offset+r+e;Hr(this.buffer,i)(t,s)}o(Jr,"B");function en(t){let{arraySize:e=0,size:r}=this.descriptor;for(let i=0;i<e;i++){let n=i<t.length?t[i]:0;Jr.call(this,n,i*r)}}o(en,"_");function tn(t){if("arraySize"in this.descriptor&&this.descriptor.arraySize)return en.call(this,Array.isArray(t)?t:[t]);Jr.call(this,Array.isArray(t)?t[0]||0:t)}o(tn,"P");var Fr=new Map;function et(t){return t.startsWith("Int")}o(et,"y");function Vr(t){let e=Fr.get(t);return e===void 0&&(e=(1<<t)-1,Fr.set(t,e)),e}o(Vr,"D");function rn(t,e){return et(t.type)?Number(BigInt.asIntN(t.bitSize,BigInt(e))):e}o(rn,"j");function nn(t,e){let r=et(t.type),{bitSize:i,type:n}=t,s=r?(1<<i-1)-1:(1<<i)-1,a=r?-(1<<i-1):0;if(e<a||e>s)throw new RangeError(`Value ${e} does not fit within ${i} bits for type ${n}`)}o(nn,"G");function Wr(t,e){if(t.bitSize<1||t.bitPosition<0)throw new Error(`bitSize(${t.bitSize}) and bitPosition(${t.bitPosition}) must be greater than bitSize(1) and bitPosition(0) for ${e}`);if(U[t.type]>32)throw new Error(`${t.type} is not supported yet`);if(t.bitPosition+t.bitSize>U[t.type])throw new Error(`bitPosition(${t.bitPosition}) + bitSize(${t.bitSize}) exceeds ${t.type} size for ${e}`)}o(Wr,"v");function sn(t,e){Wr(e,"read operation");let{type:r,bitPosition:i,bitSize:n}=e,s=Vr(n),a=t>>i&s;return et(r)&&a&1<<n-1?a|~s:a}o(sn,"Z");function on(t,e,r){Wr(e,"write operation"),nn(e,r);let{bitPosition:i,bitSize:n}=e,s=rn(e,r),a=Vr(n)<<i;return t&~a|s<<i&a}o(on,"q");function an(t,e=0,r=0){let[i,n]=t.split(":",2),s=parseInt(n,10),a=U[i],c=i.endsWith("BE");if(!a)throw new Error(`${i} is not supported`);if(r<0||r>=a)throw new Error(`Bitfield position ${r} is out of bounds (must be between 0 and ${a-1})`);if(!s)throw new Error(`${t} is not valid`);if(s+r>=a)throw new Error(`${i} size (${a}) is not enough to hold ${s} bits starting at position ${r}`);return{kind:"bitfield",type:i,size:a/8,position:e,bitSize:s,bitPosition:r,isBigEndian:c}}o(an,"$");function cn(){let t=this.descriptor.position+this.offset,e=this.descriptor.isBigEndian?"BE":"LE",r=this.buffer[`readUInt${e}`](t,this.descriptor.size);return sn(r,this.descriptor)}o(cn,"C");function ln(t){let e=this.descriptor.position+this.offset,r=this.descriptor.isBigEndian?"BE":"LE",i=this.buffer[`readUInt${r}`](e,this.descriptor.size),n=on(i,this.descriptor,t);this.buffer[`writeUInt${r}`](n,e,this.descriptor.size)}o(ln,"F");var Nr=new Set(["utf8","ascii","string"]);function un(t,e=0){let r=/^(utf8|ascii|string)(?:\[(\d+)\])?$/i,i=t.match(r);if(!i)throw new Error(`Invalid string descriptor: ${t}`);let n=i[1].toLowerCase(),s=i[2]?parseInt(i[2]):void 0;return{type:n,arraySize:s,position:e,size:2,lengthType:"UInt16LE",kind:"string"}}o(un,"A");function qr(t=0){let{position:e,type:r,size:i}=this.descriptor,n=this.offset+e+t,s=r==="string"?"utf8":r;if("lengthType"in this.descriptor&&this.descriptor.lengthType){if(this.descriptor.lengthType.includes("Big"))throw new Error("BigInt are not supported");let a=this.descriptor.lengthType,c=Number(zr(this.buffer,a)(n)),l=n+i;if(this.offset+=c,l+c>this.buffer.length)throw new Error(`String prefix length exceeds buffer position: ${l} size: ${c} > ${this.buffer.length}`);return this.buffer.subarray(l,l+c).toString(s)}if("nullTerminated"in this.descriptor){let a=n,c="maxLength"in this.descriptor?this.descriptor.maxLength:0;for(;a<this.buffer.length&&this.buffer[a]!==0;){if(c&&a>c)throw new Error(`NullTerminated String exceeds maximum length of ${c}`);a++}let l=a-n;return this.offset+=l+1,this.buffer.subarray(n,a).toString(s)}return this.buffer.subarray(n,n+i).toString(s)}o(qr,"M");function hn(){let t=[],{arraySize:e=0,size:r}=this.descriptor;t.length=e;for(let i=0;i<e;i++)t[i]=qr.call(this,i*r);return t}o(hn,"Y");function pn(){return"arraySize"in this.descriptor&&this.descriptor.arraySize?hn.call(this):qr.call(this)}o(pn,"L");function Yr(t,e=0){t??="";let{position:r,type:i,size:n}=this.descriptor,s=this.offset+r+e,a=i==="string"?"utf8":i;if("lengthType"in this.descriptor&&this.descriptor.lengthType){if(this.descriptor.lengthType.includes("Big"))throw new Error("BigInt are not supported");let c=Buffer.from(t,a);Hr(this.buffer,this.descriptor.lengthType)(c.length,s);let[l,h]=Ze(this.buffer,s+n);this.buffer=Buffer.concat([l,c,h]),this.offset+=c.length;return}if("nullTerminated"in this.descriptor){"maxLength"in this.descriptor&&this.descriptor.maxLength&&(t=t.length>this.descriptor.maxLength?t.slice(0,this.descriptor.maxLength):t);let c=t.endsWith("\0")?t:`${t}\0`,l=Buffer.from(c,a),[h,y]=Ze(this.buffer,s,n);this.buffer=Buffer.concat([h,l,y]),this.offset+=l.length;return}this.buffer.write(t,s,n,a)}o(Yr,"k");function fn(t){let{arraySize:e=0,size:r}=this.descriptor;for(let i=0;i<e;i++){let n=i<t.length?t[i]:"";Yr.call(this,n,i*r)}}o(fn,"O");function dn(t){return"arraySize"in this.descriptor&&this.descriptor.arraySize?fn.call(this,Array.isArray(t)?t:[t]):Yr.call(this,Array.isArray(t)?t[0]||"":t)}o(dn,"V");var J=class Qe{static{o(this,"e")}size;schema=new Map;constructor(e){this.size=this.compileSchema(e)}toObject(e,r){if(!Buffer.isBuffer(e))throw new Error(`Expected a buffer, but received ${typeof e}`);if(e.length<this.size)throw new Error(`Buffer size is less than expected: ${e.length} < ${this.size}`);let i={},n={buffer:e,offset:0};for(let[s,a]of this.schema)n.descriptor=a,i[s]=this.readValue(n,a.kind);return r&&typeof r=="function"&&r(n.offset),i}toBuffer(e){if(!e||typeof e!="object")throw new Error(`Expected an object of fields, but received ${typeof e}`);let r={buffer:Buffer.alloc(this.size),offset:0};for(let[i,n]of this.schema){r.descriptor=n;let s=e[i];this.writeValue(r,n.kind,s)}return r.buffer}readValue(e,r){switch(r){case"struct":return qi.call(e);case"bitfield":return cn.call(e);case"string":return pn.call(e);default:return Qi.call(e)}}writeValue(e,r,i){switch(r){case"struct":Gi.call(e,i);break;case"bitfield":ln.call(e,i);break;case"string":dn.call(e,i);break;default:tn.call(e,i)}}computeFieldSize(e,r){if(e.type instanceof Qe)return{...e,position:r,size:e.type.size,kind:"struct"};if(Nr.has(e.type))return this.computeStringFieldSize(e,r);let i=U[e.type];if(i!==void 0)return{...e,position:r,size:i/8,kind:"primitive"};throw new Error(`Invalid field type: ${e.type}`)}computeStringFieldSize(e,r){let i={...e,position:r,kind:"string"};if("lengthType"in e&&e.lengthType){let n=U[e.lengthType];if(!n)throw new Error(`Invalid length type: ${e.lengthType}`);i.size=n/8}else"nullTerminated"in e&&e.nullTerminated?i.size=0:(!("size"in e)||!e.size)&&(i.lengthType="UInt16LE",i.size=U.UInt16LE/8);return i}parseStringNotation(e,r){return e.includes(":")?an(e,r):[...Nr].find(i=>e.startsWith(i))?un(e,r):Xi(e,r)}convertToSizedField(e,r){return e instanceof Qe?{type:e,position:r,size:e.size,kind:"struct"}:typeof e=="string"?this.parseStringNotation(e,r):this.computeFieldSize(e,r)}compileSchema(e){let r={bits:0,bytes:0,bitFieldSize:0,bitFieldType:"UInt8"};for(let[i,n]of Object.entries(e)){let s=this.convertToSizedField(n,r.bytes);if("arraySize"in s&&s.arraySize&&s.arraySize>=Number.MAX_SAFE_INTEGER)throw new Error(`Array size exceeds maximum safe integer: ${s.arraySize}`);"bitSize"in s&&s.bitSize>0?this.processBitfield(r,i,s):this.processStandardField(r,i,s)}return r.bits>0&&(r.bytes+=r.bitFieldSize),r.bytes}processBitfield(e,r,i){let n=i.size*8,s=i.bitSize;(e.bits+s>n||e.bitFieldType!==i.type||e.bitFieldSize!==i.size)&&(e.bytes+=e.bitFieldSize,e.bits=0,i.position=e.bytes),i.bitPosition=e.bits,this.schema.set(r,i),e.bits+=s,e.bitFieldType=i.type,e.bitFieldSize=i.size}processStandardField(e,r,i){e.bits>0&&(e.bytes+=e.bitFieldSize,e.bits=0,i.position=e.bytes),this.schema.set(r,i);let n="arraySize"in i&&i.arraySize||0,s=n>0?i.size*n:i.size;e.bytes+=s}};var mn=new J({line:"UInt32LE",column:"UInt32LE",source:"string"}),tt=new J({kind:"UInt8:4",suiteId:{type:"string",size:14},runnerId:{type:"string",size:14},timestamp:"string"}),Gr=new J({level:"UInt8",message:{type:"string",lengthType:"UInt32LE"},ancestry:{type:"string",lengthType:"UInt32LE"},invocation:mn}),Ae=new J({error:{type:"string",lengthType:"UInt32LE"}}),Xr=new J({type:"UInt8:5",todo:"UInt8:1",skipped:"UInt8:1",duration:"UInt32LE",ancestry:{type:"string",lengthType:"UInt32LE"},description:{type:"string",lengthType:"UInt32LE"}}),Zr=new J({type:"UInt8:5",passed:"UInt8:1",duration:"UInt32LE",ancestry:{type:"string",lengthType:"UInt32LE"},description:{type:"string",lengthType:"UInt32LE"},errors:{type:"string",lengthType:"UInt32LE"}});var Qr={1:Gr,2:Ae,3:Xr,4:Zr};function ue(t,e){let r=Qr[t];if(!r)throw new Error(`Invalid schema kind: ${t}`);let i={kind:t,suiteId:globalThis?.__XJET?.runtime?.suiteId??"",runnerId:globalThis?.__XJET?.runtime.runnerId??"",timestamp:new Date().toISOString()};return Buffer.concat([tt.toBuffer(i),r.toBuffer(e)])}o(ue,"encodePacket");function ti(t,e,r){let i=tt.toBuffer({kind:2,suiteId:e??"",runnerId:r??"",timestamp:new Date().toISOString()}),n=Ae.toBuffer({error:JSON.stringify(_(t))});return Buffer.concat([i,n])}o(ti,"encodeErrorSchema");function V(t,e={}){dispatch(ue(3,{type:t,todo:e?.todo,skipped:e?.skipped,duration:e?.duration,ancestry:e?.ancestry?.join(","),description:e?.description}))}o(V,"emitStatus");function $e(t,e){let r=e.errors?.map(i=>_(i))||[];dispatch(ue(4,{type:t,errors:r.length>0?JSON.stringify(r):"",ancestry:e.ancestry.join(""),duration:e.duration,description:e.description}))}o($e,"emitEvent");var rt=(s=>(s[s.Silent=0]="Silent",s[s.Error=1]="Error",s[s.Warn=2]="Warn",s[s.Info=3]="Info",s[s.Debug=4]="Debug",s))(rt||{});var he=class{constructor(e="",r={skip:!1,only:!1}){this.description=e;this.describeOptions=r}static{o(this,"DescribeModel")}ancestry=[];testsStack=[];describesStack=[];startTime=0;hooks={afterAll:[],afterEach:[],beforeAll:[],beforeEach:[]};get options(){return this.describeOptions}get tests(){return[...this.testsStack,...this.describesStack.flatMap(e=>e.tests)]}addHook(e,r){let i=this.hooks[e];if(!i)throw new Error(`Invalid hook type: ${e}`);i.push(r)}addTest(e){e&&(e.setAncestry(this.ancestry),this.description&&e.setAncestry([this.description]),e.applyExecutionFlags(this.options.skip,this.options.only),this.testsStack.push(e))}addDescribe(e){e&&(e.inheritFromParentDescribe(this),this.describesStack.push(e))}async run(e){this.startTime=Date.now(),this.notifyDescribeStatus(this.options.skip);let r=!e.afterAllErrors?.length,i=!e.beforeAllErrors?.length;try{e.beforeAllErrors?.length||await this.executeHooks("beforeAll",e);for(let n of this.shuffleTests(this.testsStack)){if(e.hasError)return;await n.run(e,this.executeHooks.bind(this))}for(let n of this.describesStack){if(e.hasError)return;await n.run(e)}await this.executeHooks("afterAll",e),e.afterAllErrors?.length?this.notifyDescribeFailure(e.afterAllErrors):this.notifyDescribeAction()}catch(n){this.notifyDescribeFailure([n,...e.afterAllErrors]),globalThis.__XJET?.runtime.bail&&(e.hasError=!0)}finally{r&&(e.afterAllErrors=[]),i&&(e.beforeAllErrors=[])}}inheritFromParentDescribe(e){this.ancestry.push(...e.ancestry),this.hooks.beforeEach=[...e.hooks.beforeEach,...this.hooks.beforeEach],this.hooks.afterEach=[...e.hooks.afterEach,...this.hooks.afterEach],e.description&&this.ancestry.push(e.description),e.options.skip&&(this.describeOptions.skip=!0),e.options.only&&(this.describeOptions.only=!0)}async executeHooks(e,r){if(!this.options.skip){r.beforeAllErrors=r.beforeAllErrors||[],r.afterAllErrors=r.afterAllErrors||[];for(let i of this.hooks[e])try{await i.run(r)}catch(n){await this.handleHookError(e,n,r)}}}async handleHookError(e,r,i){if(e==="beforeAll")i.beforeAllErrors.push(r);else if(e==="afterAll")i.afterAllErrors.push(r);else throw r}getExecutionDuration(){return this.startTime===0?0:Date.now()-this.startTime}notifyDescribeStatus(e=!1){V(2,{skipped:e,ancestry:this.ancestry,description:this.description})}notifyDescribeAction(e=[]){$e(2,{errors:e,ancestry:this.ancestry,description:this.description,duration:this.getExecutionDuration()})}notifyDescribeFailure(e){e?.length&&this.notifyDescribeAction(e)}shuffleTests(e){if(!(globalThis.__XJET?.runtime.randomize??!1)||e.length<=1)return e;let i=e.length;for(let n=i-1;n>0;n--){let s=Math.floor(Math.random()*(n+1));[e[n],e[s]]=[e[s],e[n]]}return e}};var R=class extends Error{static{o(this,"ExecutionError")}constructor(e){super(e),this.name="xJetExecutionError"}toJSON(){let e={};for(let r of Object.keys(this)){let i=this[r];i&&(e[r]=i)}return e.name=this.name,e.stack=this.stack,e.message=this.message,e}};var ni,it;ni=[Se({scope:"singleton"})];var W=class W{static{o(this,"SuiteState")}onlyMode=!1;currentDescribe;currentTest;hasTests=!1;rootDescribe;filterRegexChain=[];constructor(){this.rootDescribe=new he,this.currentDescribe=this.rootDescribe,Array.isArray(__XJET?.runtime.filter)&&__XJET.runtime.filter.length>0&&(this.onlyMode=!0,this.filterRegexChain=__XJET.runtime.filter.map(e=>new RegExp(`^${e}$`)))}static matchesFilter(e,r){if(r.length>e.length)return!1;let i=e.length-r.length;return r.every((n,s)=>n.test(e[i+s]))}get isOnlyMode(){return this.onlyMode}get root(){return this.rootDescribe}get describe(){return this.currentDescribe}get test(){return this.currentTest}set test(e){this.currentTest=e}async run(e){try{let r=Date.now();if(V(4),!this.hasTests)throw new R("Your test suite must contain at least one test");await this.root.run(e),V(3,{duration:Date.now()-r})}catch(r){dispatch(ti(r,__XJET.runtime.suiteId,__XJET.runtime.runnerId))}}addDescribe(e,r,i={},n=[]){let s={skip:!1,only:!1,...i};if(s.only&&(this.onlyMode=!0),this.filterRegexChain.length>0){let l=[...this.currentDescribe.ancestry,this.currentDescribe.description,e];W.matchesFilter(l,this.filterRegexChain)&&(s.only=!0)}let a=new he(e,s);this.currentDescribe.addDescribe(a);let c=this.currentDescribe;this.currentDescribe=a;try{r.apply({},n)}finally{this.currentDescribe=c}}addTest(e){if(this.hasTests=!0,e.options.only&&(this.onlyMode=!0),this.currentDescribe.addTest(e),this.filterRegexChain.length>0){let r=[...e.ancestry,e.description];W.matchesFilter(r,this.filterRegexChain)&&(e.options.only=!0)}}};it=de(null),W=ye(it,0,"SuiteState",ni,W),me(it,1,W);var E=W;var ee={V8:{GLOBAL:/at\s(.*):(\d+):(\d+)/,STANDARD:/at\s(.*?)\((?:(.+?):(\d+):(\d+)|(native))\)/,EVAL:/^at\s(.+?)\s\(eval\sat\s(.+?)\s?\((.*):(\d+):(\d+)\),\s(.+?):(\d+):(\d+)\)$/},SPIDERMONKEY:{EVAL:/^(.*)@(.+?):(\d+):(\d+),\s(.+?)@(.+?):(\d+):(\d+)$/,STANDARD:/^(.*)@(.*?)(?:(\[native code\])|:(\d+):(\d+))$/},JAVASCRIPT_CORE:{STANDARD:/^(?:(global|eval)\s)?(.*)@(.*?)(?::(\d+)(?::(\d+))?)?$/}},yn=(t=>(t[t.V8=0]="V8",t[t.SPIDERMONKEY=1]="SPIDERMONKEY",t[t.JAVASCRIPT_CORE=2]="JAVASCRIPT_CORE",t[t.UNKNOWN=3]="UNKNOWN",t))(yn||{});function gn(t){return t.startsWith(" at ")||t.startsWith("at ")?0:t.includes("@")?/(?:global|eval) code@/.test(t)?2:1:3}o(gn,"l");function q(t){return t.startsWith("file://")?t.startsWith("file:///")&&/^file:\/\/\/[A-Za-z]:/.test(t)?t.substring(8):t.substring(7):(t=t.replace(/\\/g,"/"),t)}o(q,"c");function nt(t){return{source:t,eval:!1,async:!1,native:!1,constructor:!1}}o(nt,"u");function $(t){return t&&t.trim()!==""?parseInt(t,10):void 0}o($,"i");function vn(t){let e=nt(t);t.toLowerCase().includes("new")&&(e.constructor=!0),t.toLowerCase().includes("async")&&(e.async=!0);let r=t.match(ee.V8.EVAL),i=t.match(ee.V8.GLOBAL),n=!r&&t.match(ee.V8.STANDARD);return r?(e.eval=!0,e.functionName=r[1]||void 0,e.evalOrigin={line:$(r[4])??void 0,column:$(r[5])??void 0,fileName:r[3]?q(r[3]):void 0,functionName:r[2]||"<anonymous>"},e.line=$(r[7])??void 0,e.column=$(r[8])??void 0,e.fileName=r[6]?q(r[6]):void 0):n?(e.functionName=n[1]?n[1].trim():void 0,n[5]==="native"?(e.native=!0,e.fileName="[native code]"):(e.line=$(n[3])??void 0,e.column=$(n[4])??void 0,e.fileName=n[2]?q(n[2]):void 0,e.fileName?.includes("node:")&&(e.native=!0))):i&&(e.fileName=i[1]?q(i[1]):void 0,e.line=$(i[2])??void 0,e.column=$(i[3])??void 0),e}o(vn,"N");function bn(t){let e=nt(t),r=t.match(ee.SPIDERMONKEY.EVAL);if(r)return e.eval=!0,e.functionName=r[1]?r[1]:void 0,t.toLowerCase().includes("constructor")&&(e.constructor=!0),t.toLowerCase().includes("async")&&(e.async=!0),e.evalOrigin={line:$(r[7])??void 0,column:$(r[8])??void 0,fileName:q(r[6]),functionName:r[5]?r[5]:void 0},e.line=$(r[3])??void 0,e.column=$(r[4])??void 0,e;let i=t.match(ee.SPIDERMONKEY.STANDARD);return i&&(e.functionName=i[1]?i[1]:void 0,e.fileName=q(i[2]),i[3]==="[native code]"?e.fileName="[native code]":(e.line=$(i[4])??void 0,e.column=$(i[5])??void 0)),e}o(bn,"S");function Tn(t){let e=nt(t),r=t.match(ee.JAVASCRIPT_CORE.STANDARD);return r&&(e.functionName=r[2],e.eval=r[1]==="eval"||r[3]==="eval",t.toLowerCase().includes("constructor")&&(e.constructor=!0),t.toLowerCase().includes("async")&&(e.async=!0),r[3]==="[native code]"?(e.native=!0,e.fileName="[native code]"):(e.line=$(r[4])??void 0,e.column=$(r[5])??void 0,e.fileName=q(r[3]))),e}o(Tn,"p");function xn(t,e){switch(e){case 1:return bn(t);case 2:return Tn(t);case 0:default:return vn(t)}}o(xn,"g");function En(t){if(!t)return"";let e=/^\s*at .+$|^.+@.+:\d+:\d+$|^@.+:\d+:\d+$|^.+@\[native code\]$/,r=t.split(`
66
- `);for(let i=0;i<r.length;i++)if(e.test(r[i]))return r.slice(i).join(`
67
- `);return""}o(En,"A");function si(t){let e=typeof t=="string"?{stack:t,message:t,name:""}:t,r=e.name||"Error",i=En(e.stack||""),n=e?.message||"",s=gn(i),a=i.split(`
68
- `).map(c=>c.trim()).filter(c=>c.trim()!=="");return{name:r,message:n,stack:a.map(c=>xn(c,s)),rawStack:i}}o(si,"E");function oi(t=2){let r=si(new Error).stack[t];if(r?.line&&r?.column&&r?.fileName)return{line:r.line,column:r.column,source:r.fileName}}o(oi,"getInvocationLocation");function Y(t=2){let e=new Error;return e.stack?e.stack.split(`
69
- `).slice(t+1).join(`
70
- `):""}o(Y,"getTrimmedStackString");function pe(t){return function(...e){let r=v(E).test;r||(r=v(E).describe);let i=[...r?.ancestry??[],r?.description].join(","),n=e.map(a=>w(a).join(`
71
- `)).join(" "),s=oi();dispatch(ue(1,{level:rt[t],message:n,ancestry:i??"",invocation:s}))}}o(pe,"createLogHandler");var ai=pe("Info"),ci=pe("Info"),li=pe("Warn"),ui=pe("Error"),hi=pe("Debug");function st(t){if(t==null)return;let e=typeof t=="function"?t.name:void 0;if(e&&e in globalThis)return{name:e,object:globalThis};for(let[r,i]of Object.entries(globalThis)){if(i&&e&&(typeof i=="object"||typeof i=="function")&&e in i)return{name:e,object:i};if(Object.is(t,i))return{name:r,object:globalThis}}}o(st,"getParentObject");function ot(t,e){let r=Reflect.get(t,e),i=Object.getOwnPropertyDescriptor(t,e)||{},n=new A(()=>r,()=>{Reflect.set(t,e,i.value),Object.defineProperty(t,e,i)},"xJet.spyOn()");return A.mocks.push(n),Object.defineProperty(t,e,{get(){return n.apply(this,[])},set(s){return n.mockImplementation(()=>s),n.apply(this,[s])}}),n}o(ot,"mockDescriptorProperty");function pi(t,e){return new A(t,e,"xJet.fn()")}o(pi,"fnImplementation");function fi(t,e){if(typeof t=="function"&&t.xJetMock)return t;let r=st(t);if(!r)throw new R("xJet.mock item is not part of any global object");let{name:i,object:n}=r,s=Reflect.get(n,i);if(typeof t=="function"&&t.prototype&&!Object.getOwnPropertyDescriptor(t,"prototype")?.writable){let c=new A((...l)=>new t(...l),()=>{Reflect.set(n,i,s)});return Reflect.set(n,i,c),A.mocks.push(c),e&&c.mockImplementation(e),n[i]}if(typeof t=="function"){let c=new A(t,()=>{Reflect.set(n,i,s)});return Reflect.set(n,i,c),A.mocks.push(c),e&&c.mockImplementation(e),n[i]}let a=ot(n,i);return e&&a.mockImplementation(e),a}o(fi,"mockImplementation");var di=new WeakMap;function wn(t,e){return!(e in t)&&Reflect.get(t,e)!==void 0}o(wn,"isProxyProperty");function Sn(t,e,r){let i=st(t);if(!i)throw new Error("xJet.spyOn item is not part of any global object");let n=di.get(t);n||(n={proxy:null,spies:new Map},n.proxy=new Proxy(t,{get(c,l,h){return n.spies.has(l)?n.spies.get(l)():Reflect.get(c,l,h)}}),di.set(t,n),Reflect.set(i.object,i.name,n.proxy));let s=r,a=new A(s,()=>{n.spies.delete(e),Reflect.set(i.object,i.name,t)},"xJet.spyOn(Proxy#get)");return A.mocks.push(a),n.spies.set(e,a),a}o(Sn,"spyOnProxyGet");function mi(t,e){if(t==null||typeof t!="object"&&typeof t!="function")throw new R("Target must be an object or function");if(e===null)throw new R("Spied property/method key is required");if(wn(t,e))return Sn(t,e,Reflect.get(t,e));if(!(e in t))throw new R(`Property/method '${String(e)}' does not exist on target`);let r=Reflect.get(t,e);if(!r)throw new Error(`Property '${String(e)}' does not exist in the provided object`);if(r.xJetMock)return r;let i=Object.getOwnPropertyDescriptor(t,e);if(typeof r!="function"||i?.get)return ot(t,e);let n=r,s=Object.getOwnPropertyDescriptor(n,"prototype");n.prototype&&s&&!s.writable&&(n=o((...c)=>new r(...c),"fn"));let a=new A(n,()=>{Reflect.set(t,e,r)},"xJet.spyOn()");return A.mocks.push(a),Reflect.set(t,e,a),a}o(mi,"spyOnImplementation");var yi,at;yi=[Se({scope:"singleton"})];var L=class{static{o(this,"TimerService")}timers=new Map;originalDateNow=Date.now;originalSetTimeout=globalThis.setTimeout;originalSetInterval=globalThis.setInterval;originalClearTimeout=globalThis.clearTimeout;originalClearInterval=globalThis.clearInterval;now=0;nextId=1;useFakeTimers(){let e=o((a,c=0,...l)=>{let h=this.nextId++;return this.timers.set(h,{id:h,callback:a,time:this.now+c,interval:null,args:l??[]}),h},"setTimeout"),r=o((a,c=0)=>{let l=this.nextId++;return this.timers.set(l,{id:l,callback:a,time:this.now+c,interval:c,args:[]}),l},"setInterval"),i=o(a=>{this.timers.delete(a)},"clearTimeout"),n=o(a=>{this.timers.delete(a)},"clearInterval"),s=globalThis;s.setTimeout=e,s.setInterval=r,s.clearTimeout=i,s.clearInterval=n}useRealTimers(){globalThis.setTimeout=this.originalSetTimeout,globalThis.clearTimeout=this.originalClearTimeout,globalThis.setInterval=this.originalSetInterval,globalThis.clearInterval=this.originalClearInterval,Date.now=this.originalDateNow}advanceTimersByTime(e){this.now+=e,this.runDueTimers()}runAllTimers(){for(;this.timers.size>0;)this.now=Math.min(...Array.from(this.timers.values()).map(e=>e.time)),this.runDueTimers()}runOnlyPendingTimers(){let e=new Set(this.timers.keys());for(;e.size>0;){let r=Array.from(this.timers.values()).filter(i=>e.has(i.id)).map(i=>i.time);if(r.length===0)break;this.now=Math.min(...r),this.runDueTimers(e);for(let i of e)this.timers.has(i)||e.delete(i)}}runDueTimers(e){let r=!0;for(;r;){r=!1;let i=Array.from(this.timers.values()).sort((n,s)=>n.time-s.time);for(let n of i)if(this.timers.has(n.id)&&!(e&&!e.has(n.id))&&n.time<=this.now){if(n.interval!==null)for(;n.time<=this.now;)n.callback(),n.time+=n.interval;else n.callback(),this.timers.delete(n.id);r=!0}}}};at=de(null),L=ye(at,0,"TimerService",yi,L),me(at,1,L);function gi(){v(L).useFakeTimers()}o(gi,"useFakeTimers");function vi(){v(L).useRealTimers()}o(vi,"useRealTimers");function bi(){v(L).runAllTimers()}o(bi,"runAllTimers");function Ti(){v(L).runOnlyPendingTimers()}o(Ti,"runOnlyPendingTimers");function xi(t=0){v(L).advanceTimersByTime(t)}o(xi,"advanceTimersByTime");var $n=/\$([#\w.])+/g;function In(t){return typeof t=="string"?t:JSON.stringify(t,null,4)}o(In,"prettyFormat");function Cn(t,e){if(!(!e.length||!t))try{return e.reduce((r,i)=>{if(r==null||typeof r!="object")throw new Error("Path traversal failed");return r[i]},t)}catch{return}}o(Cn,"getValueByPath");function Rn(t,e,r){if(!t||typeof t!="string"||!t.startsWith("$"))return t;if(t==="$#")return String(r);let i=t.slice(1).split("."),n=Cn(e,i);if(n==null)return t;if(typeof n=="object")try{return JSON.stringify(n,(s,a)=>s&&typeof a=="object"?"[Object]":a)}catch{return String(n)}return String(n)}o(Rn,"resolveVariable");function Ln(t,e,r){return t.replace($n,i=>Rn(i,e,r))}o(Ln,"interpolateVariables");function Ei(t,e,r){let i=0;return t.includes("$")&&!t.includes("%%")&&(t=Ln(t,e[0],r)),t.replace(/%([psdifjo#%])/g,(n,s)=>{if(s==="%")return"%";if(s==="#")return String(r);let a=e[i++];switch(s){case"p":return In(a);case"s":return String(a);case"d":return Number(a).toString();case"i":return Math.floor(Number(a)).toString();case"f":return Number(a).toString();case"j":return JSON.stringify(a);case"o":return Object.prototype.toString.call(a);default:return n}})}o(Ei,"printf");function On(t,e){let r=t[0].split("|").map(i=>i.trim());if(r.length===0||r.some(i=>i===""))throw new Error("Template string headings must not be empty and should contain pipe delimiters.");if(e.length%r.length!==0)throw new Error("Not enough arguments supplied for given headings.");return Array.from({length:e.length/r.length},(i,n)=>r.reduce((s,a,c)=>(s[a]=e[n*r.length+c],s),{}))}o(On,"parseTemplate");function Ie(t,...e){if(e.length<2)throw new Error("`.each` must be called with at leas 2 argument or Tagged Template Literal.");let i=e[0]instanceof Array&&e[0].raw!==void 0?On(e.shift(),e):e;return(n,s,a)=>{i.forEach((c,l)=>{let h=Array.isArray(c)?c:[c];t(Ei(n,h,Number(l)),s,h,a)})}}o(Ie,"each");var Ce=class extends Error{static{o(this,"TimeoutError")}constructor(e,r,i=""){super(`Exceeded timeout of ${e} ms at ${r}`),Object.setPrototypeOf(this,new.target.prototype),this.name="xJetTimeoutError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="xJetFailingError",i&&(this.stack=`${this.name}: ${this.message}
72
- ${i}`)}};async function Re(t,e,r,i){let n=v(L),s=typeof t=="function"?Promise.resolve(t()):Promise.resolve(t);if(e===-1||!n.originalSetTimeout)return s;let a,c=new Promise((l,h)=>{a=n.originalSetTimeout?.(()=>h(new Ce(e,r,i)),e)});try{return await Promise.race([s,c])}finally{n.originalClearTimeout?.(a)}}o(Re,"withTimeout");var Le=class t extends R{static{o(this,"FailingError")}constructor(e){super("Failing test passed even though it was supposed to fail. Remove `.failing` to remove error."),Error.captureStackTrace&&Error.captureStackTrace(this,t),this.name="xJetFailingError",this.stack=`${this.name}: ${this.message}
73
- ${e}`}};var Oe=class{constructor(e,r,i,n=[],s={}){this.description=e;this.testImplementation=r;this.timeoutDuration=i;this.testParameters=n;this.testOptions=s}static{o(this,"TestModel")}ancestry=[];executionLocation="";executionStartTime=0;get options(){return this.testOptions}setExecutionLocation(e){this.executionLocation=e}applyExecutionFlags(e,r){this.testOptions.skip||=e,this.testOptions.only||=r}setAncestry(e){this.ancestry.push(...e)}async run(e,r,i=!1){if(v(E).test=this,this.executionStartTime=Date.now(),!this.shouldSkipDueToSetupErrors(e)&&!this.determineSkipAction(i))try{await this.executeTestWithLifecycle(e,r),this.validateTestOutcome()}catch(n){this.notifyTestFailure(n),globalThis.__XJET?.runtime.bail&&(e.hasError=!0)}finally{v(E).test=void 0}}shouldSkipDueToSetupErrors(e){return e.beforeAllErrors&&e.beforeAllErrors.length>0?(this.notifyTestFailure(e.beforeAllErrors),!0):!1}determineSkipAction(e){return v(E).isOnlyMode&&!this.testOptions.only?(this.notifyTestStatus(!0),!0):this.testOptions.skip||this.testOptions.todo?(this.notifyTestStatus(this.testOptions.skip,this.testOptions.todo),!0):e&&!this.testOptions.only?(this.notifyTestStatus(!0),!0):!1}async executeTestWithLifecycle(e,r){await r("beforeEach",e),await Re(this.executeTestWithContext(e),this.timeoutDuration,`'${this.timeoutDuration}' test`,this.executionLocation),await r("afterEach",e)}validateTestOutcome(){if(this.testOptions.failing)throw new Le(this.executionLocation);this.notifyTestAction()}isCallbackStyle(){return this.testImplementation.length===1&&this.testParameters.length===0?!0:this.testImplementation.length===2}getExecutionStrategy(){return Z(this.testImplementation)?"ASYNC":this.isCallbackStyle()?"CALLBACK":"SYNC"}async executeTestWithContext(e){switch(this.getExecutionStrategy()){case"ASYNC":case"SYNC":await this.testImplementation.apply(e,this.testParameters);break;case"CALLBACK":await this.executeCallbackStyleTest(e);break}}async executeCallbackStyleTest(e){return new Promise((r,i)=>{let n=o(a=>{a&&i(a),r()},"callbackFn"),s=[...this.testParameters];s.push(n),this.testImplementation.apply(e,s)})}getExecutionDuration(){return this.executionStartTime===0?0:Date.now()-this.executionStartTime}notifyTestStatus(e=!1,r=!1){V(1,{todo:r,skipped:e,ancestry:this.ancestry,description:this.description})}notifyTestAction(e=[]){$e(1,{errors:e,ancestry:this.ancestry,duration:this.getExecutionDuration(),description:this.description})}notifyTestFailure(e){this.notifyTestAction(Array.isArray(e)?e:[e])}};var fe=class t extends Function{static{o(this,"TestDirective")}static instance;static ERROR_MESSAGES={SKIP_ONLY:'Cannot use "only" flag on skipped test',ONLY_SKIP:'Cannot use "skip" flag on only test',SKIP_TODO:'Cannot use "todo" flag on skipped test',SKIP_FAILING:'Cannot use "failing" flag on skipped test'};static DEFAULT_TIMEOUT=globalThis.__XJET?.runtime.timeout??5e3;options={};invocationStack="";constructor(){return super(),new Proxy(this,{apply:o((e,r,i)=>{let[n,s,a]=i;this.invocationStack=Y(2),e.invoke(n,s,[],a)},"apply")})}static getInstance(){return t.instance||(t.instance=new t),t.instance}get skip(){if(this.options.only)throw new Error(t.ERROR_MESSAGES.ONLY_SKIP);return this.options.skip=!0,this}get only(){if(this.options.skip)throw new Error(t.ERROR_MESSAGES.SKIP_ONLY);return this.options.only=!0,this}get todo(){if(this.options.skip)throw new Error(t.ERROR_MESSAGES.SKIP_TODO);return this.options.todo=!0,this}get failing(){if(this.options.skip)throw new Error(t.ERROR_MESSAGES.SKIP_FAILING);return this.options.failing=!0,this}each(...e){return Ie(this.invoke.bind(this),...e)}invoke(e,r,i=[],n){this.validateTestNesting(e),r||(this.options.todo=!0);let s=this.createTest(e,r,i,n);this.registerTest(s,this.invocationStack),this.resetFlags()}validateTestNesting(e){let r=v(E).test;if(r)throw new Error(`Cannot nest a test inside a test '${e}' in '${r.description}'`)}createTest(e,r,i,n){return new Oe(e,r,n??t.DEFAULT_TIMEOUT,i,{...this.options})}registerTest(e,r){r&&e.setExecutionLocation(r),v(E).addTest(e)}resetFlags(){this.options={}}};var je=class t extends Function{static{o(this,"DescribeDirective")}static instance=null;options={};constructor(){return super(),new Proxy(this,{apply(e,r,i){e.invoke(i[0],i[1])}})}static getInstance(){return t.instance||(t.instance=new t),t.instance}get skip(){if(this.options.only)throw new Error('Cannot use "skip" flag on only test');return this.options.skip=!0,this}get only(){if(this.options.skip)throw new Error('Cannot use "only" flag on skipped test');return this.options.only=!0,this}each(...e){return Ie(this.invoke.bind(this),...e)}invoke(e,r,i=[]){let n=v(E),s=n.test;if(s)throw new Error(`Cannot nest a describe inside a test '${e}' in '${s.description}'`);n.addDescribe(e,r,this.options,i),this.options={}}};var Be=class{constructor(e,r){this.hookFunction=e;this.timeout=r}static{o(this,"HookModel")}location="";setLocation(e){this.location=e}async run(e){return Re(this.executeHook(this.hookFunction,e),this.timeout,"hook while waiting for 'done()' to be called.",this.location)}async executeHook(e,r){if(Z(e)&&e.length>0)throw new Error(`Async hook '${e.name}' should not use 'done' callback.`);return e.length>0?this.executeCallbackHook(e,r):e.call(r)}executeCallbackHook(e,r){return new Promise((i,n)=>{e.call(r,s=>{s?n(s):i()})})}};var jn=globalThis.__XJET?.runtime.timeout??5e3;function Pe(t,e,r,i=jn){let n=new Be(e,i);n.setLocation(r),v(E).describe.addHook(t,n)}o(Pe,"createHook");function ki(t,e){Pe("afterAll",t,Y(),e)}o(ki,"afterAllDirective");function wi(t,e){Pe("beforeAll",t,Y(),e)}o(wi,"beforeAllDirective");function Si(t,e){Pe("afterEach",t,Y(),e)}o(Si,"afterEachDirective");function Ai(t,e){Pe("beforeEach",t,Y(),e)}o(Ai,"beforeEachDirective");function ct(t){[...A.mocks].map(r=>{r[t]()})}o(ct,"clearMocks");var Bn=o(()=>{let t=globalThis;t.xJet={fn:pi,mock:fi,spyOn:mi,clearAllMocks:o(()=>ct("mockClear"),"clearAllMocks"),resetAllMocks:o(()=>ct("mockReset"),"resetAllMocks"),restoreAllMocks:o(()=>ct("mockRestore"),"restoreAllMocks"),log:ai,info:ci,warn:li,error:ui,debug:hi,runAllTimers:bi,useFakeTimers:gi,useRealTimers:vi,advanceTimersByTime:xi,runOnlyPendingTimers:Ti},t.expect=Pr,t.state=v(E),t.it=fe.getInstance(),t.test=fe.getInstance(),t.describe=je.getInstance(),t.afterAll=ki,t.beforeAll=wi,t.afterEach=Si,t.beforeEach=Ai},"setupGlobals");Bn();
1
+ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __knownSymbol=(name,symbol)=>(symbol=Symbol[name])?symbol:Symbol.for("Symbol."+name),__typeError=msg=>{throw TypeError(msg)};var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __decoratorStart=base=>[,,,__create(base?.[__knownSymbol("metadata")]??null)],__decoratorStrings=["class","method","getter","setter","accessor","field","value","get","set"],__expectFn=fn=>fn!==void 0&&typeof fn!="function"?__typeError("Function expected"):fn,__decoratorContext=(kind,name,done,metadata,fns)=>({kind:__decoratorStrings[kind],name,metadata,addInitializer:fn=>done._?__typeError("Already initialized"):fns.push(__expectFn(fn||null))}),__decoratorMetadata=(array,target)=>__defNormalProp(target,__knownSymbol("metadata"),array[3]),__runInitializers=(array,flags,self,value)=>{for(var i=0,fns=array[flags>>1],n=fns&&fns.length;i<n;i++)flags&1?fns[i].call(self):value=fns[i].call(self,value);return value},__decorateElement=(array,flags,name,decorators,target,extra)=>{var fn,it,done,ctx,access,k=flags&7,s=!!(flags&8),p=!!(flags&16),j=k>3?array.length+1:k?s?1:2:0,key=__decoratorStrings[k+5],initializers=k>3&&(array[j-1]=[]),extraInitializers=array[j]||(array[j]=[]),desc=k&&(!p&&!s&&(target=target.prototype),k<5&&(k>3||!p)&&__getOwnPropDesc(k<4?target:{get[name](){return __privateGet(this,extra)},set[name](x){return __privateSet(this,extra,x)}},name));k?p&&k<4&&__name(extra,(k>2?"set ":k>1?"get ":"")+name):__name(target,name);for(var i=decorators.length-1;i>=0;i--)ctx=__decoratorContext(k,name,done={},array[3],extraInitializers),k&&(ctx.static=s,ctx.private=p,access=ctx.access={has:p?x=>__privateIn(target,x):x=>name in x},k^3&&(access.get=p?x=>(k^1?__privateGet:__privateMethod)(x,target,k^4?extra:desc.get):x=>x[name]),k>2&&(access.set=p?(x,y)=>__privateSet(x,target,y,k^4?extra:desc.set):(x,y)=>x[name]=y)),it=(0,decorators[i])(k?k<4?p?extra:desc[key]:k>4?void 0:{get:desc.get,set:desc.set}:target,ctx),done._=1,k^4||it===void 0?__expectFn(it)&&(k>4?initializers.unshift(it):k?p?extra=it:desc[key]=it:target=it):typeof it!="object"||it===null?__typeError("Object expected"):(__expectFn(fn=it.get)&&(desc.get=fn),__expectFn(fn=it.set)&&(desc.set=fn),__expectFn(fn=it.init)&&initializers.unshift(fn));return k||__decoratorMetadata(array,target),desc&&__defProp(target,name,desc),p?k^4?extra:desc:target};var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg),__privateIn=(member,obj)=>Object(obj)!==obj?__typeError('Cannot use the "in" operator on this value'):member.has(obj),__privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj));var __privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),__privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method);import{xExpect}from"@remotex-labs/xjet-expect";var DEFAULT_MOCK_NAME="xJet.mock()",MockState=class extends Function{static{__name(this,"MockState")}static mocks=new Set;name;xJetMock=!0;state;queuedImplementations=[];implementation;originalImplementation;restore;constructor(implementation,restore,name){return super(),this.name=name??DEFAULT_MOCK_NAME,this.state=this.initState(),this.implementation=implementation||void 0,this.restore=restore,this.originalImplementation=implementation||(()=>{}),new Proxy(this,{get:this.invokeGet,apply:this.invokeFunction,construct:this.invokeClass})}get mock(){return Object.freeze({...this.state})}get original(){return this.originalImplementation}mockClear(){return this.state=this.initState(),this}mockReset(){return this.mockClear(),this.queuedImplementations=[],this}mockRestore(){this.mockReset();let restore=this.restore?.();return typeof restore=="function"?this.implementation=restore:this.implementation=this.originalImplementation,this}getMockImplementation(){return this.implementation}getNextImplementation(){return this.queuedImplementations.length?this.queuedImplementations.shift():this.implementation}mockImplementation(fn){return this.implementation=fn,this}mockImplementationOnce(fn){return this.queuedImplementations.push(fn),this}mockReturnValue(value){return this.mockImplementation(()=>value),this}mockReturnValueOnce(value){return this.mockImplementationOnce(()=>value),this}mockResolvedValue(value){return this.mockImplementation(()=>Promise.resolve(value)),this}mockResolvedValueOnce(value){return this.mockImplementationOnce(()=>Promise.resolve(value)),this}mockRejectedValue(value){return this.mockImplementation(()=>Promise.reject(value)),this}mockRejectedValueOnce(value){return this.mockImplementationOnce(()=>Promise.reject(value)),this}[Symbol.for("nodejs.util.inspect.custom")](){return`<Mock Constructor ${this.name}>`}initState(){return{calls:[],results:[],lastCall:void 0,contexts:[],instances:[],invocationCallOrder:[]}}invoke(thisArg,args){let thisContext=thisArg,impl=this.getNextImplementation(),argsArray=args;typeof impl=="function"&&(impl.__boundArgs&&argsArray.unshift(...impl.__boundArgs),impl.__boundThis&&(thisContext=impl.__boundThis)),this.state.calls.push(argsArray),this.state.contexts.push(thisContext),this.state.invocationCallOrder.push(this.state.invocationCallOrder.length+1);let result,index=this.state.results.push({value:void 0,type:"incomplete"})-1;if(impl)try{result={type:"return",value:impl.call(void 0,...args)}}catch(error2){result={value:error2,type:"throw"}}else result={type:"return",value:void 0};return this.state.lastCall=args,this.state.results[index]=result,result.value}invokeGet(target,property){return Reflect.has(target,property)?Reflect.get(target,property):Reflect.get(target.originalImplementation,property)}invokeClass(target,argArray,newTarget){let result=target.invoke.call(target,newTarget,argArray),isClassInstance=typeof result=="object"&&result!==null&&"constructor"in result;return target.state.instances.push(isClassInstance?result:newTarget),typeof result=="object"?result:newTarget}invokeFunction(target,thisArg,argumentsList){return target.state.instances.push(thisArg),target.invoke.call(target,thisArg,argumentsList)}};var SINGLETONS=new Map,INJECTABLES=new Map;function Injectable(options){return function(target){INJECTABLES.set(target,options||{})}}__name(Injectable,"Injectable");function inject(token,...args){if(SINGLETONS.has(token))return SINGLETONS.get(token);let metadata=INJECTABLES.get(token);if(!metadata)throw new Error(`Cannot inject ${token.name} \u2013 not marked @Injectable`);let instance=metadata.factory?metadata.factory(...args):new token(...args);return metadata?.scope==="singleton"&&SINGLETONS.set(token,instance),instance}__name(inject,"inject");import{serializeError as serializeError2}from"@remotex-labs/xjet-expect";import{serializeError}from"@remotex-labs/xjet-expect";import{Struct}from"@remotex-labs/xstruct";var invocationSchema=new Struct({line:"UInt32LE",column:"UInt32LE",source:"string"}),headerSchema=new Struct({kind:"UInt8:4",suiteId:{type:"string",size:14},runnerId:{type:"string",size:14},timestamp:"string"}),logSchema=new Struct({level:"UInt8",message:{type:"string",lengthType:"UInt32LE"},ancestry:{type:"string",lengthType:"UInt32LE"},invocation:invocationSchema}),errorSchema=new Struct({error:{type:"string",lengthType:"UInt32LE"}}),statusSchema=new Struct({type:"UInt8:5",todo:"UInt8:1",skipped:"UInt8:1",duration:"UInt32LE",ancestry:{type:"string",lengthType:"UInt32LE"},description:{type:"string",lengthType:"UInt32LE"}}),eventsSchema=new Struct({type:"UInt8:5",passed:"UInt8:1",duration:"UInt32LE",ancestry:{type:"string",lengthType:"UInt32LE"},description:{type:"string",lengthType:"UInt32LE"},errors:{type:"string",lengthType:"UInt32LE"}});var PacketSchemas={1:logSchema,2:errorSchema,3:statusSchema,4:eventsSchema};function encodePacket(kind,data){let schema=PacketSchemas[kind];if(!schema)throw new Error(`Invalid schema kind: ${kind}`);let header={kind,suiteId:globalThis?.__XJET?.runtime?.suiteId??"",runnerId:globalThis?.__XJET?.runtime.runnerId??"",timestamp:new Date().toISOString()};return Buffer.concat([headerSchema.toBuffer(header),schema.toBuffer(data)])}__name(encodePacket,"encodePacket");function encodeErrorSchema(error2,suiteId,runnerId){let header=headerSchema.toBuffer({kind:2,suiteId:suiteId??"",runnerId:runnerId??"",timestamp:new Date().toISOString()}),dataBuffer=errorSchema.toBuffer({error:JSON.stringify(serializeError(error2))});return Buffer.concat([header,dataBuffer])}__name(encodeErrorSchema,"encodeErrorSchema");function emitStatus(type,notification={}){dispatch(encodePacket(3,{type,todo:notification?.todo,skipped:notification?.skipped,duration:notification?.duration,ancestry:notification?.ancestry?.join(","),description:notification?.description}))}__name(emitStatus,"emitStatus");function emitEvent(type,notification){let stringErrors=notification.errors?.map(error2=>serializeError2(error2))||[];dispatch(encodePacket(4,{type,errors:stringErrors.length>0?JSON.stringify(stringErrors):"",ancestry:notification.ancestry.join(""),duration:notification.duration,description:notification.description}))}__name(emitEvent,"emitEvent");var LogLevel=(LogLevel2=>(LogLevel2[LogLevel2.Silent=0]="Silent",LogLevel2[LogLevel2.Error=1]="Error",LogLevel2[LogLevel2.Warn=2]="Warn",LogLevel2[LogLevel2.Info=3]="Info",LogLevel2[LogLevel2.Debug=4]="Debug",LogLevel2))(LogLevel||{});var DescribeModel=class{constructor(description="",describeOptions={skip:!1,only:!1}){this.description=description;this.describeOptions=describeOptions}static{__name(this,"DescribeModel")}ancestry=[];testsStack=[];describesStack=[];startTime=0;hooks={afterAll:[],afterEach:[],beforeAll:[],beforeEach:[]};get options(){return this.describeOptions}get tests(){return[...this.testsStack,...this.describesStack.flatMap(child=>child.tests)]}addHook(type,hook){let hookArray=this.hooks[type];if(!hookArray)throw new Error(`Invalid hook type: ${type}`);hookArray.push(hook)}addTest(test){test&&(test.setAncestry(this.ancestry),this.description&&test.setAncestry([this.description]),test.applyExecutionFlags(this.options.skip,this.options.only),this.testsStack.push(test))}addDescribe(describe){describe&&(describe.inheritFromParentDescribe(this),this.describesStack.push(describe))}async run(context){this.startTime=Date.now(),this.notifyDescribeStatus(this.options.skip);let afterAllErrorsEmpty=!context.afterAllErrors?.length,beforeAllErrorsEmpty=!context.beforeAllErrors?.length;try{context.beforeAllErrors?.length||await this.executeHooks("beforeAll",context);for(let test of this.shuffleTests(this.testsStack)){if(context.hasError)return;await test.run(context,this.executeHooks.bind(this))}for(let describe of this.describesStack){if(context.hasError)return;await describe.run(context)}await this.executeHooks("afterAll",context),context.afterAllErrors?.length?this.notifyDescribeFailure(context.afterAllErrors):this.notifyDescribeAction()}catch(error2){this.notifyDescribeFailure([error2,...context.afterAllErrors]),globalThis.__XJET?.runtime.bail&&(context.hasError=!0)}finally{afterAllErrorsEmpty&&(context.afterAllErrors=[]),beforeAllErrorsEmpty&&(context.beforeAllErrors=[])}}inheritFromParentDescribe(parent){this.ancestry.push(...parent.ancestry),this.hooks.beforeEach=[...parent.hooks.beforeEach,...this.hooks.beforeEach],this.hooks.afterEach=[...parent.hooks.afterEach,...this.hooks.afterEach],parent.description&&this.ancestry.push(parent.description),parent.options.skip&&(this.describeOptions.skip=!0),parent.options.only&&(this.describeOptions.only=!0)}async executeHooks(type,context){if(!this.options.skip){context.beforeAllErrors=context.beforeAllErrors||[],context.afterAllErrors=context.afterAllErrors||[];for(let hook of this.hooks[type])try{await hook.run(context)}catch(error2){await this.handleHookError(type,error2,context)}}}async handleHookError(type,error2,context){if(type==="beforeAll")context.beforeAllErrors.push(error2);else if(type==="afterAll")context.afterAllErrors.push(error2);else throw error2}getExecutionDuration(){return this.startTime===0?0:Date.now()-this.startTime}notifyDescribeStatus(skip=!1){emitStatus(2,{skipped:skip,ancestry:this.ancestry,description:this.description})}notifyDescribeAction(errors=[]){emitEvent(2,{errors,ancestry:this.ancestry,description:this.description,duration:this.getExecutionDuration()})}notifyDescribeFailure(errors){errors?.length&&this.notifyDescribeAction(errors)}shuffleTests(testsToShuffle){if(!(globalThis.__XJET?.runtime.randomize??!1)||testsToShuffle.length<=1)return testsToShuffle;let length=testsToShuffle.length;for(let i=length-1;i>0;i--){let j=Math.floor(Math.random()*(i+1));[testsToShuffle[i],testsToShuffle[j]]=[testsToShuffle[j],testsToShuffle[i]]}return testsToShuffle}};var ExecutionError=class extends Error{static{__name(this,"ExecutionError")}constructor(message){super(message),this.name="xJetExecutionError"}toJSON(){let json={};for(let key of Object.keys(this)){let value=this[key];value&&(json[key]=value)}return json.name=this.name,json.stack=this.stack,json.message=this.message,json}};var _SuiteState_decorators,_init;_SuiteState_decorators=[Injectable({scope:"singleton"})];var _SuiteState=class _SuiteState{static{__name(this,"SuiteState")}onlyMode=!1;currentDescribe;currentTest;hasTests=!1;rootDescribe;filterRegexChain=[];constructor(){this.rootDescribe=new DescribeModel,this.currentDescribe=this.rootDescribe,Array.isArray(__XJET?.runtime.filter)&&__XJET.runtime.filter.length>0&&(this.onlyMode=!0,this.filterRegexChain=__XJET.runtime.filter.map(part=>new RegExp(`^${part}$`)))}static matchesFilter(path,filter){if(filter.length>path.length)return!1;let offset=path.length-filter.length;return filter.every((re,i)=>re.test(path[offset+i]))}get isOnlyMode(){return this.onlyMode}get root(){return this.rootDescribe}get describe(){return this.currentDescribe}get test(){return this.currentTest}set test(test){this.currentTest=test}async run(context){try{let time=Date.now();if(emitStatus(4),!this.hasTests)throw new ExecutionError("Your test suite must contain at least one test");await this.root.run(context),emitStatus(3,{duration:Date.now()-time})}catch(e){dispatch(encodeErrorSchema(e,__XJET.runtime.suiteId,__XJET.runtime.runnerId))}}addDescribe(description,describeFn,flags={},describeArgs=[]){let options={skip:!1,only:!1,...flags};if(options.only&&(this.onlyMode=!0),this.filterRegexChain.length>0){let fullPath=[...this.currentDescribe.ancestry,this.currentDescribe.description,description];_SuiteState.matchesFilter(fullPath,this.filterRegexChain)&&(options.only=!0)}let newDescribe=new DescribeModel(description,options);this.currentDescribe.addDescribe(newDescribe);let previousDescribe=this.currentDescribe;this.currentDescribe=newDescribe;try{describeFn.apply({},describeArgs)}finally{this.currentDescribe=previousDescribe}}addTest(test){if(this.hasTests=!0,test.options.only&&(this.onlyMode=!0),this.currentDescribe.addTest(test),this.filterRegexChain.length>0){let fullPath=[...test.ancestry,test.description];_SuiteState.matchesFilter(fullPath,this.filterRegexChain)&&(test.options.only=!0)}}};_init=__decoratorStart(null),_SuiteState=__decorateElement(_init,0,"SuiteState",_SuiteState_decorators,_SuiteState),__runInitializers(_init,1,_SuiteState);var SuiteState=_SuiteState;import{serialize}from"@remotex-labs/xjet-expect";import{parseErrorStack}from"@remotex-labs/xmap/parser.component";function getInvocationLocation(position=2){let stack=parseErrorStack(new Error).stack[position];if(stack?.line&&stack?.column&&stack?.fileName)return{line:stack.line,column:stack.column,source:stack.fileName}}__name(getInvocationLocation,"getInvocationLocation");function getTrimmedStackString(position=2){let err=new Error;return err.stack?err.stack.split(`
2
+ `).slice(position+1).join(`
3
+ `):""}__name(getTrimmedStackString,"getTrimmedStackString");function createLogHandler(type){return function(...args){let parent=inject(SuiteState).test;parent||(parent=inject(SuiteState).describe);let context=[...parent?.ancestry??[],parent?.description].join(","),formattedArgs=args.map(data=>serialize(data).join(`
4
+ `)).join(" "),location=getInvocationLocation();dispatch(encodePacket(1,{level:LogLevel[type],message:formattedArgs,ancestry:context??"",invocation:location}))}}__name(createLogHandler,"createLogHandler");var log=createLogHandler("Info"),info=createLogHandler("Info"),warn=createLogHandler("Warn"),error=createLogHandler("Error"),debug=createLogHandler("Debug");function deepSearchObject(target,element,key,maxDepth=3){let visited=new WeakSet;function search(target2,depth){if(depth>maxDepth||target2==null||typeof target2!="object"&&typeof target2!="function"||visited.has(target2))return null;if(visited.add(target2),key&&key in target2)return{parent:target2,key};for(let[prop,value]of Object.entries(target2)){if(Object.is(value,element))return{parent:target2,key:prop};if(value&&(typeof value=="object"||typeof value=="function")){let found=search(value,depth+1);if(found)return found}}return null}return __name(search,"search"),search(target,0)}__name(deepSearchObject,"deepSearchObject");function getOwnProperty(parent,key){let method=Reflect.get(parent,key),descriptor=Object.getOwnPropertyDescriptor(parent,key);return descriptor?.get&&!descriptor.configurable&&"default"in parent&&Reflect.get(parent.default,key)===method?{parent:parent.default,key}:{parent,key}}__name(getOwnProperty,"getOwnProperty");function mockDescriptorProperty(target,key){let original=Reflect.get(target,key),originalDescriptor=Object.getOwnPropertyDescriptor(target,key)||{},mockInstance=new MockState(()=>original,()=>{Reflect.set(target,key,originalDescriptor.value),Object.defineProperty(target,key,originalDescriptor)},"xJet.spyOn()");return MockState.mocks.add(new WeakRef(mockInstance)),Object.defineProperty(target,key,{get(){return mockInstance.apply(this,[])},set(value){return mockInstance.mockImplementation(()=>value),mockInstance.apply(this,[value])}}),mockInstance}__name(mockDescriptorProperty,"mockDescriptorProperty");function fnImplementation(implementation,restore){return new MockState(implementation,restore,"xJet.fn()")}__name(fnImplementation,"fnImplementation");function mockImplementation(element,implementation){if(!element)throw new ExecutionError("xJet.mock element is not defined");if(typeof element=="function"&&element.xJetMock)return element;let findObject=deepSearchObject(globalThis,element,element?.name);if(!findObject)throw new ExecutionError(`Unable to mock this item: it was not found in any global object.
5
+ If you are trying to mock a Proxy object, please use xJet.spyOn() instead.`);let{parent,key}=getOwnProperty(findObject.parent,findObject.key),method=Reflect.get(parent,key);if(typeof method=="function"&&method.prototype&&!Object.getOwnPropertyDescriptor(method,"prototype")?.writable){let mock2=new MockState((...args)=>new method(...args),()=>{Reflect.set(parent,key,method)});return Reflect.set(parent,key,mock2),MockState.mocks.add(new WeakRef(mock2)),implementation&&mock2.mockImplementation(implementation),mock2}if(typeof method=="function"){let mock2=new MockState(method,()=>{Reflect.set(parent,key,method)});return Reflect.set(parent,key,mock2),MockState.mocks.add(new WeakRef(mock2)),implementation&&mock2.mockImplementation(implementation),mock2}let mock=mockDescriptorProperty(parent,key);return implementation&&mock.mockImplementation(implementation),mock}__name(mockImplementation,"mockImplementation");function isProxyProperty(obj,key){return!(key in obj)&&Reflect.get(obj,key)!==void 0}__name(isProxyProperty,"isProxyProperty");function isMockProxy(value){return value&&typeof value=="object"&&"__isMockProxy__"in value}__name(isMockProxy,"isMockProxy");function createMockProxy(target){let state={mocks:new Map,customGetter:null},handler={get(_target,prop,receiver){return prop==="__isMockProxy__"?!0:prop==="__MockMap__"?state:state.customGetter?state.customGetter(target,prop,receiver):state.mocks.has(prop)?state.mocks.get(prop):Reflect.get(target,prop,receiver)}};return new Proxy({},handler)}__name(createMockProxy,"createMockProxy");function spyOnProxyGet(target,prop){let found=deepSearchObject(globalThis,target);if(!found)throw new Error("xJet.spyOn item is not part of any global object");if(!isMockProxy(target)){let{parent,key}=getOwnProperty(found.parent,found.key),method=Reflect.get(parent,key);Reflect.set(parent,key,createMockProxy(method)),target=Reflect.get(parent,key)}let proxy=target,mockState=new MockState(target[prop],()=>{proxy.__MockMap__?.mocks.delete(prop)},"xJet.spyOn(Proxy#get)");return proxy.__MockMap__?.mocks.set(prop,mockState),mockState}__name(spyOnProxyGet,"spyOnProxyGet");function spyOnImplementation(target,prop){if(target==null||typeof target!="object"&&typeof target!="function")throw new ExecutionError("Target must be an object or function");if(prop===null)throw new ExecutionError("Spied property/method key is required");if(isProxyProperty(target,prop))return spyOnProxyGet(target,prop);let{parent,key}=getOwnProperty(target,prop);if(!(key in parent))throw new ExecutionError(`Property/method '${String(key)}' does not exist on target`);let method=Reflect.get(parent,key);if(!method)throw new Error(`Property '${String(key)}' does not exist in the provided object`);if(method.xJetMock)return method;let descriptor=Object.getOwnPropertyDescriptor(target,key);if(typeof method!="function"||descriptor?.get)return mockDescriptorProperty(target,key);let fn=method,protoDesc=Object.getOwnPropertyDescriptor(fn,"prototype");fn.prototype&&protoDesc&&!protoDesc.writable&&(fn=__name((...args)=>new method(...args),"fn"));let mockState=new MockState(fn,()=>{Reflect.set(target,key,method)},"xJet.spyOn()");return MockState.mocks.add(new WeakRef(mockState)),Reflect.set(target,key,mockState),mockState}__name(spyOnImplementation,"spyOnImplementation");var _TimerService_decorators,_init2;_TimerService_decorators=[Injectable({scope:"singleton"})];var TimerService=class{static{__name(this,"TimerService")}timers=new Map;originalDateNow=Date.now;originalSetTimeout=globalThis.setTimeout;originalSetInterval=globalThis.setInterval;originalClearTimeout=globalThis.clearTimeout;originalClearInterval=globalThis.clearInterval;now=0;nextId=1;useFakeTimers(){let setTimeout=__name((cb,delay=0,...args)=>{let id=this.nextId++;return this.timers.set(id,{id,callback:cb,time:this.now+delay,interval:null,args:args??[]}),id},"setTimeout"),setInterval=__name((cb,interval=0)=>{let id=this.nextId++;return this.timers.set(id,{id,callback:cb,time:this.now+interval,interval,args:[]}),id},"setInterval"),clearTimeout=__name(id=>{this.timers.delete(id)},"clearTimeout"),clearInterval=__name(id=>{this.timers.delete(id)},"clearInterval"),global=globalThis;global.setTimeout=setTimeout,global.setInterval=setInterval,global.clearTimeout=clearTimeout,global.clearInterval=clearInterval}useRealTimers(){globalThis.setTimeout=this.originalSetTimeout,globalThis.clearTimeout=this.originalClearTimeout,globalThis.setInterval=this.originalSetInterval,globalThis.clearInterval=this.originalClearInterval,Date.now=this.originalDateNow}advanceTimersByTime(ms){this.now+=ms,this.runDueTimers()}runAllTimers(){for(;this.timers.size>0;)this.now=Math.min(...Array.from(this.timers.values()).map(t=>t.time)),this.runDueTimers()}runOnlyPendingTimers(){let pendingTimers=new Set(this.timers.keys());for(;pendingTimers.size>0;){let nextTimerTimes=Array.from(this.timers.values()).filter(t=>pendingTimers.has(t.id)).map(t=>t.time);if(nextTimerTimes.length===0)break;this.now=Math.min(...nextTimerTimes),this.runDueTimers(pendingTimers);for(let id of pendingTimers)this.timers.has(id)||pendingTimers.delete(id)}}runDueTimers(limitTimers){let executed=!0;for(;executed;){executed=!1;let timers=Array.from(this.timers.values()).sort((a,b)=>a.time-b.time);for(let timer of timers)if(this.timers.has(timer.id)&&!(limitTimers&&!limitTimers.has(timer.id))&&timer.time<=this.now){if(timer.interval!==null)for(;timer.time<=this.now;)timer.callback(),timer.time+=timer.interval;else timer.callback(),this.timers.delete(timer.id);executed=!0}}}};_init2=__decoratorStart(null),TimerService=__decorateElement(_init2,0,"TimerService",_TimerService_decorators,TimerService),__runInitializers(_init2,1,TimerService);function useFakeTimers(){inject(TimerService).useFakeTimers()}__name(useFakeTimers,"useFakeTimers");function useRealTimers(){inject(TimerService).useRealTimers()}__name(useRealTimers,"useRealTimers");function runAllTimers(){inject(TimerService).runAllTimers()}__name(runAllTimers,"runAllTimers");function runOnlyPendingTimers(){inject(TimerService).runOnlyPendingTimers()}__name(runOnlyPendingTimers,"runOnlyPendingTimers");function advanceTimersByTime(ms=0){inject(TimerService).advanceTimersByTime(ms)}__name(advanceTimersByTime,"advanceTimersByTime");var VARIABLE_PATTERN=/\$([#\w.])+/g;function prettyFormat(value){return typeof value=="string"?value:JSON.stringify(value,null,4)}__name(prettyFormat,"prettyFormat");function getValueByPath(data,path){if(!(!path.length||!data))try{return path.reduce((obj,key)=>{if(obj==null||typeof obj!="object")throw new Error("Path traversal failed");return obj[key]},data)}catch{return}}__name(getValueByPath,"getValueByPath");function resolveVariable(token,data,arrayIndex){if(!token||typeof token!="string"||!token.startsWith("$"))return token;if(token==="$#")return String(arrayIndex);let propertyPath=token.slice(1).split("."),resolvedValue=getValueByPath(data,propertyPath);if(resolvedValue==null)return token;if(typeof resolvedValue=="object")try{return JSON.stringify(resolvedValue,(key,value)=>key&&typeof value=="object"?"[Object]":value)}catch{return String(resolvedValue)}return String(resolvedValue)}__name(resolveVariable,"resolveVariable");function interpolateVariables(template,data,arrayIndex){return template.replace(VARIABLE_PATTERN,variableToken=>resolveVariable(variableToken,data,arrayIndex))}__name(interpolateVariables,"interpolateVariables");function printf(description,params,index){let paramIndex=0;return description.includes("$")&&!description.includes("%%")&&(description=interpolateVariables(description,params[0],index)),description.replace(/%([psdifjo#%])/g,(match,format)=>{if(format==="%")return"%";if(format==="#")return String(index);let value=params[paramIndex++];switch(format){case"p":return prettyFormat(value);case"s":return String(value);case"d":return Number(value).toString();case"i":return Math.floor(Number(value)).toString();case"f":return Number(value).toString();case"j":return JSON.stringify(value);case"o":return Object.prototype.toString.call(value);default:return match}})}__name(printf,"printf");function parseTemplate(templateString,inputData){let headings=templateString[0].split("|").map(h=>h.trim());if(headings.length===0||headings.some(h=>h===""))throw new Error("Template string headings must not be empty and should contain pipe delimiters.");if(inputData.length%headings.length!==0)throw new Error("Not enough arguments supplied for given headings.");return Array.from({length:inputData.length/headings.length},(_,rowIndex)=>headings.reduce((acc,heading,columnIndex)=>(acc[heading]=inputData[rowIndex*headings.length+columnIndex],acc),{}))}__name(parseTemplate,"parseTemplate");function each(executor,...args){if(args.length<2)throw new Error("`.each` must be called with at leas 2 argument or Tagged Template Literal.");let cases=args[0]instanceof Array&&args[0].raw!==void 0?parseTemplate(args.shift(),args):args;return(name,blockFn,timeout)=>{cases.forEach((testCase,index)=>{let parseArgs=Array.isArray(testCase)?testCase:[testCase];executor(printf(name,parseArgs,Number(index)),blockFn,parseArgs,timeout)})}}__name(each,"each");var TimeoutError=class extends Error{static{__name(this,"TimeoutError")}constructor(timeout,at,stack=""){super(`Exceeded timeout of ${timeout} ms at ${at}`),Object.setPrototypeOf(this,new.target.prototype),this.name="xJetTimeoutError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="xJetFailingError",stack&&(this.stack=`${this.name}: ${this.message}
6
+ ${stack}`)}};async function withTimeout(task,delay,at,stack){let timers=inject(TimerService),taskPromise=typeof task=="function"?Promise.resolve(task()):Promise.resolve(task);if(delay===-1||!timers.originalSetTimeout)return taskPromise;let timeoutId,timeoutPromise=new Promise((_,reject)=>{timeoutId=timers.originalSetTimeout?.(()=>reject(new TimeoutError(delay,at,stack)),delay)});try{return await Promise.race([taskPromise,timeoutPromise])}finally{timers.originalClearTimeout?.(timeoutId)}}__name(withTimeout,"withTimeout");var FailingError=class _FailingError extends ExecutionError{static{__name(this,"FailingError")}constructor(stack){super("Failing test passed even though it was supposed to fail. Remove `.failing` to remove error."),Error.captureStackTrace&&Error.captureStackTrace(this,_FailingError),this.name="xJetFailingError",this.stack=`${this.name}: ${this.message}
7
+ ${stack}`}};import{isPromise}from"@remotex-labs/xjet-expect";var TestModel=class{constructor(description,testImplementation,timeoutDuration,testParameters=[],testOptions={}){this.description=description;this.testImplementation=testImplementation;this.timeoutDuration=timeoutDuration;this.testParameters=testParameters;this.testOptions=testOptions}static{__name(this,"TestModel")}ancestry=[];executionLocation="";executionStartTime=0;get options(){return this.testOptions}setExecutionLocation(location){this.executionLocation=location}applyExecutionFlags(skip,only){this.testOptions.skip||=skip,this.testOptions.only||=only}setAncestry(parentTests){this.ancestry.push(...parentTests)}async run(context,runLifecycleHooks,isExclusiveMode=!1){if(inject(SuiteState).test=this,this.executionStartTime=Date.now(),!this.shouldSkipDueToSetupErrors(context)&&!this.determineSkipAction(isExclusiveMode))try{await this.executeTestWithLifecycle(context,runLifecycleHooks),this.validateTestOutcome()}catch(error2){this.notifyTestFailure(error2),globalThis.__XJET?.runtime.bail&&(context.hasError=!0)}finally{inject(SuiteState).test=void 0}}shouldSkipDueToSetupErrors(context){return context.beforeAllErrors&&context.beforeAllErrors.length>0?(this.notifyTestFailure(context.beforeAllErrors),!0):!1}determineSkipAction(isExclusiveMode){return inject(SuiteState).isOnlyMode&&!this.testOptions.only?(this.notifyTestStatus(!0),!0):this.testOptions.skip||this.testOptions.todo?(this.notifyTestStatus(this.testOptions.skip,this.testOptions.todo),!0):isExclusiveMode&&!this.testOptions.only?(this.notifyTestStatus(!0),!0):!1}async executeTestWithLifecycle(context,runLifecycleHooks){await runLifecycleHooks("beforeEach",context),await withTimeout(this.executeTestWithContext(context),this.timeoutDuration,`'${this.timeoutDuration}' test`,this.executionLocation),await runLifecycleHooks("afterEach",context)}validateTestOutcome(){if(this.testOptions.failing)throw new FailingError(this.executionLocation);this.notifyTestAction()}isCallbackStyle(){return this.testImplementation.length===1&&this.testParameters.length===0?!0:this.testImplementation.length===2}getExecutionStrategy(){return isPromise(this.testImplementation)?"ASYNC":this.isCallbackStyle()?"CALLBACK":"SYNC"}async executeTestWithContext(context){switch(this.getExecutionStrategy()){case"ASYNC":case"SYNC":await this.testImplementation.apply(context,this.testParameters);break;case"CALLBACK":await this.executeCallbackStyleTest(context);break}}async executeCallbackStyleTest(context){return new Promise((resolve,reject)=>{let callbackFn=__name(error2=>{error2&&reject(error2),resolve()},"callbackFn"),allParameters=[...this.testParameters];allParameters.push(callbackFn),this.testImplementation.apply(context,allParameters)})}getExecutionDuration(){return this.executionStartTime===0?0:Date.now()-this.executionStartTime}notifyTestStatus(skip=!1,todo=!1){emitStatus(1,{todo,skipped:skip,ancestry:this.ancestry,description:this.description})}notifyTestAction(errors=[]){emitEvent(1,{errors,ancestry:this.ancestry,duration:this.getExecutionDuration(),description:this.description})}notifyTestFailure(error2){this.notifyTestAction(Array.isArray(error2)?error2:[error2])}};var TestDirective=class _TestDirective extends Function{static{__name(this,"TestDirective")}static instance;static ERROR_MESSAGES={SKIP_ONLY:'Cannot use "only" flag on skipped test',ONLY_SKIP:'Cannot use "skip" flag on only test',SKIP_TODO:'Cannot use "todo" flag on skipped test',SKIP_FAILING:'Cannot use "failing" flag on skipped test'};static DEFAULT_TIMEOUT=globalThis.__XJET?.runtime.timeout??5e3;options={};invocationStack="";constructor(){return super(),new Proxy(this,{apply:__name((target,_,args)=>{let[description,block,timeout]=args;this.invocationStack=getTrimmedStackString(2),target.invoke(description,block,[],timeout)},"apply")})}static getInstance(){return _TestDirective.instance||(_TestDirective.instance=new _TestDirective),_TestDirective.instance}get skip(){if(this.options.only)throw new Error(_TestDirective.ERROR_MESSAGES.ONLY_SKIP);return this.options.skip=!0,this}get only(){if(this.options.skip)throw new Error(_TestDirective.ERROR_MESSAGES.SKIP_ONLY);return this.options.only=!0,this}get todo(){if(this.options.skip)throw new Error(_TestDirective.ERROR_MESSAGES.SKIP_TODO);return this.options.todo=!0,this}get failing(){if(this.options.skip)throw new Error(_TestDirective.ERROR_MESSAGES.SKIP_FAILING);return this.options.failing=!0,this}each(...args){return each(this.invoke.bind(this),...args)}invoke(description,block,args=[],timeout){this.validateTestNesting(description),block||(this.options.todo=!0);let test=this.createTest(description,block,args,timeout);this.registerTest(test,this.invocationStack),this.resetFlags()}validateTestNesting(description){let runningTest=inject(SuiteState).test;if(runningTest)throw new Error(`Cannot nest a test inside a test '${description}' in '${runningTest.description}'`)}createTest(description,block,args,timeout){return new TestModel(description,block,timeout??_TestDirective.DEFAULT_TIMEOUT,args,{...this.options})}registerTest(test,location){location&&test.setExecutionLocation(location),inject(SuiteState).addTest(test)}resetFlags(){this.options={}}};var DescribeDirective=class _DescribeDirective extends Function{static{__name(this,"DescribeDirective")}static instance=null;options={};constructor(){return super(),new Proxy(this,{apply(target,thisArg,args){target.invoke(args[0],args[1])}})}static getInstance(){return _DescribeDirective.instance||(_DescribeDirective.instance=new _DescribeDirective),_DescribeDirective.instance}get skip(){if(this.options.only)throw new Error('Cannot use "skip" flag on only test');return this.options.skip=!0,this}get only(){if(this.options.skip)throw new Error('Cannot use "only" flag on skipped test');return this.options.only=!0,this}each(...args){return each(this.invoke.bind(this),...args)}invoke(description,block,args=[]){let suiteState=inject(SuiteState),runningTest=suiteState.test;if(runningTest)throw new Error(`Cannot nest a describe inside a test '${description}' in '${runningTest.description}'`);suiteState.addDescribe(description,block,this.options,args),this.options={}}};import{isPromise as isPromise2}from"@remotex-labs/xjet-expect";var HookModel=class{constructor(hookFunction,timeout){this.hookFunction=hookFunction;this.timeout=timeout}static{__name(this,"HookModel")}location="";setLocation(location){this.location=location}async run(context){return withTimeout(this.executeHook(this.hookFunction,context),this.timeout,"hook while waiting for 'done()' to be called.",this.location)}async executeHook(hook,context){if(isPromise2(hook)&&hook.length>0)throw new Error(`Async hook '${hook.name}' should not use 'done' callback.`);return hook.length>0?this.executeCallbackHook(hook,context):hook.call(context)}executeCallbackHook(hook,context){return new Promise((resolve,reject)=>{hook.call(context,error2=>{error2?reject(error2):resolve()})})}};var DEFAULT_TIMEOUT=globalThis.__XJET?.runtime.timeout??5e3;function createHook(hookType,callback,location,timeout=DEFAULT_TIMEOUT){let hook=new HookModel(callback,timeout);hook.setLocation(location),inject(SuiteState).describe.addHook(hookType,hook)}__name(createHook,"createHook");function afterAllDirective(callback,timeout){createHook("afterAll",callback,getTrimmedStackString(),timeout)}__name(afterAllDirective,"afterAllDirective");function beforeAllDirective(callback,timeout){createHook("beforeAll",callback,getTrimmedStackString(),timeout)}__name(beforeAllDirective,"beforeAllDirective");function afterEachDirective(callback,timeout){createHook("afterEach",callback,getTrimmedStackString(),timeout)}__name(afterEachDirective,"afterEachDirective");function beforeEachDirective(callback,timeout){createHook("beforeEach",callback,getTrimmedStackString(),timeout)}__name(beforeEachDirective,"beforeEachDirective");function clearMocks(method){MockState.mocks.forEach(mock=>{let instance=mock.deref();if(!instance)return MockState.mocks.delete(mock);instance[method]()})}__name(clearMocks,"clearMocks");var setupGlobals=__name(()=>{let globals=globalThis;globals.xJet={fn:fnImplementation,mock:mockImplementation,spyOn:spyOnImplementation,clearAllMocks:__name(()=>clearMocks("mockClear"),"clearAllMocks"),resetAllMocks:__name(()=>clearMocks("mockReset"),"resetAllMocks"),restoreAllMocks:__name(()=>clearMocks("mockRestore"),"restoreAllMocks"),log,info,warn,error,debug,runAllTimers,useFakeTimers,useRealTimers,advanceTimersByTime,runOnlyPendingTimers},globals.expect=xExpect,globals.state=inject(SuiteState),globals.it=TestDirective.getInstance(),globals.test=TestDirective.getInstance(),globals.describe=DescribeDirective.getInstance(),globals.afterAll=afterAllDirective,globals.beforeAll=beforeAllDirective,globals.afterEach=afterEachDirective,globals.beforeEach=beforeEachDirective},"setupGlobals");setupGlobals();
74
8
  //# sourceMappingURL=shared.js.map