diff --git a/client/dist/assets/index-C1XavMtG.js b/client/dist/assets/index-C1XavMtG.js new file mode 100644 index 0000000..bbd8325 --- /dev/null +++ b/client/dist/assets/index-C1XavMtG.js @@ -0,0 +1,73 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))i(a);new MutationObserver(a=>{for(const h of a)if(h.type==="childList")for(const y of h.addedNodes)y.tagName==="LINK"&&y.rel==="modulepreload"&&i(y)}).observe(document,{childList:!0,subtree:!0});function r(a){const h={};return a.integrity&&(h.integrity=a.integrity),a.referrerPolicy&&(h.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?h.credentials="include":a.crossOrigin==="anonymous"?h.credentials="omit":h.credentials="same-origin",h}function i(a){if(a.ep)return;a.ep=!0;const h=r(a);fetch(a.href,h)}})();function Ta(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Aa={exports:{}},Ds={},Pa={exports:{}},J={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var wi=Symbol.for("react.element"),Yu=Symbol.for("react.portal"),Ju=Symbol.for("react.fragment"),Zu=Symbol.for("react.strict_mode"),eh=Symbol.for("react.profiler"),th=Symbol.for("react.provider"),rh=Symbol.for("react.context"),ih=Symbol.for("react.forward_ref"),sh=Symbol.for("react.suspense"),nh=Symbol.for("react.memo"),oh=Symbol.for("react.lazy"),ml=Symbol.iterator;function lh(e){return e===null||typeof e!="object"?null:(e=ml&&e[ml]||e["@@iterator"],typeof e=="function"?e:null)}var Ma={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ba=Object.assign,Oa={};function Dr(e,t,r){this.props=e,this.context=t,this.refs=Oa,this.updater=r||Ma}Dr.prototype.isReactComponent={};Dr.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Dr.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Ia(){}Ia.prototype=Dr.prototype;function Eo(e,t,r){this.props=e,this.context=t,this.refs=Oa,this.updater=r||Ma}var ko=Eo.prototype=new Ia;ko.constructor=Eo;Ba(ko,Dr.prototype);ko.isPureReactComponent=!0;var Sl=Array.isArray,Ha=Object.prototype.hasOwnProperty,bo={current:null},Fa={key:!0,ref:!0,__self:!0,__source:!0};function Na(e,t,r){var i,a={},h=null,y=null;if(t!=null)for(i in t.ref!==void 0&&(y=t.ref),t.key!==void 0&&(h=""+t.key),t)Ha.call(t,i)&&!Fa.hasOwnProperty(i)&&(a[i]=t[i]);var n=arguments.length-2;if(n===1)a.children=r;else if(1>>1,F=x[M];if(0>>1;M<$;){var G=2*(M+1)-1,X=x[G],ee=G+1,L=x[ee];if(0>a(X,T))eea(L,X)?(x[M]=L,x[ee]=T,M=ee):(x[M]=X,x[G]=T,M=G);else if(eea(L,T))x[M]=L,x[ee]=T,M=ee;else break e}}return D}function a(x,D){var T=x.sortIndex-D.sortIndex;return T!==0?T:x.id-D.id}if(typeof performance=="object"&&typeof performance.now=="function"){var h=performance;e.unstable_now=function(){return h.now()}}else{var y=Date,n=y.now();e.unstable_now=function(){return y.now()-n}}var u=[],f=[],S=1,d=null,p=3,C=!1,w=!1,m=!1,c=typeof setTimeout=="function"?setTimeout:null,o=typeof clearTimeout=="function"?clearTimeout:null,s=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function l(x){for(var D=r(f);D!==null;){if(D.callback===null)i(f);else if(D.startTime<=x)i(f),D.sortIndex=D.expirationTime,t(u,D);else break;D=r(f)}}function _(x){if(m=!1,l(x),!w)if(r(u)!==null)w=!0,U(g);else{var D=r(f);D!==null&&j(_,D.startTime-x)}}function g(x,D){w=!1,m&&(m=!1,o(v),v=-1),C=!0;var T=p;try{for(l(D),d=r(u);d!==null&&(!(d.expirationTime>D)||x&&!P());){var M=d.callback;if(typeof M=="function"){d.callback=null,p=d.priorityLevel;var F=M(d.expirationTime<=D);D=e.unstable_now(),typeof F=="function"?d.callback=F:d===r(u)&&i(u),l(D)}else i(u);d=r(u)}if(d!==null)var $=!0;else{var G=r(f);G!==null&&j(_,G.startTime-D),$=!1}return $}finally{d=null,p=T,C=!1}}var E=!1,b=null,v=-1,k=5,R=-1;function P(){return!(e.unstable_now()-Rx||125M?(x.sortIndex=T,t(f,x),r(u)===null&&x===r(f)&&(m?(o(v),v=-1):m=!0,j(_,T-M))):(x.sortIndex=F,t(u,x),w||C||(w=!0,U(g))),x},e.unstable_shouldYield=P,e.unstable_wrapCallback=function(x){var D=p;return function(){var T=p;p=D;try{return x.apply(this,arguments)}finally{p=T}}}})(Ka);$a.exports=Ka;var mh=$a.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Sh=dt,Ne=mh;function W(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Dn=Object.prototype.hasOwnProperty,yh=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Cl={},wl={};function Ch(e){return Dn.call(wl,e)?!0:Dn.call(Cl,e)?!1:yh.test(e)?wl[e]=!0:(Cl[e]=!0,!1)}function wh(e,t,r,i){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return i?!1:r!==null?!r.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Eh(e,t,r,i){if(t===null||typeof t>"u"||wh(e,t,r,i))return!0;if(i)return!1;if(r!==null)switch(r.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function De(e,t,r,i,a,h,y){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=i,this.attributeNamespace=a,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=h,this.removeEmptyString=y}var Ce={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Ce[e]=new De(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Ce[t]=new De(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Ce[e]=new De(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Ce[e]=new De(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Ce[e]=new De(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Ce[e]=new De(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Ce[e]=new De(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Ce[e]=new De(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Ce[e]=new De(e,5,!1,e.toLowerCase(),null,!1,!1)});var Lo=/[\-:]([a-z])/g;function Ro(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Lo,Ro);Ce[t]=new De(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Lo,Ro);Ce[t]=new De(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Lo,Ro);Ce[t]=new De(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Ce[e]=new De(e,1,!1,e.toLowerCase(),null,!1,!1)});Ce.xlinkHref=new De("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Ce[e]=new De(e,1,!1,e.toLowerCase(),null,!0,!0)});function Do(e,t,r,i){var a=Ce.hasOwnProperty(t)?Ce[t]:null;(a!==null?a.type!==0:i||!(2n||a[y]!==h[n]){var u=` +`+a[y].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=y&&0<=n);break}}}finally{tn=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?$r(e):""}function kh(e){switch(e.tag){case 5:return $r(e.type);case 16:return $r("Lazy");case 13:return $r("Suspense");case 19:return $r("SuspenseList");case 0:case 2:case 15:return e=rn(e.type,!1),e;case 11:return e=rn(e.type.render,!1),e;case 1:return e=rn(e.type,!0),e;default:return""}}function Mn(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case sr:return"Fragment";case ir:return"Portal";case Tn:return"Profiler";case To:return"StrictMode";case An:return"Suspense";case Pn:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Xa:return(e.displayName||"Context")+".Consumer";case qa:return(e._context.displayName||"Context")+".Provider";case Ao:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Po:return t=e.displayName||null,t!==null?t:Mn(e.type)||"Memo";case wt:t=e._payload,e=e._init;try{return Mn(e(t))}catch{}}return null}function bh(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Mn(t);case 8:return t===To?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function It(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Qa(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function xh(e){var t=Qa(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),i=""+e[t];if(!e.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var a=r.get,h=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return a.call(this)},set:function(y){i=""+y,h.call(this,y)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return i},setValue:function(y){i=""+y},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Ti(e){e._valueTracker||(e._valueTracker=xh(e))}function Ya(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var r=t.getValue(),i="";return e&&(i=Qa(e)?e.checked?"true":"false":e.value),e=i,e!==r?(t.setValue(e),!0):!1}function ns(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Bn(e,t){var r=t.checked;return ue({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function kl(e,t){var r=t.defaultValue==null?"":t.defaultValue,i=t.checked!=null?t.checked:t.defaultChecked;r=It(t.value!=null?t.value:r),e._wrapperState={initialChecked:i,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Ja(e,t){t=t.checked,t!=null&&Do(e,"checked",t,!1)}function On(e,t){Ja(e,t);var r=It(t.value),i=t.type;if(r!=null)i==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(i==="submit"||i==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?In(e,t.type,r):t.hasOwnProperty("defaultValue")&&In(e,t.type,It(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function bl(e,t,r){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var i=t.type;if(!(i!=="submit"&&i!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,r||t===e.value||(e.value=t),e.defaultValue=t}r=e.name,r!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,r!==""&&(e.name=r)}function In(e,t,r){(t!=="number"||ns(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var Kr=Array.isArray;function pr(e,t,r,i){if(e=e.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=Ai.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function si(e,t){if(t){var r=e.firstChild;if(r&&r===e.lastChild&&r.nodeType===3){r.nodeValue=t;return}}e.textContent=t}var Xr={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Lh=["Webkit","ms","Moz","O"];Object.keys(Xr).forEach(function(e){Lh.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Xr[t]=Xr[e]})});function rc(e,t,r){return t==null||typeof t=="boolean"||t===""?"":r||typeof t!="number"||t===0||Xr.hasOwnProperty(e)&&Xr[e]?(""+t).trim():t+"px"}function ic(e,t){e=e.style;for(var r in t)if(t.hasOwnProperty(r)){var i=r.indexOf("--")===0,a=rc(r,t[r],i);r==="float"&&(r="cssFloat"),i?e.setProperty(r,a):e[r]=a}}var Rh=ue({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Nn(e,t){if(t){if(Rh[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(W(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(W(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(W(61))}if(t.style!=null&&typeof t.style!="object")throw Error(W(62))}}function zn(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var jn=null;function Mo(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Un=null,vr=null,gr=null;function Rl(e){if(e=bi(e)){if(typeof Un!="function")throw Error(W(280));var t=e.stateNode;t&&(t=Bs(t),Un(e.stateNode,e.type,t))}}function sc(e){vr?gr?gr.push(e):gr=[e]:vr=e}function nc(){if(vr){var e=vr,t=gr;if(gr=vr=null,Rl(e),t)for(e=0;e>>=0,e===0?32:31-(Nh(e)/zh|0)|0}var Pi=64,Mi=4194304;function Vr(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function cs(e,t){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,h=e.pingedLanes,y=r&268435455;if(y!==0){var n=y&~a;n!==0?i=Vr(n):(h&=y,h!==0&&(i=Vr(h)))}else y=r&~a,y!==0?i=Vr(y):h!==0&&(i=Vr(h));if(i===0)return 0;if(t!==0&&t!==i&&!(t&a)&&(a=i&-i,h=t&-t,a>=h||a===16&&(h&4194240)!==0))return t;if(i&4&&(i|=r&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=i;0r;r++)t.push(e);return t}function Ei(e,t,r){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ze(t),e[t]=r}function $h(e,t){var r=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var i=e.eventTimes;for(e=e.expirationTimes;0=Qr),Hl=" ",Fl=!1;function bc(e,t){switch(e){case"keyup":return md.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function xc(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var nr=!1;function yd(e,t){switch(e){case"compositionend":return xc(t);case"keypress":return t.which!==32?null:(Fl=!0,Hl);case"textInput":return e=t.data,e===Hl&&Fl?null:e;default:return null}}function Cd(e,t){if(nr)return e==="compositionend"||!jo&&bc(e,t)?(e=Ec(),Gi=Fo=xt=null,nr=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:r,offset:t-e};e=i}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=Ul(r)}}function Tc(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Tc(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Ac(){for(var e=window,t=ns();t instanceof e.HTMLIFrameElement;){try{var r=typeof t.contentWindow.location.href=="string"}catch{r=!1}if(r)e=t.contentWindow;else break;t=ns(e.document)}return t}function Uo(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Td(e){var t=Ac(),r=e.focusedElem,i=e.selectionRange;if(t!==r&&r&&r.ownerDocument&&Tc(r.ownerDocument.documentElement,r)){if(i!==null&&Uo(r)){if(t=i.start,e=i.end,e===void 0&&(e=t),"selectionStart"in r)r.selectionStart=t,r.selectionEnd=Math.min(e,r.value.length);else if(e=(t=r.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var a=r.textContent.length,h=Math.min(i.start,a);i=i.end===void 0?h:Math.min(i.end,a),!e.extend&&h>i&&(a=i,i=h,h=a),a=Wl(r,h);var y=Wl(r,i);a&&y&&(e.rangeCount!==1||e.anchorNode!==a.node||e.anchorOffset!==a.offset||e.focusNode!==y.node||e.focusOffset!==y.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),e.removeAllRanges(),h>i?(e.addRange(t),e.extend(y.node,y.offset)):(t.setEnd(y.node,y.offset),e.addRange(t)))}}for(t=[],e=r;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r=document.documentMode,or=null,Xn=null,Jr=null,Gn=!1;function $l(e,t,r){var i=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;Gn||or==null||or!==ns(i)||(i=or,"selectionStart"in i&&Uo(i)?i={start:i.selectionStart,end:i.selectionEnd}:(i=(i.ownerDocument&&i.ownerDocument.defaultView||window).getSelection(),i={anchorNode:i.anchorNode,anchorOffset:i.anchorOffset,focusNode:i.focusNode,focusOffset:i.focusOffset}),Jr&&ui(Jr,i)||(Jr=i,i=ds(Xn,"onSelect"),0cr||(e.current=to[cr],to[cr]=null,cr--)}function ie(e,t){cr++,to[cr]=e.current,e.current=t}var Ht={},be=Nt(Ht),Me=Nt(!1),Xt=Ht;function wr(e,t){var r=e.type.contextTypes;if(!r)return Ht;var i=e.stateNode;if(i&&i.__reactInternalMemoizedUnmaskedChildContext===t)return i.__reactInternalMemoizedMaskedChildContext;var a={},h;for(h in r)a[h]=t[h];return i&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a),a}function Be(e){return e=e.childContextTypes,e!=null}function _s(){ne(Me),ne(be)}function Yl(e,t,r){if(be.current!==Ht)throw Error(W(168));ie(be,t),ie(Me,r)}function zc(e,t,r){var i=e.stateNode;if(t=t.childContextTypes,typeof i.getChildContext!="function")return r;i=i.getChildContext();for(var a in i)if(!(a in t))throw Error(W(108,bh(e)||"Unknown",a));return ue({},r,i)}function ps(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Ht,Xt=be.current,ie(be,e),ie(Me,Me.current),!0}function Jl(e,t,r){var i=e.stateNode;if(!i)throw Error(W(169));r?(e=zc(e,t,Xt),i.__reactInternalMemoizedMergedChildContext=e,ne(Me),ne(be),ie(be,e)):ne(Me),ie(Me,r)}var ct=null,Os=!1,gn=!1;function jc(e){ct===null?ct=[e]:ct.push(e)}function Ud(e){Os=!0,jc(e)}function zt(){if(!gn&&ct!==null){gn=!0;var e=0,t=re;try{var r=ct;for(re=1;e>=y,a-=y,ut=1<<32-Ze(t)+a|r<v?(k=b,b=null):k=b.sibling;var R=p(o,b,l[v],_);if(R===null){b===null&&(b=k);break}e&&b&&R.alternate===null&&t(o,b),s=h(R,s,v),E===null?g=R:E.sibling=R,E=R,b=k}if(v===l.length)return r(o,b),oe&&jt(o,v),g;if(b===null){for(;vv?(k=b,b=null):k=b.sibling;var P=p(o,b,R.value,_);if(P===null){b===null&&(b=k);break}e&&b&&P.alternate===null&&t(o,b),s=h(P,s,v),E===null?g=P:E.sibling=P,E=P,b=k}if(R.done)return r(o,b),oe&&jt(o,v),g;if(b===null){for(;!R.done;v++,R=l.next())R=d(o,R.value,_),R!==null&&(s=h(R,s,v),E===null?g=R:E.sibling=R,E=R);return oe&&jt(o,v),g}for(b=i(o,b);!R.done;v++,R=l.next())R=C(b,o,v,R.value,_),R!==null&&(e&&R.alternate!==null&&b.delete(R.key===null?v:R.key),s=h(R,s,v),E===null?g=R:E.sibling=R,E=R);return e&&b.forEach(function(A){return t(o,A)}),oe&&jt(o,v),g}function c(o,s,l,_){if(typeof l=="object"&&l!==null&&l.type===sr&&l.key===null&&(l=l.props.children),typeof l=="object"&&l!==null){switch(l.$$typeof){case Di:e:{for(var g=l.key,E=s;E!==null;){if(E.key===g){if(g=l.type,g===sr){if(E.tag===7){r(o,E.sibling),s=a(E,l.props.children),s.return=o,o=s;break e}}else if(E.elementType===g||typeof g=="object"&&g!==null&&g.$$typeof===wt&&ta(g)===E.type){r(o,E.sibling),s=a(E,l.props),s.ref=jr(o,E,l),s.return=o,o=s;break e}r(o,E);break}else t(o,E);E=E.sibling}l.type===sr?(s=qt(l.props.children,o.mode,_,l.key),s.return=o,o=s):(_=is(l.type,l.key,l.props,null,o.mode,_),_.ref=jr(o,s,l),_.return=o,o=_)}return y(o);case ir:e:{for(E=l.key;s!==null;){if(s.key===E)if(s.tag===4&&s.stateNode.containerInfo===l.containerInfo&&s.stateNode.implementation===l.implementation){r(o,s.sibling),s=a(s,l.children||[]),s.return=o,o=s;break e}else{r(o,s);break}else t(o,s);s=s.sibling}s=bn(l,o.mode,_),s.return=o,o=s}return y(o);case wt:return E=l._init,c(o,s,E(l._payload),_)}if(Kr(l))return w(o,s,l,_);if(Ir(l))return m(o,s,l,_);zi(o,l)}return typeof l=="string"&&l!==""||typeof l=="number"?(l=""+l,s!==null&&s.tag===6?(r(o,s.sibling),s=a(s,l),s.return=o,o=s):(r(o,s),s=kn(l,o.mode,_),s.return=o,o=s),y(o)):r(o,s)}return c}var kr=Kc(!0),Vc=Kc(!1),ms=Nt(null),Ss=null,dr=null,Vo=null;function qo(){Vo=dr=Ss=null}function Xo(e){var t=ms.current;ne(ms),e._currentValue=t}function so(e,t,r){for(;e!==null;){var i=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,i!==null&&(i.childLanes|=t)):i!==null&&(i.childLanes&t)!==t&&(i.childLanes|=t),e===r)break;e=e.return}}function Sr(e,t){Ss=e,Vo=dr=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Pe=!0),e.firstContext=null)}function qe(e){var t=e._currentValue;if(Vo!==e)if(e={context:e,memoizedValue:t,next:null},dr===null){if(Ss===null)throw Error(W(308));dr=e,Ss.dependencies={lanes:0,firstContext:e}}else dr=dr.next=e;return t}var $t=null;function Go(e){$t===null?$t=[e]:$t.push(e)}function qc(e,t,r,i){var a=t.interleaved;return a===null?(r.next=r,Go(t)):(r.next=a.next,a.next=r),t.interleaved=r,vt(e,i)}function vt(e,t){e.lanes|=t;var r=e.alternate;for(r!==null&&(r.lanes|=t),r=e,e=e.return;e!==null;)e.childLanes|=t,r=e.alternate,r!==null&&(r.childLanes|=t),r=e,e=e.return;return r.tag===3?r.stateNode:null}var Et=!1;function Qo(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Xc(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function ft(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Pt(e,t,r){var i=e.updateQueue;if(i===null)return null;if(i=i.shared,Z&2){var a=i.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),i.pending=t,vt(e,r)}return a=i.interleaved,a===null?(t.next=t,Go(i)):(t.next=a.next,a.next=t),i.interleaved=t,vt(e,r)}function Yi(e,t,r){if(t=t.updateQueue,t!==null&&(t=t.shared,(r&4194240)!==0)){var i=t.lanes;i&=e.pendingLanes,r|=i,t.lanes=r,Oo(e,r)}}function ra(e,t){var r=e.updateQueue,i=e.alternate;if(i!==null&&(i=i.updateQueue,r===i)){var a=null,h=null;if(r=r.firstBaseUpdate,r!==null){do{var y={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};h===null?a=h=y:h=h.next=y,r=r.next}while(r!==null);h===null?a=h=t:h=h.next=t}else a=h=t;r={baseState:i.baseState,firstBaseUpdate:a,lastBaseUpdate:h,shared:i.shared,effects:i.effects},e.updateQueue=r;return}e=r.lastBaseUpdate,e===null?r.firstBaseUpdate=t:e.next=t,r.lastBaseUpdate=t}function ys(e,t,r,i){var a=e.updateQueue;Et=!1;var h=a.firstBaseUpdate,y=a.lastBaseUpdate,n=a.shared.pending;if(n!==null){a.shared.pending=null;var u=n,f=u.next;u.next=null,y===null?h=f:y.next=f,y=u;var S=e.alternate;S!==null&&(S=S.updateQueue,n=S.lastBaseUpdate,n!==y&&(n===null?S.firstBaseUpdate=f:n.next=f,S.lastBaseUpdate=u))}if(h!==null){var d=a.baseState;y=0,S=f=u=null,n=h;do{var p=n.lane,C=n.eventTime;if((i&p)===p){S!==null&&(S=S.next={eventTime:C,lane:0,tag:n.tag,payload:n.payload,callback:n.callback,next:null});e:{var w=e,m=n;switch(p=t,C=r,m.tag){case 1:if(w=m.payload,typeof w=="function"){d=w.call(C,d,p);break e}d=w;break e;case 3:w.flags=w.flags&-65537|128;case 0:if(w=m.payload,p=typeof w=="function"?w.call(C,d,p):w,p==null)break e;d=ue({},d,p);break e;case 2:Et=!0}}n.callback!==null&&n.lane!==0&&(e.flags|=64,p=a.effects,p===null?a.effects=[n]:p.push(n))}else C={eventTime:C,lane:p,tag:n.tag,payload:n.payload,callback:n.callback,next:null},S===null?(f=S=C,u=d):S=S.next=C,y|=p;if(n=n.next,n===null){if(n=a.shared.pending,n===null)break;p=n,n=p.next,p.next=null,a.lastBaseUpdate=p,a.shared.pending=null}}while(!0);if(S===null&&(u=d),a.baseState=u,a.firstBaseUpdate=f,a.lastBaseUpdate=S,t=a.shared.interleaved,t!==null){a=t;do y|=a.lane,a=a.next;while(a!==t)}else h===null&&(a.shared.lanes=0);Yt|=y,e.lanes=y,e.memoizedState=d}}function ia(e,t,r){if(e=t.effects,t.effects=null,e!==null)for(t=0;tr?r:4,e(!0);var i=Sn.transition;Sn.transition={};try{e(!1),t()}finally{re=r,Sn.transition=i}}function hu(){return Xe().memoizedState}function Vd(e,t,r){var i=Bt(e);if(r={lane:i,action:r,hasEagerState:!1,eagerState:null,next:null},du(e))fu(t,r);else if(r=qc(e,t,r,i),r!==null){var a=Le();et(r,e,i,a),_u(r,t,i)}}function qd(e,t,r){var i=Bt(e),a={lane:i,action:r,hasEagerState:!1,eagerState:null,next:null};if(du(e))fu(t,a);else{var h=e.alternate;if(e.lanes===0&&(h===null||h.lanes===0)&&(h=t.lastRenderedReducer,h!==null))try{var y=t.lastRenderedState,n=h(y,r);if(a.hasEagerState=!0,a.eagerState=n,tt(n,y)){var u=t.interleaved;u===null?(a.next=a,Go(t)):(a.next=u.next,u.next=a),t.interleaved=a;return}}catch{}finally{}r=qc(e,t,a,i),r!==null&&(a=Le(),et(r,e,i,a),_u(r,t,i))}}function du(e){var t=e.alternate;return e===ce||t!==null&&t===ce}function fu(e,t){Zr=ws=!0;var r=e.pending;r===null?t.next=t:(t.next=r.next,r.next=t),e.pending=t}function _u(e,t,r){if(r&4194240){var i=t.lanes;i&=e.pendingLanes,r|=i,t.lanes=r,Oo(e,r)}}var Es={readContext:qe,useCallback:we,useContext:we,useEffect:we,useImperativeHandle:we,useInsertionEffect:we,useLayoutEffect:we,useMemo:we,useReducer:we,useRef:we,useState:we,useDebugValue:we,useDeferredValue:we,useTransition:we,useMutableSource:we,useSyncExternalStore:we,useId:we,unstable_isNewReconciler:!1},Xd={readContext:qe,useCallback:function(e,t){return st().memoizedState=[e,t===void 0?null:t],e},useContext:qe,useEffect:na,useImperativeHandle:function(e,t,r){return r=r!=null?r.concat([e]):null,Zi(4194308,4,ou.bind(null,t,e),r)},useLayoutEffect:function(e,t){return Zi(4194308,4,e,t)},useInsertionEffect:function(e,t){return Zi(4,2,e,t)},useMemo:function(e,t){var r=st();return t=t===void 0?null:t,e=e(),r.memoizedState=[e,t],e},useReducer:function(e,t,r){var i=st();return t=r!==void 0?r(t):t,i.memoizedState=i.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},i.queue=e,e=e.dispatch=Vd.bind(null,ce,e),[i.memoizedState,e]},useRef:function(e){var t=st();return e={current:e},t.memoizedState=e},useState:sa,useDebugValue:sl,useDeferredValue:function(e){return st().memoizedState=e},useTransition:function(){var e=sa(!1),t=e[0];return e=Kd.bind(null,e[1]),st().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,r){var i=ce,a=st();if(oe){if(r===void 0)throw Error(W(407));r=r()}else{if(r=t(),ge===null)throw Error(W(349));Qt&30||Jc(i,t,r)}a.memoizedState=r;var h={value:r,getSnapshot:t};return a.queue=h,na(eu.bind(null,i,h,e),[e]),i.flags|=2048,mi(9,Zc.bind(null,i,h,r,t),void 0,null),r},useId:function(){var e=st(),t=ge.identifierPrefix;if(oe){var r=ht,i=ut;r=(i&~(1<<32-Ze(i)-1)).toString(32)+r,t=":"+t+"R"+r,r=vi++,0<\/script>",e=e.removeChild(e.firstChild)):typeof i.is=="string"?e=y.createElement(r,{is:i.is}):(e=y.createElement(r),r==="select"&&(y=e,i.multiple?y.multiple=!0:i.size&&(y.size=i.size))):e=y.createElementNS(e,r),e[nt]=t,e[fi]=i,ku(e,t,!1,!1),t.stateNode=e;e:{switch(y=zn(r,i),r){case"dialog":se("cancel",e),se("close",e),a=i;break;case"iframe":case"object":case"embed":se("load",e),a=i;break;case"video":case"audio":for(a=0;aLr&&(t.flags|=128,i=!0,Ur(h,!1),t.lanes=4194304)}else{if(!i)if(e=Cs(y),e!==null){if(t.flags|=128,i=!0,r=e.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),Ur(h,!0),h.tail===null&&h.tailMode==="hidden"&&!y.alternate&&!oe)return Ee(t),null}else 2*de()-h.renderingStartTime>Lr&&r!==1073741824&&(t.flags|=128,i=!0,Ur(h,!1),t.lanes=4194304);h.isBackwards?(y.sibling=t.child,t.child=y):(r=h.last,r!==null?r.sibling=y:t.child=y,h.last=y)}return h.tail!==null?(t=h.tail,h.rendering=t,h.tail=t.sibling,h.renderingStartTime=de(),t.sibling=null,r=ae.current,ie(ae,i?r&1|2:r&1),t):(Ee(t),null);case 22:case 23:return ul(),i=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==i&&(t.flags|=8192),i&&t.mode&1?Ie&1073741824&&(Ee(t),t.subtreeFlags&6&&(t.flags|=8192)):Ee(t),null;case 24:return null;case 25:return null}throw Error(W(156,t.tag))}function rf(e,t){switch($o(t),t.tag){case 1:return Be(t.type)&&_s(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return br(),ne(Me),ne(be),Zo(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Jo(t),null;case 13:if(ne(ae),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(W(340));Er()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ne(ae),null;case 4:return br(),null;case 10:return Xo(t.type._context),null;case 22:case 23:return ul(),null;case 24:return null;default:return null}}var Ui=!1,ke=!1,sf=typeof WeakSet=="function"?WeakSet:Set,q=null;function fr(e,t){var r=e.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(i){he(e,t,i)}else r.current=null}function _o(e,t,r){try{r()}catch(i){he(e,t,i)}}var va=!1;function nf(e,t){if(Qn=us,e=Ac(),Uo(e)){if("selectionStart"in e)var r={start:e.selectionStart,end:e.selectionEnd};else e:{r=(r=e.ownerDocument)&&r.defaultView||window;var i=r.getSelection&&r.getSelection();if(i&&i.rangeCount!==0){r=i.anchorNode;var a=i.anchorOffset,h=i.focusNode;i=i.focusOffset;try{r.nodeType,h.nodeType}catch{r=null;break e}var y=0,n=-1,u=-1,f=0,S=0,d=e,p=null;t:for(;;){for(var C;d!==r||a!==0&&d.nodeType!==3||(n=y+a),d!==h||i!==0&&d.nodeType!==3||(u=y+i),d.nodeType===3&&(y+=d.nodeValue.length),(C=d.firstChild)!==null;)p=d,d=C;for(;;){if(d===e)break t;if(p===r&&++f===a&&(n=y),p===h&&++S===i&&(u=y),(C=d.nextSibling)!==null)break;d=p,p=d.parentNode}d=C}r=n===-1||u===-1?null:{start:n,end:u}}else r=null}r=r||{start:0,end:0}}else r=null;for(Yn={focusedElem:e,selectionRange:r},us=!1,q=t;q!==null;)if(t=q,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,q=e;else for(;q!==null;){t=q;try{var w=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(w!==null){var m=w.memoizedProps,c=w.memoizedState,o=t.stateNode,s=o.getSnapshotBeforeUpdate(t.elementType===t.type?m:Qe(t.type,m),c);o.__reactInternalSnapshotBeforeUpdate=s}break;case 3:var l=t.stateNode.containerInfo;l.nodeType===1?l.textContent="":l.nodeType===9&&l.documentElement&&l.removeChild(l.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(W(163))}}catch(_){he(t,t.return,_)}if(e=t.sibling,e!==null){e.return=t.return,q=e;break}q=t.return}return w=va,va=!1,w}function ei(e,t,r){var i=t.updateQueue;if(i=i!==null?i.lastEffect:null,i!==null){var a=i=i.next;do{if((a.tag&e)===e){var h=a.destroy;a.destroy=void 0,h!==void 0&&_o(t,r,h)}a=a.next}while(a!==i)}}function Fs(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var r=t=t.next;do{if((r.tag&e)===e){var i=r.create;r.destroy=i()}r=r.next}while(r!==t)}}function po(e){var t=e.ref;if(t!==null){var r=e.stateNode;switch(e.tag){case 5:e=r;break;default:e=r}typeof t=="function"?t(e):t.current=e}}function Lu(e){var t=e.alternate;t!==null&&(e.alternate=null,Lu(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[nt],delete t[fi],delete t[eo],delete t[zd],delete t[jd])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Ru(e){return e.tag===5||e.tag===3||e.tag===4}function ga(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Ru(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function vo(e,t,r){var i=e.tag;if(i===5||i===6)e=e.stateNode,t?r.nodeType===8?r.parentNode.insertBefore(e,t):r.insertBefore(e,t):(r.nodeType===8?(t=r.parentNode,t.insertBefore(e,r)):(t=r,t.appendChild(e)),r=r._reactRootContainer,r!=null||t.onclick!==null||(t.onclick=fs));else if(i!==4&&(e=e.child,e!==null))for(vo(e,t,r),e=e.sibling;e!==null;)vo(e,t,r),e=e.sibling}function go(e,t,r){var i=e.tag;if(i===5||i===6)e=e.stateNode,t?r.insertBefore(e,t):r.appendChild(e);else if(i!==4&&(e=e.child,e!==null))for(go(e,t,r),e=e.sibling;e!==null;)go(e,t,r),e=e.sibling}var Se=null,Ye=!1;function Ct(e,t,r){for(r=r.child;r!==null;)Du(e,t,r),r=r.sibling}function Du(e,t,r){if(ot&&typeof ot.onCommitFiberUnmount=="function")try{ot.onCommitFiberUnmount(Ts,r)}catch{}switch(r.tag){case 5:ke||fr(r,t);case 6:var i=Se,a=Ye;Se=null,Ct(e,t,r),Se=i,Ye=a,Se!==null&&(Ye?(e=Se,r=r.stateNode,e.nodeType===8?e.parentNode.removeChild(r):e.removeChild(r)):Se.removeChild(r.stateNode));break;case 18:Se!==null&&(Ye?(e=Se,r=r.stateNode,e.nodeType===8?vn(e.parentNode,r):e.nodeType===1&&vn(e,r),ai(e)):vn(Se,r.stateNode));break;case 4:i=Se,a=Ye,Se=r.stateNode.containerInfo,Ye=!0,Ct(e,t,r),Se=i,Ye=a;break;case 0:case 11:case 14:case 15:if(!ke&&(i=r.updateQueue,i!==null&&(i=i.lastEffect,i!==null))){a=i=i.next;do{var h=a,y=h.destroy;h=h.tag,y!==void 0&&(h&2||h&4)&&_o(r,t,y),a=a.next}while(a!==i)}Ct(e,t,r);break;case 1:if(!ke&&(fr(r,t),i=r.stateNode,typeof i.componentWillUnmount=="function"))try{i.props=r.memoizedProps,i.state=r.memoizedState,i.componentWillUnmount()}catch(n){he(r,t,n)}Ct(e,t,r);break;case 21:Ct(e,t,r);break;case 22:r.mode&1?(ke=(i=ke)||r.memoizedState!==null,Ct(e,t,r),ke=i):Ct(e,t,r);break;default:Ct(e,t,r)}}function ma(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var r=e.stateNode;r===null&&(r=e.stateNode=new sf),t.forEach(function(i){var a=_f.bind(null,e,i);r.has(i)||(r.add(i),i.then(a,a))})}}function Ge(e,t){var r=t.deletions;if(r!==null)for(var i=0;ia&&(a=y),i&=~h}if(i=a,i=de()-i,i=(120>i?120:480>i?480:1080>i?1080:1920>i?1920:3e3>i?3e3:4320>i?4320:1960*lf(i/1960))-i,10e?16:e,Lt===null)var i=!1;else{if(e=Lt,Lt=null,xs=0,Z&6)throw Error(W(331));var a=Z;for(Z|=4,q=e.current;q!==null;){var h=q,y=h.child;if(q.flags&16){var n=h.deletions;if(n!==null){for(var u=0;ude()-al?Vt(e,0):ll|=r),Oe(e,t)}function Hu(e,t){t===0&&(e.mode&1?(t=Mi,Mi<<=1,!(Mi&130023424)&&(Mi=4194304)):t=1);var r=Le();e=vt(e,t),e!==null&&(Ei(e,t,r),Oe(e,r))}function ff(e){var t=e.memoizedState,r=0;t!==null&&(r=t.retryLane),Hu(e,r)}function _f(e,t){var r=0;switch(e.tag){case 13:var i=e.stateNode,a=e.memoizedState;a!==null&&(r=a.retryLane);break;case 19:i=e.stateNode;break;default:throw Error(W(314))}i!==null&&i.delete(t),Hu(e,r)}var Fu;Fu=function(e,t,r){if(e!==null)if(e.memoizedProps!==t.pendingProps||Me.current)Pe=!0;else{if(!(e.lanes&r)&&!(t.flags&128))return Pe=!1,ef(e,t,r);Pe=!!(e.flags&131072)}else Pe=!1,oe&&t.flags&1048576&&Uc(t,gs,t.index);switch(t.lanes=0,t.tag){case 2:var i=t.type;es(e,t),e=t.pendingProps;var a=wr(t,be.current);Sr(t,r),a=tl(null,t,i,e,a,r);var h=rl();return t.flags|=1,typeof a=="object"&&a!==null&&typeof a.render=="function"&&a.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Be(i)?(h=!0,ps(t)):h=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,Qo(t),a.updater=Hs,t.stateNode=a,a._reactInternals=t,oo(t,i,e,r),t=co(null,t,i,!0,h,r)):(t.tag=0,oe&&h&&Wo(t),xe(null,t,a,r),t=t.child),t;case 16:i=t.elementType;e:{switch(es(e,t),e=t.pendingProps,a=i._init,i=a(i._payload),t.type=i,a=t.tag=vf(i),e=Qe(i,e),a){case 0:t=ao(null,t,i,e,r);break e;case 1:t=fa(null,t,i,e,r);break e;case 11:t=ha(null,t,i,e,r);break e;case 14:t=da(null,t,i,Qe(i.type,e),r);break e}throw Error(W(306,i,""))}return t;case 0:return i=t.type,a=t.pendingProps,a=t.elementType===i?a:Qe(i,a),ao(e,t,i,a,r);case 1:return i=t.type,a=t.pendingProps,a=t.elementType===i?a:Qe(i,a),fa(e,t,i,a,r);case 3:e:{if(Cu(t),e===null)throw Error(W(387));i=t.pendingProps,h=t.memoizedState,a=h.element,Xc(e,t),ys(t,i,null,r);var y=t.memoizedState;if(i=y.element,h.isDehydrated)if(h={element:i,isDehydrated:!1,cache:y.cache,pendingSuspenseBoundaries:y.pendingSuspenseBoundaries,transitions:y.transitions},t.updateQueue.baseState=h,t.memoizedState=h,t.flags&256){a=xr(Error(W(423)),t),t=_a(e,t,i,r,a);break e}else if(i!==a){a=xr(Error(W(424)),t),t=_a(e,t,i,r,a);break e}else for(He=At(t.stateNode.containerInfo.firstChild),Fe=t,oe=!0,Je=null,r=Vc(t,null,i,r),t.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(Er(),i===a){t=gt(e,t,r);break e}xe(e,t,i,r)}t=t.child}return t;case 5:return Gc(t),e===null&&io(t),i=t.type,a=t.pendingProps,h=e!==null?e.memoizedProps:null,y=a.children,Jn(i,a)?y=null:h!==null&&Jn(i,h)&&(t.flags|=32),yu(e,t),xe(e,t,y,r),t.child;case 6:return e===null&&io(t),null;case 13:return wu(e,t,r);case 4:return Yo(t,t.stateNode.containerInfo),i=t.pendingProps,e===null?t.child=kr(t,null,i,r):xe(e,t,i,r),t.child;case 11:return i=t.type,a=t.pendingProps,a=t.elementType===i?a:Qe(i,a),ha(e,t,i,a,r);case 7:return xe(e,t,t.pendingProps,r),t.child;case 8:return xe(e,t,t.pendingProps.children,r),t.child;case 12:return xe(e,t,t.pendingProps.children,r),t.child;case 10:e:{if(i=t.type._context,a=t.pendingProps,h=t.memoizedProps,y=a.value,ie(ms,i._currentValue),i._currentValue=y,h!==null)if(tt(h.value,y)){if(h.children===a.children&&!Me.current){t=gt(e,t,r);break e}}else for(h=t.child,h!==null&&(h.return=t);h!==null;){var n=h.dependencies;if(n!==null){y=h.child;for(var u=n.firstContext;u!==null;){if(u.context===i){if(h.tag===1){u=ft(-1,r&-r),u.tag=2;var f=h.updateQueue;if(f!==null){f=f.shared;var S=f.pending;S===null?u.next=u:(u.next=S.next,S.next=u),f.pending=u}}h.lanes|=r,u=h.alternate,u!==null&&(u.lanes|=r),so(h.return,r,t),n.lanes|=r;break}u=u.next}}else if(h.tag===10)y=h.type===t.type?null:h.child;else if(h.tag===18){if(y=h.return,y===null)throw Error(W(341));y.lanes|=r,n=y.alternate,n!==null&&(n.lanes|=r),so(y,r,t),y=h.sibling}else y=h.child;if(y!==null)y.return=h;else for(y=h;y!==null;){if(y===t){y=null;break}if(h=y.sibling,h!==null){h.return=y.return,y=h;break}y=y.return}h=y}xe(e,t,a.children,r),t=t.child}return t;case 9:return a=t.type,i=t.pendingProps.children,Sr(t,r),a=qe(a),i=i(a),t.flags|=1,xe(e,t,i,r),t.child;case 14:return i=t.type,a=Qe(i,t.pendingProps),a=Qe(i.type,a),da(e,t,i,a,r);case 15:return mu(e,t,t.type,t.pendingProps,r);case 17:return i=t.type,a=t.pendingProps,a=t.elementType===i?a:Qe(i,a),es(e,t),t.tag=1,Be(i)?(e=!0,ps(t)):e=!1,Sr(t,r),pu(t,i,a),oo(t,i,a,r),co(null,t,i,!0,e,r);case 19:return Eu(e,t,r);case 22:return Su(e,t,r)}throw Error(W(156,t.tag))};function Nu(e,t){return dc(e,t)}function pf(e,t,r,i){this.tag=e,this.key=r,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=i,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ke(e,t,r,i){return new pf(e,t,r,i)}function dl(e){return e=e.prototype,!(!e||!e.isReactComponent)}function vf(e){if(typeof e=="function")return dl(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Ao)return 11;if(e===Po)return 14}return 2}function Ot(e,t){var r=e.alternate;return r===null?(r=Ke(e.tag,t,e.key,e.mode),r.elementType=e.elementType,r.type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=t,r.type=e.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=e.flags&14680064,r.childLanes=e.childLanes,r.lanes=e.lanes,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,t=e.dependencies,r.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r}function is(e,t,r,i,a,h){var y=2;if(i=e,typeof e=="function")dl(e)&&(y=1);else if(typeof e=="string")y=5;else e:switch(e){case sr:return qt(r.children,a,h,t);case To:y=8,a|=8;break;case Tn:return e=Ke(12,r,t,a|2),e.elementType=Tn,e.lanes=h,e;case An:return e=Ke(13,r,t,a),e.elementType=An,e.lanes=h,e;case Pn:return e=Ke(19,r,t,a),e.elementType=Pn,e.lanes=h,e;case Ga:return zs(r,a,h,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case qa:y=10;break e;case Xa:y=9;break e;case Ao:y=11;break e;case Po:y=14;break e;case wt:y=16,i=null;break e}throw Error(W(130,e==null?e:typeof e,""))}return t=Ke(y,r,t,a),t.elementType=e,t.type=i,t.lanes=h,t}function qt(e,t,r,i){return e=Ke(7,e,i,t),e.lanes=r,e}function zs(e,t,r,i){return e=Ke(22,e,i,t),e.elementType=Ga,e.lanes=r,e.stateNode={isHidden:!1},e}function kn(e,t,r){return e=Ke(6,e,null,t),e.lanes=r,e}function bn(e,t,r){return t=Ke(4,e.children!==null?e.children:[],e.key,t),t.lanes=r,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function gf(e,t,r,i,a){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=nn(0),this.expirationTimes=nn(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=nn(0),this.identifierPrefix=i,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function fl(e,t,r,i,a,h,y,n,u){return e=new gf(e,t,r,n,u),t===1?(t=1,h===!0&&(t|=8)):t=0,h=Ke(3,null,null,t),e.current=h,h.stateNode=e,h.memoizedState={element:i,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},Qo(h),e}function mf(e,t,r){var i=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Wu)}catch(e){console.error(e)}}Wu(),Wa.exports=ze;var Ef=Wa.exports,xa=Ef;Rn.createRoot=xa.createRoot,Rn.hydrateRoot=xa.hydrateRoot;const kf={},La=e=>{let t;const r=new Set,i=(S,d)=>{const p=typeof S=="function"?S(t):S;if(!Object.is(p,t)){const C=t;t=d??(typeof p!="object"||p===null)?p:Object.assign({},t,p),r.forEach(w=>w(t,C))}},a=()=>t,u={setState:i,getState:a,getInitialState:()=>f,subscribe:S=>(r.add(S),()=>r.delete(S)),destroy:()=>{(kf?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),r.clear()}},f=t=e(i,a,u);return u},bf=e=>e?La(e):La;var $u={exports:{}},Ku={},Vu={exports:{}},qu={};/** + * @license React + * use-sync-external-store-shim.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Rr=dt;function xf(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Lf=typeof Object.is=="function"?Object.is:xf,Rf=Rr.useState,Df=Rr.useEffect,Tf=Rr.useLayoutEffect,Af=Rr.useDebugValue;function Pf(e,t){var r=t(),i=Rf({inst:{value:r,getSnapshot:t}}),a=i[0].inst,h=i[1];return Tf(function(){a.value=r,a.getSnapshot=t,xn(a)&&h({inst:a})},[e,r,t]),Df(function(){return xn(a)&&h({inst:a}),e(function(){xn(a)&&h({inst:a})})},[e]),Af(r),r}function xn(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!Lf(e,r)}catch{return!0}}function Mf(e,t){return t()}var Bf=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Mf:Pf;qu.useSyncExternalStore=Rr.useSyncExternalStore!==void 0?Rr.useSyncExternalStore:Bf;Vu.exports=qu;var Of=Vu.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Ks=dt,If=Of;function Hf(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Ff=typeof Object.is=="function"?Object.is:Hf,Nf=If.useSyncExternalStore,zf=Ks.useRef,jf=Ks.useEffect,Uf=Ks.useMemo,Wf=Ks.useDebugValue;Ku.useSyncExternalStoreWithSelector=function(e,t,r,i,a){var h=zf(null);if(h.current===null){var y={hasValue:!1,value:null};h.current=y}else y=h.current;h=Uf(function(){function u(C){if(!f){if(f=!0,S=C,C=i(C),a!==void 0&&y.hasValue){var w=y.value;if(a(w,C))return d=w}return d=C}if(w=d,Ff(S,C))return w;var m=i(C);return a!==void 0&&a(w,m)?(S=C,w):(S=C,d=m)}var f=!1,S,d,p=r===void 0?null:r;return[function(){return u(t())},p===null?void 0:function(){return u(p())}]},[t,r,i,a]);var n=Nf(e,h[0],h[1]);return jf(function(){y.hasValue=!0,y.value=n},[n]),Wf(n),n};$u.exports=Ku;var $f=$u.exports;const Kf=Ta($f),Xu={},{useDebugValue:Vf}=ja,{useSyncExternalStoreWithSelector:qf}=Kf;let Ra=!1;const Xf=e=>e;function Gf(e,t=Xf,r){(Xu?"production":void 0)!=="production"&&r&&!Ra&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),Ra=!0);const i=qf(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,r);return Vf(i),i}const Qf=e=>{(Xu?"production":void 0)!=="production"&&typeof e!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const t=typeof e=="function"?bf(e):e,r=(i,a)=>Gf(t,i,a);return Object.assign(r,t),r},Vs=e=>Qf,ss={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},wo=new Map,Ki=e=>{const t=wo.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([r,i])=>[r,i.getState()])):{}},Yf=(e,t,r)=>{if(e===void 0)return{type:"untracked",connection:t.connect(r)};const i=wo.get(r.name);if(i)return{type:"tracked",store:e,...i};const a={connection:t.connect(r),stores:{}};return wo.set(r.name,a),{type:"tracked",store:e,...a}},Jf=(e,t={})=>(r,i,a)=>{const{enabled:h,anonymousActionType:y,store:n,...u}=t;let f;try{f=(h??(ss?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!f)return(ss?"production":void 0)!=="production"&&h&&console.warn("[zustand devtools middleware] Please install/enable Redux devtools extension"),e(r,i,a);const{connection:S,...d}=Yf(n,f,u);let p=!0;a.setState=(m,c,o)=>{const s=r(m,c);if(!p)return s;const l=o===void 0?{type:y||"anonymous"}:typeof o=="string"?{type:o}:o;return n===void 0?(S==null||S.send(l,i()),s):(S==null||S.send({...l,type:`${n}/${l.type}`},{...Ki(u.name),[n]:a.getState()}),s)};const C=(...m)=>{const c=p;p=!1,r(...m),p=c},w=e(a.setState,i,a);if(d.type==="untracked"?S==null||S.init(w):(d.stores[d.store]=a,S==null||S.init(Object.fromEntries(Object.entries(d.stores).map(([m,c])=>[m,m===d.store?w:c.getState()])))),a.dispatchFromDevtools&&typeof a.dispatch=="function"){let m=!1;const c=a.dispatch;a.dispatch=(...o)=>{(ss?"production":void 0)!=="production"&&o[0].type==="__setState"&&!m&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),m=!0),c(...o)}}return S.subscribe(m=>{var c;switch(m.type){case"ACTION":if(typeof m.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return Ln(m.payload,o=>{if(o.type==="__setState"){if(n===void 0){C(o.state);return}Object.keys(o.state).length!==1&&console.error(` + [zustand devtools middleware] Unsupported __setState action format. + When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(), + and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } } + `);const s=o.state[n];if(s==null)return;JSON.stringify(a.getState())!==JSON.stringify(s)&&C(s);return}a.dispatchFromDevtools&&typeof a.dispatch=="function"&&a.dispatch(o)});case"DISPATCH":switch(m.payload.type){case"RESET":return C(w),n===void 0?S==null?void 0:S.init(a.getState()):S==null?void 0:S.init(Ki(u.name));case"COMMIT":if(n===void 0){S==null||S.init(a.getState());return}return S==null?void 0:S.init(Ki(u.name));case"ROLLBACK":return Ln(m.state,o=>{if(n===void 0){C(o),S==null||S.init(a.getState());return}C(o[n]),S==null||S.init(Ki(u.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return Ln(m.state,o=>{if(n===void 0){C(o);return}JSON.stringify(a.getState())!==JSON.stringify(o[n])&&C(o[n])});case"IMPORT_STATE":{const{nextLiftedState:o}=m.payload,s=(c=o.computedStates.slice(-1)[0])==null?void 0:c.state;if(!s)return;C(n===void 0?s:s[n]),S==null||S.send(null,o);return}case"PAUSE_RECORDING":return p=!p}return}}),w},qs=Jf,Ln=(e,t)=>{let r;try{r=JSON.parse(e)}catch(i){console.error("[zustand devtools middleware] Could not parse the received json",i)}r!==void 0&&t(r)};function Zf(e,t){let r;try{r=e()}catch{return}return{getItem:a=>{var h;const y=u=>u===null?null:JSON.parse(u,void 0),n=(h=r.getItem(a))!=null?h:null;return n instanceof Promise?n.then(y):y(n)},setItem:(a,h)=>r.setItem(a,JSON.stringify(h,void 0)),removeItem:a=>r.removeItem(a)}}const yi=e=>t=>{try{const r=e(t);return r instanceof Promise?r:{then(i){return yi(i)(r)},catch(i){return this}}}catch(r){return{then(i){return this},catch(i){return yi(i)(r)}}}},e_=(e,t)=>(r,i,a)=>{let h={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:c=>c,version:0,merge:(c,o)=>({...o,...c}),...t},y=!1;const n=new Set,u=new Set;let f;try{f=h.getStorage()}catch{}if(!f)return e((...c)=>{console.warn(`[zustand persist middleware] Unable to update item '${h.name}', the given storage is currently unavailable.`),r(...c)},i,a);const S=yi(h.serialize),d=()=>{const c=h.partialize({...i()});let o;const s=S({state:c,version:h.version}).then(l=>f.setItem(h.name,l)).catch(l=>{o=l});if(o)throw o;return s},p=a.setState;a.setState=(c,o)=>{p(c,o),d()};const C=e((...c)=>{r(...c),d()},i,a);let w;const m=()=>{var c;if(!f)return;y=!1,n.forEach(s=>s(i()));const o=((c=h.onRehydrateStorage)==null?void 0:c.call(h,i()))||void 0;return yi(f.getItem.bind(f))(h.name).then(s=>{if(s)return h.deserialize(s)}).then(s=>{if(s)if(typeof s.version=="number"&&s.version!==h.version){if(h.migrate)return h.migrate(s.state,s.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return s.state}).then(s=>{var l;return w=h.merge(s,(l=i())!=null?l:C),r(w,!0),d()}).then(()=>{o==null||o(w,void 0),y=!0,u.forEach(s=>s(w))}).catch(s=>{o==null||o(void 0,s)})};return a.persist={setOptions:c=>{h={...h,...c},c.getStorage&&(f=c.getStorage())},clearStorage:()=>{f==null||f.removeItem(h.name)},getOptions:()=>h,rehydrate:()=>m(),hasHydrated:()=>y,onHydrate:c=>(n.add(c),()=>{n.delete(c)}),onFinishHydration:c=>(u.add(c),()=>{u.delete(c)})},m(),w||C},t_=(e,t)=>(r,i,a)=>{let h={storage:Zf(()=>localStorage),partialize:m=>m,version:0,merge:(m,c)=>({...c,...m}),...t},y=!1;const n=new Set,u=new Set;let f=h.storage;if(!f)return e((...m)=>{console.warn(`[zustand persist middleware] Unable to update item '${h.name}', the given storage is currently unavailable.`),r(...m)},i,a);const S=()=>{const m=h.partialize({...i()});return f.setItem(h.name,{state:m,version:h.version})},d=a.setState;a.setState=(m,c)=>{d(m,c),S()};const p=e((...m)=>{r(...m),S()},i,a);a.getInitialState=()=>p;let C;const w=()=>{var m,c;if(!f)return;y=!1,n.forEach(s=>{var l;return s((l=i())!=null?l:p)});const o=((c=h.onRehydrateStorage)==null?void 0:c.call(h,(m=i())!=null?m:p))||void 0;return yi(f.getItem.bind(f))(h.name).then(s=>{if(s)if(typeof s.version=="number"&&s.version!==h.version){if(h.migrate)return[!0,h.migrate(s.state,s.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,s.state];return[!1,void 0]}).then(s=>{var l;const[_,g]=s;if(C=h.merge(g,(l=i())!=null?l:p),r(C,!0),_)return S()}).then(()=>{o==null||o(C,void 0),C=i(),y=!0,u.forEach(s=>s(C))}).catch(s=>{o==null||o(void 0,s)})};return a.persist={setOptions:m=>{h={...h,...m},m.storage&&(f=m.storage)},clearStorage:()=>{f==null||f.removeItem(h.name)},getOptions:()=>h,rehydrate:()=>w(),hasHydrated:()=>y,onHydrate:m=>(n.add(m),()=>{n.delete(m)}),onFinishHydration:m=>(u.add(m),()=>{u.delete(m)})},h.skipHydration||w(),C||p},r_=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((ss?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),e_(e,t)):t_(e,t),i_=r_,s_={camX:0,camY:0,zoom:1,flying:!1,dragging:!1,collapsed:!1,spacePanning:!1,setCam:()=>{},setZoom:()=>{},setFlying:()=>{},setDragging:()=>{},setCollapsed:()=>{},setSpacePanning:()=>{}},Ci=Vs()(qs(i_(e=>({...s_,setCam:(t,r)=>e({camX:t,camY:r}),setZoom:t=>e({zoom:t}),setFlying:t=>e({flying:t}),setDragging:t=>e({dragging:t}),setCollapsed:t=>e({collapsed:t}),setSpacePanning:t=>e({spacePanning:t})}),{name:"canvas-state"}))),n_={krates:new Map,selectedKrateId:null,addKrate:()=>{},removeKrate:()=>{},selectKrate:()=>{},updateKrate:()=>{}},gl=Vs()(qs(e=>({...n_,addKrate:t=>e(r=>({krates:new Map(r.krates).set(t.id,t)})),removeKrate:t=>e(r=>{const i=new Map(r.krates);return i.delete(t),{krates:i}}),selectKrate:t=>e({selectedKrateId:t}),updateKrate:(t,r)=>e(i=>{const a=i.krates.get(t);return a?{krates:new Map(i.krates).set(t,{...a,...r})}:i})}))),o_=({krate:e,collapsed:t})=>{const{selectKrate:r}=gl();return t?K.jsxs("div",{style:{position:"absolute",left:e.x,top:e.y,width:"230px",height:"auto",padding:"12px",background:e.color?`rgba(${Da(e.color)}, 0.04)`:"rgba(255,255,255,0.04)",border:`1px dashed ${e.color||"#6fb1ff"}4D`,borderRadius:"18px",cursor:"pointer"},onClick:()=>r(e.id),children:[K.jsx("div",{style:{fontWeight:"600",color:e.color||"#6fb1ff"},children:e.title}),K.jsx("div",{style:{fontSize:"12px",color:"#888"},children:e.windows.size>0?'..."':"Empty"})]}):K.jsxs("div",{style:{position:"absolute",left:e.x,top:e.y,width:e.width,height:e.height,background:e.color?`rgba(${Da(e.color)}, 0.04)`:"rgba(255,255,255,0.04)",border:`1px dashed ${e.color||"#6fb1ff"}4D`,borderRadius:"18px"},onMouseDown:()=>r(e.id),children:[K.jsx(l_,{krate:e,onDragStart:()=>{}}),K.jsx("div",{style:{padding:"30px",display:"grid",gridTemplateColumns:`repeat(${e.windowLayout.cols}, 1fr)`,gap:"16px"},children:Array.from(e.windows.values()).map(i=>K.jsx("div",{style:{backgroundColor:"#1a1e26",border:"1px solid rgba(140,165,200,0.18)",borderRadius:"8px",padding:"12px",minHeight:"100px"},children:i.title},i.id))})]})},l_=({krate:e,onDragStart:t})=>K.jsxs("div",{style:{padding:"8px 12px",borderBottom:`1px solid ${e.color||"#6fb1ff"}33`,cursor:"grab",display:"flex",alignItems:"center",gap:"8px"},onMouseDown:r=>{r.stopPropagation(),t()},children:[K.jsx("span",{style:{fontWeight:"600",flex:1},children:e.title}),K.jsxs("span",{style:{fontSize:"12px",color:"#888"},children:[e.windows.size," windows"]}),K.jsx("button",{style:{background:"none",border:"none",color:"#888",cursor:"pointer",padding:"4px"},onClick:r=>{r.stopPropagation(),alert("Minimize todo")},children:"—"}),K.jsx("button",{style:{background:"none",border:"none",color:"#888",cursor:"pointer",padding:"4px"},onClick:r=>{r.stopPropagation(),alert("Delete todo")},children:"×"})]}),Da=e=>{const t=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),i=parseInt(e.slice(5,7),16);return`${t}, ${r}, ${i}`},a_=({...e})=>{const{camX:t,camY:r,zoom:i,collapsed:a}=Ci(),{krates:h}=gl(),y={position:"absolute",width:"12000px",height:"8000px",transform:`translate(${t}px, ${r}px) scale(${i})`,transformOrigin:"0 0"};return K.jsx("div",{style:y,...e,children:Array.from(h.values()).filter(n=>!n.minimized).map(n=>K.jsx(o_,{krate:n,collapsed:a},n.id))})},c_=({...e})=>{Ci();const t={position:"absolute",top:0,left:0,right:0,bottom:0,pointerEvents:"none",backgroundSize:"34px 34px, 170px 170px",backgroundPosition:"0 0, 0 0",backgroundImage:` + linear-gradient(to right, rgba(125,145,175,.04) 1px, transparent 1px), + linear-gradient(to bottom, rgba(125,145,175,.04) 1px, transparent 1px), + linear-gradient(to right, rgba(125,145,175,.075) 1px, transparent 1px), + linear-gradient(to bottom, rgba(125,145,175,.075) 1px, transparent 1px) + `};return K.jsx("div",{style:t,...e})},u_=({...e})=>{const{camX:t,camY:r,zoom:i}=Ci(),{krates:a}=gl(),h=dt.useRef(null),y=180,n=120,u=12e3,f=8e3,S=y/u,d=n/f,p=window.innerWidth/i,C=window.innerHeight/i,w=t*S,m=r*d,c=p*S,o=C*d,s=l=>{var k;const _=(k=h.current)==null?void 0:k.getBoundingClientRect();if(!_)return;const g=l.clientX-_.left,E=l.clientY-_.top,b=g/S-t-p/2,v=E/d-r-C/2;Ci.getState().setCam(b,v)};return K.jsxs("div",{ref:h,onClick:s,style:{position:"absolute",right:"18px",bottom:"64px",width:y,height:n,background:"rgba(16,20,28,.97)",border:"1px solid rgba(140,165,200,.2)",borderRadius:"4px",overflow:"hidden",zIndex:30},...e,children:[Array.from(a.values()).map(l=>K.jsx("div",{style:{position:"absolute",left:l.x*S,top:l.y*d,width:l.width*S,height:l.height*d,backgroundColor:l.color||"#6fb1ff",opacity:.7}},l.id)),K.jsx("div",{style:{position:"absolute",left:w,top:m,width:c,height:o,border:"1px solid #4dd6e8",borderColor:"rgba(77, 214, 232, 0.4)",boxSizing:"border-box"}})]})},h_={open:!1,query:"",filterType:null,sel:0,navigated:!1},d_=Vs()(qs(e=>({...h_,setOpen:t=>e({open:t}),setQuery:t=>e({query:t,navigated:!1,sel:0}),setFilter:t=>e({filterType:t}),setSel:t=>e({sel:t,navigated:!0}),toggle:()=>e(t=>({open:!t.open})),close:()=>e({open:!1,query:"",filterType:null,sel:0,navigated:!1})}))),f_=({...e})=>{const{open:t,query:r,filterType:i}=d_();if(!t)return null;const a=[{id:"all",label:"All"},{id:"krate",label:"Krates"},{id:"namespace",label:"Namespaces"},{id:"pod",label:"Pods"},{id:"deployment",label:"Deployments"},{id:"service",label:"Services"}];return K.jsx("div",{style:{position:"absolute",top:"100px",left:"50%",transform:"translateX(-50%)",width:"600px",zIndex:100},...e,children:K.jsxs("div",{style:{background:"#1a1e26",border:"1px solid rgba(140,165,200,0.18)",borderRadius:"12px",overflow:"hidden"},children:[K.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px",padding:"12px 16px",borderBottom:"1px solid rgba(140,165,200,0.18)"},children:[K.jsx("span",{style:{color:"#888"},children:"🔍"}),K.jsx("input",{type:"text",value:r,placeholder:"Search...",autoFocus:!0,style:{flex:1,background:"transparent",border:"none",color:"#fff",fontSize:"16px",outline:"none"}}),K.jsx("button",{style:{background:"none",border:"none",color:"#888",cursor:"pointer",padding:"4px"},children:"Esc"})]}),K.jsx("div",{style:{padding:"8px 16px",display:"flex",gap:"8px",flexWrap:"wrap"},children:a.map(h=>K.jsx("button",{style:{padding:"4px 12px",borderRadius:"12px",background:i===h.id?"#4dd6e8":"#2a3040",color:i===h.id?"#000":"#aaa",border:"none",cursor:"pointer",fontSize:"12px"},children:h.label},h.id))}),K.jsx("div",{style:{padding:"8px 16px",color:"#888",fontSize:"12px"},children:"Select: Enter, Close: Esc"})]})})},__={currentUser:{id:"local-user",name:"User"},presence:new Map},p_=Vs()(qs(e=>({...__,setCurrentUser:t=>e({currentUser:t}),addPresence:t=>e(r=>({presence:new Map(r.presence).set(t.userId,t)})),removePresence:t=>e(r=>{const i=new Map(r.presence);return i.delete(t),{presence:i}}),updatePresence:(t,r)=>e(i=>{const a=i.presence.get(t);return a?{presence:new Map(i.presence).set(t,{...a,...r})}:i})}))),v_=({open:e,onClose:t,users:r})=>{if(!e)return null;const i=a=>{t(),console.log(`Spectating user: ${a}`)};return K.jsxs("div",{style:{position:"absolute",right:0,top:0,bottom:0,width:"380px",zIndex:56,background:"rgba(13,17,24,.98)",borderLeft:"1px solid rgba(140,165,200,.2)",overflowY:"auto"},onClick:t,children:[K.jsxs("div",{style:{padding:"16px",borderBottom:"1px solid rgba(140,165,200,0.18)",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[K.jsx("h2",{style:{margin:0,color:"#fff",fontSize:"16px"},children:"Users"}),K.jsx("button",{onClick:t,style:{background:"none",border:"none",color:"#888",cursor:"pointer",fontSize:"20px"},children:"×"})]}),K.jsx("div",{style:{padding:"16px"},children:r.map(a=>K.jsx("div",{style:{marginBottom:"16px",padding:"12px",background:"rgba(255,255,255,0.02)",borderRadius:"8px"},onClick:h=>h.stopPropagation(),children:K.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[K.jsx("div",{style:{width:"40px",height:"40px",borderRadius:"50%",background:a.color,display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:"600"},children:a.name.slice(0,2).toUpperCase()}),K.jsxs("div",{style:{flex:1},children:[K.jsx("div",{style:{color:"#fff",fontWeight:"600"},children:a.name}),K.jsx("div",{style:{color:"#888",fontSize:"12px"},children:a.status})]}),K.jsx("button",{onClick:()=>i(a.userId),style:{background:"#4dd6e8",border:"none",borderRadius:"4px",padding:"6px 10px",color:"#000",fontSize:"12px",fontWeight:"600",cursor:"pointer"},children:"Spectate"})]})},a.userId))})]})},g_=()=>{const{currentUser:e,presence:t}=p_(),[r,i]=dt.useState(!1),[a,h]=dt.useState(!0);dt.useEffect(()=>{const n=setInterval(()=>{h(u=>!u)},1e3);return()=>clearInterval(n)},[]);const y=Array.from(t.values()).map(n=>({userId:n.userId,name:n.name,color:n.color,status:"active"}));return K.jsxs(K.Fragment,{children:[K.jsxs("div",{style:{position:"absolute",top:0,left:0,right:0,zIndex:10,height:"56px",display:"flex",alignItems:"center",padding:"13px 18px"},children:[K.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flex:1},children:[K.jsxs("div",{style:{background:"rgba(14,18,25,.82)",border:"1px solid rgba(140,165,200,.18)",borderRadius:"9px",padding:"7px 12px",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",gap:"6px",cursor:"pointer"},children:[K.jsx("div",{style:{width:"12px",height:"12px",background:"#4dd6e8",clipPath:"polygon(50% 0,100% 50%,50% 100%,0 50%)"}}),K.jsx("span",{style:{color:"#fff",fontSize:"14px",fontWeight:"600"},children:"krates / yard"})]}),K.jsxs("div",{style:{background:"rgba(14,18,25,.82)",border:"1px solid rgba(140,165,200,.18)",borderRadius:"9px",padding:"7px 12px",display:"flex",alignItems:"center",gap:"8px",backdropFilter:"blur(6px)"},children:[K.jsx("span",{style:{color:"#fff",fontSize:"14px"},children:"local"}),K.jsx("div",{style:{width:"8px",height:"8px",borderRadius:"50%",background:"#4ad07a",boxShadow:"0 0 8px #4ad07a"}})]}),y.length>0&&K.jsx("div",{style:{background:"rgba(14,18,25,.82)",border:"1px solid rgba(140,165,200,.18)",borderRadius:"9px",padding:"7px 12px",backdropFilter:"blur(6px)"},children:K.jsxs("span",{style:{color:"#4dd6e8",fontSize:"14px"},children:[y.length," active"]})})]}),K.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[K.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"4px 10px",borderRadius:"9px",background:"rgba(14,18,25,.82)",border:"1px solid rgba(140,165,200,.18)",backdropFilter:"blur(6px)"},children:[K.jsx("span",{style:{color:"#aaa",fontSize:"12px"},children:"synced"}),K.jsx("div",{style:{width:"6px",height:"6px",borderRadius:"50%",background:"#4dd6e8",opacity:a?1:.5,animation:a?"pulse 1.6s ease-in-out infinite":"none"}})]}),K.jsx("button",{onClick:()=>i(!r),style:{background:r?"rgba(77,214,232,0.1)":"rgba(14,18,25,.82)",border:r?"1px solid #4dd6e8":"1px solid rgba(140,165,200,.18)",borderRadius:"9px",padding:"6px 12px",backdropFilter:"blur(6px)",color:r?"#4dd6e8":"#aaa",fontSize:"14px",cursor:"pointer"},children:"◉ admin"}),y.slice(0,5).map(n=>K.jsx("div",{style:{width:"30px",height:"30px",borderRadius:"50%",background:n.color,display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",color:"#fff",fontWeight:"600",cursor:"pointer",border:n.userId===e.id?"2px solid #4dd6e8":"none"},title:n.name,children:n.userId===e.id?"★":n.name.slice(0,2).toUpperCase()},n.userId)),y.length>5&&K.jsxs("div",{style:{width:"30px",height:"30px",borderRadius:"50%",background:"#2a3040",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"10px",color:"#aaa",cursor:"pointer"},children:["+",y.length-5]})]})]}),K.jsx(v_,{open:r,onClose:()=>i(!1),users:y})]})};var m_={exports:{}};(function(e,t){(function(r,i){e.exports=i()})(self,()=>(()=>{var r={4567:function(y,n,u){var f=this&&this.__decorate||function(l,_,g,E){var b,v=arguments.length,k=v<3?_:E===null?E=Object.getOwnPropertyDescriptor(_,g):E;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(l,_,g,E);else for(var R=l.length-1;R>=0;R--)(b=l[R])&&(k=(v<3?b(k):v>3?b(_,g,k):b(_,g))||k);return v>3&&k&&Object.defineProperty(_,g,k),k},S=this&&this.__param||function(l,_){return function(g,E){_(g,E,l)}};Object.defineProperty(n,"__esModule",{value:!0}),n.AccessibilityManager=void 0;const d=u(9042),p=u(6114),C=u(9924),w=u(844),m=u(5596),c=u(4725),o=u(3656);let s=n.AccessibilityManager=class extends w.Disposable{constructor(l,_){super(),this._terminal=l,this._renderService=_,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=document.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=document.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let g=0;gthis._handleBoundaryFocus(g,0),this._bottomBoundaryFocusListener=g=>this._handleBoundaryFocus(g,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=document.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new C.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize(g=>this._handleResize(g.rows))),this.register(this._terminal.onRender(g=>this._refreshRows(g.start,g.end))),this.register(this._terminal.onScroll(()=>this._refreshRows())),this.register(this._terminal.onA11yChar(g=>this._handleChar(g))),this.register(this._terminal.onLineFeed(()=>this._handleChar(` +`))),this.register(this._terminal.onA11yTab(g=>this._handleTab(g))),this.register(this._terminal.onKey(g=>this._handleKey(g.key))),this.register(this._terminal.onBlur(()=>this._clearLiveRegion())),this.register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._screenDprMonitor=new m.ScreenDprMonitor(window),this.register(this._screenDprMonitor),this._screenDprMonitor.setListener(()=>this._refreshRowsDimensions()),this.register((0,o.addDisposableDomListener)(window,"resize",()=>this._refreshRowsDimensions())),this._refreshRows(),this.register((0,w.toDisposable)(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(l){for(let _=0;_0?this._charsToConsume.shift()!==l&&(this._charsToAnnounce+=l):this._charsToAnnounce+=l,l===` +`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=d.tooMuchOutput)),p.isMac&&this._liveRegion.textContent&&this._liveRegion.textContent.length>0&&!this._liveRegion.parentNode&&setTimeout(()=>{this._accessibilityContainer.appendChild(this._liveRegion)},0))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0,p.isMac&&this._liveRegion.remove()}_handleKey(l){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(l)||this._charsToConsume.push(l)}_refreshRows(l,_){this._liveRegionDebouncer.refresh(l,_,this._terminal.rows)}_renderRows(l,_){const g=this._terminal.buffer,E=g.lines.length.toString();for(let b=l;b<=_;b++){const v=g.translateBufferLineToString(g.ydisp+b,!0),k=(g.ydisp+b+1).toString(),R=this._rowElements[b];R&&(v.length===0?R.innerText=" ":R.textContent=v,R.setAttribute("aria-posinset",k),R.setAttribute("aria-setsize",E))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(l,_){const g=l.target,E=this._rowElements[_===0?1:this._rowElements.length-2];if(g.getAttribute("aria-posinset")===(_===0?"1":`${this._terminal.buffer.lines.length}`)||l.relatedTarget!==E)return;let b,v;if(_===0?(b=g,v=this._rowElements.pop(),this._rowContainer.removeChild(v)):(b=this._rowElements.shift(),v=g,this._rowContainer.removeChild(b)),b.removeEventListener("focus",this._topBoundaryFocusListener),v.removeEventListener("focus",this._bottomBoundaryFocusListener),_===0){const k=this._createAccessibilityTreeNode();this._rowElements.unshift(k),this._rowContainer.insertAdjacentElement("afterbegin",k)}else{const k=this._createAccessibilityTreeNode();this._rowElements.push(k),this._rowContainer.appendChild(k)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(_===0?-1:1),this._rowElements[_===0?1:this._rowElements.length-2].focus(),l.preventDefault(),l.stopImmediatePropagation()}_handleResize(l){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let _=this._rowContainer.children.length;_l;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const l=document.createElement("div");return l.setAttribute("role","listitem"),l.tabIndex=-1,this._refreshRowDimensions(l),l}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let l=0;l{function u(p){return p.replace(/\r?\n/g,"\r")}function f(p,C){return C?"\x1B[200~"+p+"\x1B[201~":p}function S(p,C,w,m){p=f(p=u(p),w.decPrivateModes.bracketedPasteMode&&m.rawOptions.ignoreBracketedPasteMode!==!0),w.triggerDataEvent(p,!0),C.value=""}function d(p,C,w){const m=w.getBoundingClientRect(),c=p.clientX-m.left-10,o=p.clientY-m.top-10;C.style.width="20px",C.style.height="20px",C.style.left=`${c}px`,C.style.top=`${o}px`,C.style.zIndex="1000",C.focus()}Object.defineProperty(n,"__esModule",{value:!0}),n.rightClickHandler=n.moveTextAreaUnderMouseCursor=n.paste=n.handlePasteEvent=n.copyHandler=n.bracketTextForPaste=n.prepareTextForTerminal=void 0,n.prepareTextForTerminal=u,n.bracketTextForPaste=f,n.copyHandler=function(p,C){p.clipboardData&&p.clipboardData.setData("text/plain",C.selectionText),p.preventDefault()},n.handlePasteEvent=function(p,C,w,m){p.stopPropagation(),p.clipboardData&&S(p.clipboardData.getData("text/plain"),C,w,m)},n.paste=S,n.moveTextAreaUnderMouseCursor=d,n.rightClickHandler=function(p,C,w,m,c){d(p,C,w),c&&m.rightClickSelect(p),C.value=m.selectionText,C.select()}},7239:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ColorContrastCache=void 0;const f=u(1505);n.ColorContrastCache=class{constructor(){this._color=new f.TwoKeyMap,this._css=new f.TwoKeyMap}setCss(S,d,p){this._css.set(S,d,p)}getCss(S,d){return this._css.get(S,d)}setColor(S,d,p){this._color.set(S,d,p)}getColor(S,d){return this._color.get(S,d)}clear(){this._color.clear(),this._css.clear()}}},3656:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.addDisposableDomListener=void 0,n.addDisposableDomListener=function(u,f,S,d){u.addEventListener(f,S,d);let p=!1;return{dispose:()=>{p||(p=!0,u.removeEventListener(f,S,d))}}}},6465:function(y,n,u){var f=this&&this.__decorate||function(c,o,s,l){var _,g=arguments.length,E=g<3?o:l===null?l=Object.getOwnPropertyDescriptor(o,s):l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(c,o,s,l);else for(var b=c.length-1;b>=0;b--)(_=c[b])&&(E=(g<3?_(E):g>3?_(o,s,E):_(o,s))||E);return g>3&&E&&Object.defineProperty(o,s,E),E},S=this&&this.__param||function(c,o){return function(s,l){o(s,l,c)}};Object.defineProperty(n,"__esModule",{value:!0}),n.Linkifier2=void 0;const d=u(3656),p=u(8460),C=u(844),w=u(2585);let m=n.Linkifier2=class extends C.Disposable{get currentLink(){return this._currentLink}constructor(c){super(),this._bufferService=c,this._linkProviders=[],this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new p.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new p.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,C.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,C.toDisposable)(()=>{this._lastMouseEvent=void 0})),this.register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0}))}registerLinkProvider(c){return this._linkProviders.push(c),{dispose:()=>{const o=this._linkProviders.indexOf(c);o!==-1&&this._linkProviders.splice(o,1)}}}attachToDom(c,o,s){this._element=c,this._mouseService=o,this._renderService=s,this.register((0,d.addDisposableDomListener)(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this.register((0,d.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,d.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,d.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(c){if(this._lastMouseEvent=c,!this._element||!this._mouseService)return;const o=this._positionFromMouseEvent(c,this._element,this._mouseService);if(!o)return;this._isMouseOut=!1;const s=c.composedPath();for(let l=0;l{g==null||g.forEach(E=>{E.link.dispose&&E.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=c.y);let _=!1;for(const[g,E]of this._linkProviders.entries())o?!((l=this._activeProviderReplies)===null||l===void 0)&&l.get(g)&&(_=this._checkLinkProviderResult(g,c,_)):E.provideLinks(c.y,b=>{var v,k;if(this._isMouseOut)return;const R=b==null?void 0:b.map(P=>({link:P}));(v=this._activeProviderReplies)===null||v===void 0||v.set(g,R),_=this._checkLinkProviderResult(g,c,_),((k=this._activeProviderReplies)===null||k===void 0?void 0:k.size)===this._linkProviders.length&&this._removeIntersectingLinks(c.y,this._activeProviderReplies)})}_removeIntersectingLinks(c,o){const s=new Set;for(let l=0;lc?this._bufferService.cols:E.link.range.end.x;for(let k=b;k<=v;k++){if(s.has(k)){_.splice(g--,1);break}s.add(k)}}}}_checkLinkProviderResult(c,o,s){var l;if(!this._activeProviderReplies)return s;const _=this._activeProviderReplies.get(c);let g=!1;for(let E=0;Ethis._linkAtPosition(b.link,o));E&&(s=!0,this._handleNewLink(E))}if(this._activeProviderReplies.size===this._linkProviders.length&&!s)for(let E=0;Ethis._linkAtPosition(v.link,o));if(b){s=!0,this._handleNewLink(b);break}}return s}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(c){if(!this._element||!this._mouseService||!this._currentLink)return;const o=this._positionFromMouseEvent(c,this._element,this._mouseService);o&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,o)&&this._currentLink.link.activate(c,this._currentLink.link.text)}_clearCurrentLink(c,o){this._element&&this._currentLink&&this._lastMouseEvent&&(!c||!o||this._currentLink.link.range.start.y>=c&&this._currentLink.link.range.end.y<=o)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,C.disposeArray)(this._linkCacheDisposables))}_handleNewLink(c){if(!this._element||!this._lastMouseEvent||!this._mouseService)return;const o=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);o&&this._linkAtPosition(c.link,o)&&(this._currentLink=c,this._currentLink.state={decorations:{underline:c.link.decorations===void 0||c.link.decorations.underline,pointerCursor:c.link.decorations===void 0||c.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,c.link,this._lastMouseEvent),c.link.decorations={},Object.defineProperties(c.link.decorations,{pointerCursor:{get:()=>{var s,l;return(l=(s=this._currentLink)===null||s===void 0?void 0:s.state)===null||l===void 0?void 0:l.decorations.pointerCursor},set:s=>{var l,_;!((l=this._currentLink)===null||l===void 0)&&l.state&&this._currentLink.state.decorations.pointerCursor!==s&&(this._currentLink.state.decorations.pointerCursor=s,this._currentLink.state.isHovered&&((_=this._element)===null||_===void 0||_.classList.toggle("xterm-cursor-pointer",s)))}},underline:{get:()=>{var s,l;return(l=(s=this._currentLink)===null||s===void 0?void 0:s.state)===null||l===void 0?void 0:l.decorations.underline},set:s=>{var l,_,g;!((l=this._currentLink)===null||l===void 0)&&l.state&&((g=(_=this._currentLink)===null||_===void 0?void 0:_.state)===null||g===void 0?void 0:g.decorations.underline)!==s&&(this._currentLink.state.decorations.underline=s,this._currentLink.state.isHovered&&this._fireUnderlineEvent(c.link,s))}}}),this._renderService&&this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(s=>{if(!this._currentLink)return;const l=s.start===0?0:s.start+1+this._bufferService.buffer.ydisp,_=this._bufferService.buffer.ydisp+1+s.end;if(this._currentLink.link.range.start.y>=l&&this._currentLink.link.range.end.y<=_&&(this._clearCurrentLink(l,_),this._lastMouseEvent&&this._element)){const g=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);g&&this._askForLink(g,!1)}})))}_linkHover(c,o,s){var l;!((l=this._currentLink)===null||l===void 0)&&l.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(o,!0),this._currentLink.state.decorations.pointerCursor&&c.classList.add("xterm-cursor-pointer")),o.hover&&o.hover(s,o.text)}_fireUnderlineEvent(c,o){const s=c.range,l=this._bufferService.buffer.ydisp,_=this._createLinkUnderlineEvent(s.start.x-1,s.start.y-l-1,s.end.x,s.end.y-l-1,void 0);(o?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(_)}_linkLeave(c,o,s){var l;!((l=this._currentLink)===null||l===void 0)&&l.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(o,!1),this._currentLink.state.decorations.pointerCursor&&c.classList.remove("xterm-cursor-pointer")),o.leave&&o.leave(s,o.text)}_linkAtPosition(c,o){const s=c.range.start.y*this._bufferService.cols+c.range.start.x,l=c.range.end.y*this._bufferService.cols+c.range.end.x,_=o.y*this._bufferService.cols+o.x;return s<=_&&_<=l}_positionFromMouseEvent(c,o,s){const l=s.getCoords(c,o,this._bufferService.cols,this._bufferService.rows);if(l)return{x:l[0],y:l[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(c,o,s,l,_){return{x1:c,y1:o,x2:s,y2:l,cols:this._bufferService.cols,fg:_}}};n.Linkifier2=m=f([S(0,w.IBufferService)],m)},9042:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.tooMuchOutput=n.promptLabel=void 0,n.promptLabel="Terminal input",n.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(y,n,u){var f=this&&this.__decorate||function(m,c,o,s){var l,_=arguments.length,g=_<3?c:s===null?s=Object.getOwnPropertyDescriptor(c,o):s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")g=Reflect.decorate(m,c,o,s);else for(var E=m.length-1;E>=0;E--)(l=m[E])&&(g=(_<3?l(g):_>3?l(c,o,g):l(c,o))||g);return _>3&&g&&Object.defineProperty(c,o,g),g},S=this&&this.__param||function(m,c){return function(o,s){c(o,s,m)}};Object.defineProperty(n,"__esModule",{value:!0}),n.OscLinkProvider=void 0;const d=u(511),p=u(2585);let C=n.OscLinkProvider=class{constructor(m,c,o){this._bufferService=m,this._optionsService=c,this._oscLinkService=o}provideLinks(m,c){var o;const s=this._bufferService.buffer.lines.get(m-1);if(!s)return void c(void 0);const l=[],_=this._optionsService.rawOptions.linkHandler,g=new d.CellData,E=s.getTrimmedLength();let b=-1,v=-1,k=!1;for(let R=0;R_?_.activate(I,z,A):w(0,z),hover:(I,z)=>{var U;return(U=_==null?void 0:_.hover)===null||U===void 0?void 0:U.call(_,I,z,A)},leave:(I,z)=>{var U;return(U=_==null?void 0:_.leave)===null||U===void 0?void 0:U.call(_,I,z,A)}})}k=!1,g.hasExtendedAttrs()&&g.extended.urlId?(v=R,b=g.extended.urlId):(v=-1,b=-1)}}c(l)}};function w(m,c){if(confirm(`Do you want to navigate to ${c}? + +WARNING: This link could potentially be dangerous`)){const o=window.open();if(o){try{o.opener=null}catch{}o.location.href=c}else console.warn("Opening link blocked as opener could not be cleared")}}n.OscLinkProvider=C=f([S(0,p.IBufferService),S(1,p.IOptionsService),S(2,p.IOscLinkService)],C)},6193:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.RenderDebouncer=void 0,n.RenderDebouncer=class{constructor(u,f){this._parentWindow=u,this._renderCallback=f,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._parentWindow.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(u){return this._refreshCallbacks.push(u),this._animationFrame||(this._animationFrame=this._parentWindow.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(u,f,S){this._rowCount=S,u=u!==void 0?u:0,f=f!==void 0?f:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,u):u,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,f):f,this._animationFrame||(this._animationFrame=this._parentWindow.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return void this._runRefreshCallbacks();const u=Math.max(this._rowStart,0),f=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(u,f),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const u of this._refreshCallbacks)u(0);this._refreshCallbacks=[]}}},5596:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ScreenDprMonitor=void 0;const f=u(844);class S extends f.Disposable{constructor(p){super(),this._parentWindow=p,this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this.register((0,f.toDisposable)(()=>{this.clearListener()}))}setListener(p){this._listener&&this.clearListener(),this._listener=p,this._outerListener=()=>{this._listener&&(this._listener(this._parentWindow.devicePixelRatio,this._currentDevicePixelRatio),this._updateDpr())},this._updateDpr()}_updateDpr(){var p;this._outerListener&&((p=this._resolutionMediaMatchList)===null||p===void 0||p.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){this._resolutionMediaMatchList&&this._listener&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._listener=void 0,this._outerListener=void 0)}}n.ScreenDprMonitor=S},3236:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Terminal=void 0;const f=u(3614),S=u(3656),d=u(6465),p=u(9042),C=u(3730),w=u(1680),m=u(3107),c=u(5744),o=u(2950),s=u(1296),l=u(428),_=u(4269),g=u(5114),E=u(8934),b=u(3230),v=u(9312),k=u(4725),R=u(6731),P=u(8055),A=u(8969),B=u(8460),I=u(844),z=u(6114),U=u(8437),j=u(2584),x=u(7399),D=u(5941),T=u(9074),M=u(2585),F=u(5435),$=u(4567),G=typeof window<"u"?window.document:null;class X extends A.CoreTerminal{get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(L={}){super(L),this.browser=z,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new I.MutableDisposable),this._onCursorMove=this.register(new B.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new B.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new B.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new B.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new B.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new B.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new B.EventEmitter),this._onBlur=this.register(new B.EventEmitter),this._onA11yCharEmitter=this.register(new B.EventEmitter),this._onA11yTabEmitter=this.register(new B.EventEmitter),this._onWillOpen=this.register(new B.EventEmitter),this._setup(),this.linkifier2=this.register(this._instantiationService.createInstance(d.Linkifier2)),this.linkifier2.registerLinkProvider(this._instantiationService.createInstance(C.OscLinkProvider)),this._decorationService=this._instantiationService.createInstance(T.DecorationService),this._instantiationService.setService(M.IDecorationService,this._decorationService),this.register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this.register(this._inputHandler.onRequestRefreshRows((O,N)=>this.refresh(O,N))),this.register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this.register(this._inputHandler.onRequestReset(()=>this.reset())),this.register(this._inputHandler.onRequestWindowsOptionsReport(O=>this._reportWindowsOptions(O))),this.register(this._inputHandler.onColor(O=>this._handleColorEvent(O))),this.register((0,B.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,B.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,B.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,B.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this.register(this._bufferService.onResize(O=>this._afterResize(O.cols,O.rows))),this.register((0,I.toDisposable)(()=>{var O,N;this._customKeyEventHandler=void 0,(N=(O=this.element)===null||O===void 0?void 0:O.parentNode)===null||N===void 0||N.removeChild(this.element)}))}_handleColorEvent(L){if(this._themeService)for(const O of L){let N,H="";switch(O.index){case 256:N="foreground",H="10";break;case 257:N="background",H="11";break;case 258:N="cursor",H="12";break;default:N="ansi",H="4;"+O.index}switch(O.type){case 0:const Q=P.color.toColorRGB(N==="ansi"?this._themeService.colors.ansi[O.index]:this._themeService.colors[N]);this.coreService.triggerDataEvent(`${j.C0.ESC}]${H};${(0,D.toRgbString)(Q)}${j.C1_ESCAPED.ST}`);break;case 1:if(N==="ansi")this._themeService.modifyColors(V=>V.ansi[O.index]=P.rgba.toColor(...O.color));else{const V=N;this._themeService.modifyColors(te=>te[V]=P.rgba.toColor(...O.color))}break;case 2:this._themeService.restoreColor(O.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(L){L?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance($.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(L){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(j.C0.ESC+"[I"),this.updateCursorStyle(L),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var L;return(L=this.textarea)===null||L===void 0?void 0:L.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(j.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;const L=this.buffer.ybase+this.buffer.y,O=this.buffer.lines.get(L);if(!O)return;const N=Math.min(this.buffer.x,this.cols-1),H=this._renderService.dimensions.css.cell.height,Q=O.getWidth(N),V=this._renderService.dimensions.css.cell.width*Q,te=this.buffer.y*this._renderService.dimensions.css.cell.height,me=N*this._renderService.dimensions.css.cell.width;this.textarea.style.left=me+"px",this.textarea.style.top=te+"px",this.textarea.style.width=V+"px",this.textarea.style.height=H+"px",this.textarea.style.lineHeight=H+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this.register((0,S.addDisposableDomListener)(this.element,"copy",O=>{this.hasSelection()&&(0,f.copyHandler)(O,this._selectionService)}));const L=O=>(0,f.handlePasteEvent)(O,this.textarea,this.coreService,this.optionsService);this.register((0,S.addDisposableDomListener)(this.textarea,"paste",L)),this.register((0,S.addDisposableDomListener)(this.element,"paste",L)),z.isFirefox?this.register((0,S.addDisposableDomListener)(this.element,"mousedown",O=>{O.button===2&&(0,f.rightClickHandler)(O,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this.register((0,S.addDisposableDomListener)(this.element,"contextmenu",O=>{(0,f.rightClickHandler)(O,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),z.isLinux&&this.register((0,S.addDisposableDomListener)(this.element,"auxclick",O=>{O.button===1&&(0,f.moveTextAreaUnderMouseCursor)(O,this.textarea,this.screenElement)}))}_bindKeys(){this.register((0,S.addDisposableDomListener)(this.textarea,"keyup",L=>this._keyUp(L),!0)),this.register((0,S.addDisposableDomListener)(this.textarea,"keydown",L=>this._keyDown(L),!0)),this.register((0,S.addDisposableDomListener)(this.textarea,"keypress",L=>this._keyPress(L),!0)),this.register((0,S.addDisposableDomListener)(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this.register((0,S.addDisposableDomListener)(this.textarea,"compositionupdate",L=>this._compositionHelper.compositionupdate(L))),this.register((0,S.addDisposableDomListener)(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this.register((0,S.addDisposableDomListener)(this.textarea,"input",L=>this._inputEvent(L),!0)),this.register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(L){var O;if(!L)throw new Error("Terminal requires a parent element.");L.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this._document=L.ownerDocument,this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),L.appendChild(this.element);const N=G.createDocumentFragment();this._viewportElement=G.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),N.appendChild(this._viewportElement),this._viewportScrollArea=G.createElement("div"),this._viewportScrollArea.classList.add("xterm-scroll-area"),this._viewportElement.appendChild(this._viewportScrollArea),this.screenElement=G.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._helperContainer=G.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),N.appendChild(this.screenElement),this.textarea=G.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",p.promptLabel),z.isChromeOS||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._coreBrowserService=this._instantiationService.createInstance(g.CoreBrowserService,this.textarea,(O=this._document.defaultView)!==null&&O!==void 0?O:window),this._instantiationService.setService(k.ICoreBrowserService,this._coreBrowserService),this.register((0,S.addDisposableDomListener)(this.textarea,"focus",H=>this._handleTextAreaFocus(H))),this.register((0,S.addDisposableDomListener)(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(l.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(k.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(R.ThemeService),this._instantiationService.setService(k.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(_.CharacterJoinerService),this._instantiationService.setService(k.ICharacterJoinerService,this._characterJoinerService),this._renderService=this.register(this._instantiationService.createInstance(b.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(k.IRenderService,this._renderService),this.register(this._renderService.onRenderedViewportChange(H=>this._onRender.fire(H))),this.onResize(H=>this._renderService.resize(H.cols,H.rows)),this._compositionView=G.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(o.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this.element.appendChild(N);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._mouseService=this._instantiationService.createInstance(E.MouseService),this._instantiationService.setService(k.IMouseService,this._mouseService),this.viewport=this._instantiationService.createInstance(w.Viewport,this._viewportElement,this._viewportScrollArea),this.viewport.onRequestScrollLines(H=>this.scrollLines(H.amount,H.suppressScrollEvent,1)),this.register(this._inputHandler.onRequestSyncScrollBar(()=>this.viewport.syncScrollArea())),this.register(this.viewport),this.register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this.register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this.register(this.onBlur(()=>this._renderService.handleBlur())),this.register(this.onFocus(()=>this._renderService.handleFocus())),this.register(this._renderService.onDimensionsChange(()=>this.viewport.syncScrollArea())),this._selectionService=this.register(this._instantiationService.createInstance(v.SelectionService,this.element,this.screenElement,this.linkifier2)),this._instantiationService.setService(k.ISelectionService,this._selectionService),this.register(this._selectionService.onRequestScrollLines(H=>this.scrollLines(H.amount,H.suppressScrollEvent))),this.register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this.register(this._selectionService.onRequestRedraw(H=>this._renderService.handleSelectionChanged(H.start,H.end,H.columnSelectMode))),this.register(this._selectionService.onLinuxMouseSelection(H=>{this.textarea.value=H,this.textarea.focus(),this.textarea.select()})),this.register(this._onScroll.event(H=>{this.viewport.syncScrollArea(),this._selectionService.refresh()})),this.register((0,S.addDisposableDomListener)(this._viewportElement,"scroll",()=>this._selectionService.refresh())),this.linkifier2.attachToDom(this.screenElement,this._mouseService,this._renderService),this.register(this._instantiationService.createInstance(m.BufferDecorationRenderer,this.screenElement)),this.register((0,S.addDisposableDomListener)(this.element,"mousedown",H=>this._selectionService.handleMouseDown(H))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance($.AccessibilityManager,this)),this.register(this.optionsService.onSpecificOptionChange("screenReaderMode",H=>this._handleScreenReaderModeOptionChange(H))),this.options.overviewRulerWidth&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(c.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRulerWidth",H=>{!this._overviewRulerRenderer&&H&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(c.OverviewRulerRenderer,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(s.DomRenderer,this.element,this.screenElement,this._viewportElement,this.linkifier2)}bindMouse(){const L=this,O=this.element;function N(V){const te=L._mouseService.getMouseReportCoords(V,L.screenElement);if(!te)return!1;let me,Te;switch(V.overrideType||V.type){case"mousemove":Te=32,V.buttons===void 0?(me=3,V.button!==void 0&&(me=V.button<3?V.button:3)):me=1&V.buttons?0:4&V.buttons?1:2&V.buttons?2:3;break;case"mouseup":Te=0,me=V.button<3?V.button:3;break;case"mousedown":Te=1,me=V.button<3?V.button:3;break;case"wheel":if(L.viewport.getLinesScrolled(V)===0)return!1;Te=V.deltaY<0?0:1,me=4;break;default:return!1}return!(Te===void 0||me===void 0||me>4)&&L.coreMouseService.triggerMouseEvent({col:te.col,row:te.row,x:te.x,y:te.y,button:me,action:Te,ctrl:V.ctrlKey,alt:V.altKey,shift:V.shiftKey})}const H={mouseup:null,wheel:null,mousedrag:null,mousemove:null},Q={mouseup:V=>(N(V),V.buttons||(this._document.removeEventListener("mouseup",H.mouseup),H.mousedrag&&this._document.removeEventListener("mousemove",H.mousedrag)),this.cancel(V)),wheel:V=>(N(V),this.cancel(V,!0)),mousedrag:V=>{V.buttons&&N(V)},mousemove:V=>{V.buttons||N(V)}};this.register(this.coreMouseService.onProtocolChange(V=>{V?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(V)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),8&V?H.mousemove||(O.addEventListener("mousemove",Q.mousemove),H.mousemove=Q.mousemove):(O.removeEventListener("mousemove",H.mousemove),H.mousemove=null),16&V?H.wheel||(O.addEventListener("wheel",Q.wheel,{passive:!1}),H.wheel=Q.wheel):(O.removeEventListener("wheel",H.wheel),H.wheel=null),2&V?H.mouseup||(O.addEventListener("mouseup",Q.mouseup),H.mouseup=Q.mouseup):(this._document.removeEventListener("mouseup",H.mouseup),O.removeEventListener("mouseup",H.mouseup),H.mouseup=null),4&V?H.mousedrag||(H.mousedrag=Q.mousedrag):(this._document.removeEventListener("mousemove",H.mousedrag),H.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this.register((0,S.addDisposableDomListener)(O,"mousedown",V=>{if(V.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(V))return N(V),H.mouseup&&this._document.addEventListener("mouseup",H.mouseup),H.mousedrag&&this._document.addEventListener("mousemove",H.mousedrag),this.cancel(V)})),this.register((0,S.addDisposableDomListener)(O,"wheel",V=>{if(!H.wheel){if(!this.buffer.hasScrollback){const te=this.viewport.getLinesScrolled(V);if(te===0)return;const me=j.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(V.deltaY<0?"A":"B");let Te="";for(let tr=0;tr{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchStart(V),this.cancel(V)},{passive:!0})),this.register((0,S.addDisposableDomListener)(O,"touchmove",V=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchMove(V)?void 0:this.cancel(V)},{passive:!1}))}refresh(L,O){var N;(N=this._renderService)===null||N===void 0||N.refreshRows(L,O)}updateCursorStyle(L){var O;!((O=this._selectionService)===null||O===void 0)&&O.shouldColumnSelect(L)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(L,O,N=0){var H;N===1?(super.scrollLines(L,O,N),this.refresh(0,this.rows-1)):(H=this.viewport)===null||H===void 0||H.scrollLines(L)}paste(L){(0,f.paste)(L,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(L){this._customKeyEventHandler=L}registerLinkProvider(L){return this.linkifier2.registerLinkProvider(L)}registerCharacterJoiner(L){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");const O=this._characterJoinerService.register(L);return this.refresh(0,this.rows-1),O}deregisterCharacterJoiner(L){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(L)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(L){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+L)}registerDecoration(L){return this._decorationService.registerDecoration(L)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(L,O,N){this._selectionService.setSelection(L,O,N)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var L;(L=this._selectionService)===null||L===void 0||L.clearSelection()}selectAll(){var L;(L=this._selectionService)===null||L===void 0||L.selectAll()}selectLines(L,O){var N;(N=this._selectionService)===null||N===void 0||N.selectLines(L,O)}_keyDown(L){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(L)===!1)return!1;const O=this.browser.isMac&&this.options.macOptionIsMeta&&L.altKey;if(!O&&!this._compositionHelper.keydown(L))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(),!1;O||L.key!=="Dead"&&L.key!=="AltGraph"||(this._unprocessedDeadKey=!0);const N=(0,x.evaluateKeyboardEvent)(L,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(L),N.type===3||N.type===2){const H=this.rows-1;return this.scrollLines(N.type===2?-H:H),this.cancel(L,!0)}return N.type===1&&this.selectAll(),!!this._isThirdLevelShift(this.browser,L)||(N.cancel&&this.cancel(L,!0),!N.key||!!(L.key&&!L.ctrlKey&&!L.altKey&&!L.metaKey&&L.key.length===1&&L.key.charCodeAt(0)>=65&&L.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):(N.key!==j.C0.ETX&&N.key!==j.C0.CR||(this.textarea.value=""),this._onKey.fire({key:N.key,domEvent:L}),this._showCursor(),this.coreService.triggerDataEvent(N.key,!0),!this.optionsService.rawOptions.screenReaderMode||L.altKey||L.ctrlKey?this.cancel(L,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(L,O){const N=L.isMac&&!this.options.macOptionIsMeta&&O.altKey&&!O.ctrlKey&&!O.metaKey||L.isWindows&&O.altKey&&O.ctrlKey&&!O.metaKey||L.isWindows&&O.getModifierState("AltGraph");return O.type==="keypress"?N:N&&(!O.keyCode||O.keyCode>47)}_keyUp(L){this._keyDownSeen=!1,this._customKeyEventHandler&&this._customKeyEventHandler(L)===!1||(function(O){return O.keyCode===16||O.keyCode===17||O.keyCode===18}(L)||this.focus(),this.updateCursorStyle(L),this._keyPressHandled=!1)}_keyPress(L){let O;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(L)===!1)return!1;if(this.cancel(L),L.charCode)O=L.charCode;else if(L.which===null||L.which===void 0)O=L.keyCode;else{if(L.which===0||L.charCode===0)return!1;O=L.which}return!(!O||(L.altKey||L.ctrlKey||L.metaKey)&&!this._isThirdLevelShift(this.browser,L)||(O=String.fromCharCode(O),this._onKey.fire({key:O,domEvent:L}),this._showCursor(),this.coreService.triggerDataEvent(O,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(L){if(L.data&&L.inputType==="insertText"&&(!L.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;const O=L.data;return this.coreService.triggerDataEvent(O,!0),this.cancel(L),!0}return!1}resize(L,O){L!==this.cols||O!==this.rows?super.resize(L,O):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(L,O){var N,H;(N=this._charSizeService)===null||N===void 0||N.measure(),(H=this.viewport)===null||H===void 0||H.syncScrollArea(!0)}clear(){var L;if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let O=1;O{Object.defineProperty(n,"__esModule",{value:!0}),n.TimeBasedDebouncer=void 0,n.TimeBasedDebouncer=class{constructor(u,f=1e3){this._renderCallback=u,this._debounceThresholdMS=f,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(u,f,S){this._rowCount=S,u=u!==void 0?u:0,f=f!==void 0?f:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,u):u,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,f):f;const d=Date.now();if(d-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=d,this._innerRefresh();else if(!this._additionalRefreshRequested){const p=d-this._lastRefreshMs,C=this._debounceThresholdMS-p;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=Date.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},C)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;const u=Math.max(this._rowStart,0),f=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(u,f)}}},1680:function(y,n,u){var f=this&&this.__decorate||function(o,s,l,_){var g,E=arguments.length,b=E<3?s:_===null?_=Object.getOwnPropertyDescriptor(s,l):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")b=Reflect.decorate(o,s,l,_);else for(var v=o.length-1;v>=0;v--)(g=o[v])&&(b=(E<3?g(b):E>3?g(s,l,b):g(s,l))||b);return E>3&&b&&Object.defineProperty(s,l,b),b},S=this&&this.__param||function(o,s){return function(l,_){s(l,_,o)}};Object.defineProperty(n,"__esModule",{value:!0}),n.Viewport=void 0;const d=u(3656),p=u(4725),C=u(8460),w=u(844),m=u(2585);let c=n.Viewport=class extends w.Disposable{constructor(o,s,l,_,g,E,b,v){super(),this._viewportElement=o,this._scrollArea=s,this._bufferService=l,this._optionsService=_,this._charSizeService=g,this._renderService=E,this._coreBrowserService=b,this.scrollBarWidth=0,this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._wheelPartialScroll=0,this._refreshAnimationFrame=null,this._ignoreNextScrollEvent=!1,this._smoothScrollState={startTime:0,origin:-1,target:-1},this._onRequestScrollLines=this.register(new C.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this.scrollBarWidth=this._viewportElement.offsetWidth-this._scrollArea.offsetWidth||15,this.register((0,d.addDisposableDomListener)(this._viewportElement,"scroll",this._handleScroll.bind(this))),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate(k=>this._activeBuffer=k.activeBuffer)),this._renderDimensions=this._renderService.dimensions,this.register(this._renderService.onDimensionsChange(k=>this._renderDimensions=k)),this._handleThemeChange(v.colors),this.register(v.onChangeColors(k=>this._handleThemeChange(k))),this.register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.syncScrollArea())),setTimeout(()=>this.syncScrollArea())}_handleThemeChange(o){this._viewportElement.style.backgroundColor=o.background.css}reset(){this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._coreBrowserService.window.requestAnimationFrame(()=>this.syncScrollArea())}_refresh(o){if(o)return this._innerRefresh(),void(this._refreshAnimationFrame!==null&&this._coreBrowserService.window.cancelAnimationFrame(this._refreshAnimationFrame));this._refreshAnimationFrame===null&&(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._charSizeService.height>0){this._currentRowHeight=this._renderService.dimensions.device.cell.height/this._coreBrowserService.dpr,this._currentDeviceCellHeight=this._renderService.dimensions.device.cell.height,this._lastRecordedViewportHeight=this._viewportElement.offsetHeight;const s=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderService.dimensions.css.canvas.height);this._lastRecordedBufferHeight!==s&&(this._lastRecordedBufferHeight=s,this._scrollArea.style.height=this._lastRecordedBufferHeight+"px")}const o=this._bufferService.buffer.ydisp*this._currentRowHeight;this._viewportElement.scrollTop!==o&&(this._ignoreNextScrollEvent=!0,this._viewportElement.scrollTop=o),this._refreshAnimationFrame=null}syncScrollArea(o=!1){if(this._lastRecordedBufferLength!==this._bufferService.buffer.lines.length)return this._lastRecordedBufferLength=this._bufferService.buffer.lines.length,void this._refresh(o);this._lastRecordedViewportHeight===this._renderService.dimensions.css.canvas.height&&this._lastScrollTop===this._activeBuffer.ydisp*this._currentRowHeight&&this._renderDimensions.device.cell.height===this._currentDeviceCellHeight||this._refresh(o)}_handleScroll(o){if(this._lastScrollTop=this._viewportElement.scrollTop,!this._viewportElement.offsetParent)return;if(this._ignoreNextScrollEvent)return this._ignoreNextScrollEvent=!1,void this._onRequestScrollLines.fire({amount:0,suppressScrollEvent:!0});const s=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._onRequestScrollLines.fire({amount:s,suppressScrollEvent:!0})}_smoothScroll(){if(this._isDisposed||this._smoothScrollState.origin===-1||this._smoothScrollState.target===-1)return;const o=this._smoothScrollPercent();this._viewportElement.scrollTop=this._smoothScrollState.origin+Math.round(o*(this._smoothScrollState.target-this._smoothScrollState.origin)),o<1?this._coreBrowserService.window.requestAnimationFrame(()=>this._smoothScroll()):this._clearSmoothScrollState()}_smoothScrollPercent(){return this._optionsService.rawOptions.smoothScrollDuration&&this._smoothScrollState.startTime?Math.max(Math.min((Date.now()-this._smoothScrollState.startTime)/this._optionsService.rawOptions.smoothScrollDuration,1),0):1}_clearSmoothScrollState(){this._smoothScrollState.startTime=0,this._smoothScrollState.origin=-1,this._smoothScrollState.target=-1}_bubbleScroll(o,s){const l=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(s<0&&this._viewportElement.scrollTop!==0||s>0&&l0&&(_=A),g=""}}return{bufferElements:E,cursorElement:_}}getLinesScrolled(o){if(o.deltaY===0||o.shiftKey)return 0;let s=this._applyScrollModifier(o.deltaY,o);return o.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(s/=this._currentRowHeight+0,this._wheelPartialScroll+=s,s=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):o.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(s*=this._bufferService.rows),s}_applyScrollModifier(o,s){const l=this._optionsService.rawOptions.fastScrollModifier;return l==="alt"&&s.altKey||l==="ctrl"&&s.ctrlKey||l==="shift"&&s.shiftKey?o*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:o*this._optionsService.rawOptions.scrollSensitivity}handleTouchStart(o){this._lastTouchY=o.touches[0].pageY}handleTouchMove(o){const s=this._lastTouchY-o.touches[0].pageY;return this._lastTouchY=o.touches[0].pageY,s!==0&&(this._viewportElement.scrollTop+=s,this._bubbleScroll(o,s))}};n.Viewport=c=f([S(2,m.IBufferService),S(3,m.IOptionsService),S(4,p.ICharSizeService),S(5,p.IRenderService),S(6,p.ICoreBrowserService),S(7,p.IThemeService)],c)},3107:function(y,n,u){var f=this&&this.__decorate||function(c,o,s,l){var _,g=arguments.length,E=g<3?o:l===null?l=Object.getOwnPropertyDescriptor(o,s):l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(c,o,s,l);else for(var b=c.length-1;b>=0;b--)(_=c[b])&&(E=(g<3?_(E):g>3?_(o,s,E):_(o,s))||E);return g>3&&E&&Object.defineProperty(o,s,E),E},S=this&&this.__param||function(c,o){return function(s,l){o(s,l,c)}};Object.defineProperty(n,"__esModule",{value:!0}),n.BufferDecorationRenderer=void 0;const d=u(3656),p=u(4725),C=u(844),w=u(2585);let m=n.BufferDecorationRenderer=class extends C.Disposable{constructor(c,o,s,l){super(),this._screenElement=c,this._bufferService=o,this._decorationService=s,this._renderService=l,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this.register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this.register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this.register((0,d.addDisposableDomListener)(window,"resize",()=>this._queueRefresh())),this.register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this.register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this.register(this._decorationService.onDecorationRemoved(_=>this._removeDecoration(_))),this.register((0,C.toDisposable)(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(const c of this._decorationService.decorations)this._renderDecoration(c);this._dimensionsChanged=!1}_renderDecoration(c){this._refreshStyle(c),this._dimensionsChanged&&this._refreshXPosition(c)}_createElement(c){var o,s;const l=document.createElement("div");l.classList.add("xterm-decoration"),l.classList.toggle("xterm-decoration-top-layer",((o=c==null?void 0:c.options)===null||o===void 0?void 0:o.layer)==="top"),l.style.width=`${Math.round((c.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,l.style.height=(c.options.height||1)*this._renderService.dimensions.css.cell.height+"px",l.style.top=(c.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",l.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;const _=(s=c.options.x)!==null&&s!==void 0?s:0;return _&&_>this._bufferService.cols&&(l.style.display="none"),this._refreshXPosition(c,l),l}_refreshStyle(c){const o=c.marker.line-this._bufferService.buffers.active.ydisp;if(o<0||o>=this._bufferService.rows)c.element&&(c.element.style.display="none",c.onRenderEmitter.fire(c.element));else{let s=this._decorationElements.get(c);s||(s=this._createElement(c),c.element=s,this._decorationElements.set(c,s),this._container.appendChild(s),c.onDispose(()=>{this._decorationElements.delete(c),s.remove()})),s.style.top=o*this._renderService.dimensions.css.cell.height+"px",s.style.display=this._altBufferIsActive?"none":"block",c.onRenderEmitter.fire(s)}}_refreshXPosition(c,o=c.element){var s;if(!o)return;const l=(s=c.options.x)!==null&&s!==void 0?s:0;(c.options.anchor||"left")==="right"?o.style.right=l?l*this._renderService.dimensions.css.cell.width+"px":"":o.style.left=l?l*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(c){var o;(o=this._decorationElements.get(c))===null||o===void 0||o.remove(),this._decorationElements.delete(c),c.dispose()}};n.BufferDecorationRenderer=m=f([S(1,w.IBufferService),S(2,w.IDecorationService),S(3,p.IRenderService)],m)},5871:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ColorZoneStore=void 0,n.ColorZoneStore=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(u){if(u.options.overviewRulerOptions){for(const f of this._zones)if(f.color===u.options.overviewRulerOptions.color&&f.position===u.options.overviewRulerOptions.position){if(this._lineIntersectsZone(f,u.marker.line))return;if(this._lineAdjacentToZone(f,u.marker.line,u.options.overviewRulerOptions.position))return void this._addLineToZone(f,u.marker.line)}if(this._zonePoolIndex=u.startBufferLine&&f<=u.endBufferLine}_lineAdjacentToZone(u,f,S){return f>=u.startBufferLine-this._linePadding[S||"full"]&&f<=u.endBufferLine+this._linePadding[S||"full"]}_addLineToZone(u,f){u.startBufferLine=Math.min(u.startBufferLine,f),u.endBufferLine=Math.max(u.endBufferLine,f)}}},5744:function(y,n,u){var f=this&&this.__decorate||function(_,g,E,b){var v,k=arguments.length,R=k<3?g:b===null?b=Object.getOwnPropertyDescriptor(g,E):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")R=Reflect.decorate(_,g,E,b);else for(var P=_.length-1;P>=0;P--)(v=_[P])&&(R=(k<3?v(R):k>3?v(g,E,R):v(g,E))||R);return k>3&&R&&Object.defineProperty(g,E,R),R},S=this&&this.__param||function(_,g){return function(E,b){g(E,b,_)}};Object.defineProperty(n,"__esModule",{value:!0}),n.OverviewRulerRenderer=void 0;const d=u(5871),p=u(3656),C=u(4725),w=u(844),m=u(2585),c={full:0,left:0,center:0,right:0},o={full:0,left:0,center:0,right:0},s={full:0,left:0,center:0,right:0};let l=n.OverviewRulerRenderer=class extends w.Disposable{get _width(){return this._optionsService.options.overviewRulerWidth||0}constructor(_,g,E,b,v,k,R){var P;super(),this._viewportElement=_,this._screenElement=g,this._bufferService=E,this._decorationService=b,this._renderService=v,this._optionsService=k,this._coreBrowseService=R,this._colorZoneStore=new d.ColorZoneStore,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=document.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),(P=this._viewportElement.parentElement)===null||P===void 0||P.insertBefore(this._canvas,this._viewportElement);const A=this._canvas.getContext("2d");if(!A)throw new Error("Ctx cannot be null");this._ctx=A,this._registerDecorationListeners(),this._registerBufferChangeListeners(),this._registerDimensionChangeListeners(),this.register((0,w.toDisposable)(()=>{var B;(B=this._canvas)===null||B===void 0||B.remove()}))}_registerDecorationListeners(){this.register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this.register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0)))}_registerBufferChangeListeners(){this.register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this.register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this.register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())}))}_registerDimensionChangeListeners(){this.register(this._renderService.onRender(()=>{this._containerHeight&&this._containerHeight===this._screenElement.clientHeight||(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this.register(this._optionsService.onSpecificOptionChange("overviewRulerWidth",()=>this._queueRefresh(!0))),this.register((0,p.addDisposableDomListener)(this._coreBrowseService.window,"resize",()=>this._queueRefresh(!0))),this._queueRefresh(!0)}_refreshDrawConstants(){const _=Math.floor(this._canvas.width/3),g=Math.ceil(this._canvas.width/3);o.full=this._canvas.width,o.left=_,o.center=g,o.right=_,this._refreshDrawHeightConstants(),s.full=0,s.left=0,s.center=o.left,s.right=o.left+o.center}_refreshDrawHeightConstants(){c.full=Math.round(2*this._coreBrowseService.dpr);const _=this._canvas.height/this._bufferService.buffer.lines.length,g=Math.round(Math.max(Math.min(_,12),6)*this._coreBrowseService.dpr);c.left=g,c.center=g,c.right=g}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*c.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*c.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*c.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*c.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowseService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowseService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(const g of this._decorationService.decorations)this._colorZoneStore.addDecoration(g);this._ctx.lineWidth=1;const _=this._colorZoneStore.zones;for(const g of _)g.position!=="full"&&this._renderColorZone(g);for(const g of _)g.position==="full"&&this._renderColorZone(g);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderColorZone(_){this._ctx.fillStyle=_.color,this._ctx.fillRect(s[_.position||"full"],Math.round((this._canvas.height-1)*(_.startBufferLine/this._bufferService.buffers.active.lines.length)-c[_.position||"full"]/2),o[_.position||"full"],Math.round((this._canvas.height-1)*((_.endBufferLine-_.startBufferLine)/this._bufferService.buffers.active.lines.length)+c[_.position||"full"]))}_queueRefresh(_,g){this._shouldUpdateDimensions=_||this._shouldUpdateDimensions,this._shouldUpdateAnchor=g||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowseService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};n.OverviewRulerRenderer=l=f([S(2,m.IBufferService),S(3,m.IDecorationService),S(4,C.IRenderService),S(5,m.IOptionsService),S(6,C.ICoreBrowserService)],l)},2950:function(y,n,u){var f=this&&this.__decorate||function(m,c,o,s){var l,_=arguments.length,g=_<3?c:s===null?s=Object.getOwnPropertyDescriptor(c,o):s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")g=Reflect.decorate(m,c,o,s);else for(var E=m.length-1;E>=0;E--)(l=m[E])&&(g=(_<3?l(g):_>3?l(c,o,g):l(c,o))||g);return _>3&&g&&Object.defineProperty(c,o,g),g},S=this&&this.__param||function(m,c){return function(o,s){c(o,s,m)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CompositionHelper=void 0;const d=u(4725),p=u(2585),C=u(2584);let w=n.CompositionHelper=class{get isComposing(){return this._isComposing}constructor(m,c,o,s,l,_){this._textarea=m,this._compositionView=c,this._bufferService=o,this._optionsService=s,this._coreService=l,this._renderService=_,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(m){this._compositionView.textContent=m.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(m){if(this._isComposing||this._isSendingComposition){if(m.keyCode===229||m.keyCode===16||m.keyCode===17||m.keyCode===18)return!1;this._finalizeComposition(!1)}return m.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(m){if(this._compositionView.classList.remove("active"),this._isComposing=!1,m){const c={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){let o;this._isSendingComposition=!1,c.start+=this._dataAlreadySent.length,o=this._isComposing?this._textarea.value.substring(c.start,c.end):this._textarea.value.substring(c.start),o.length>0&&this._coreService.triggerDataEvent(o,!0)}},0)}else{this._isSendingComposition=!1;const c=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(c,!0)}}_handleAnyTextareaChanges(){const m=this._textarea.value;setTimeout(()=>{if(!this._isComposing){const c=this._textarea.value,o=c.replace(m,"");this._dataAlreadySent=o,c.length>m.length?this._coreService.triggerDataEvent(o,!0):c.lengththis.updateCompositionElements(!0),0)}}};n.CompositionHelper=w=f([S(2,p.IBufferService),S(3,p.IOptionsService),S(4,p.ICoreService),S(5,d.IRenderService)],w)},9806:(y,n)=>{function u(f,S,d){const p=d.getBoundingClientRect(),C=f.getComputedStyle(d),w=parseInt(C.getPropertyValue("padding-left")),m=parseInt(C.getPropertyValue("padding-top"));return[S.clientX-p.left-w,S.clientY-p.top-m]}Object.defineProperty(n,"__esModule",{value:!0}),n.getCoords=n.getCoordsRelativeToElement=void 0,n.getCoordsRelativeToElement=u,n.getCoords=function(f,S,d,p,C,w,m,c,o){if(!w)return;const s=u(f,S,d);return s?(s[0]=Math.ceil((s[0]+(o?m/2:0))/m),s[1]=Math.ceil(s[1]/c),s[0]=Math.min(Math.max(s[0],1),p+(o?1:0)),s[1]=Math.min(Math.max(s[1],1),C),s):void 0}},9504:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.moveToCellSequence=void 0;const f=u(2584);function S(c,o,s,l){const _=c-d(c,s),g=o-d(o,s),E=Math.abs(_-g)-function(b,v,k){let R=0;const P=b-d(b,k),A=v-d(v,k);for(let B=0;B=0&&co?"A":"B"}function C(c,o,s,l,_,g){let E=c,b=o,v="";for(;E!==s||b!==l;)E+=_?1:-1,_&&E>g.cols-1?(v+=g.buffer.translateBufferLineToString(b,!1,c,E),E=0,c=0,b++):!_&&E<0&&(v+=g.buffer.translateBufferLineToString(b,!1,0,c+1),E=g.cols-1,c=E,b--);return v+g.buffer.translateBufferLineToString(b,!1,c,E)}function w(c,o){const s=o?"O":"[";return f.C0.ESC+s+c}function m(c,o){c=Math.floor(c);let s="";for(let l=0;l0?P-d(P,A):k;const z=P,U=function(j,x,D,T,M,F){let $;return $=S(D,T,M,F).length>0?T-d(T,M):x,j=D&&$c?"D":"C",m(Math.abs(_-c),w(E,l));E=g>o?"D":"C";const b=Math.abs(g-o);return m(function(v,k){return k.cols-v}(g>o?c:_,s)+(b-1)*s.cols+1+((g>o?_:c)-1),w(E,l))}},1296:function(y,n,u){var f=this&&this.__decorate||function(A,B,I,z){var U,j=arguments.length,x=j<3?B:z===null?z=Object.getOwnPropertyDescriptor(B,I):z;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")x=Reflect.decorate(A,B,I,z);else for(var D=A.length-1;D>=0;D--)(U=A[D])&&(x=(j<3?U(x):j>3?U(B,I,x):U(B,I))||x);return j>3&&x&&Object.defineProperty(B,I,x),x},S=this&&this.__param||function(A,B){return function(I,z){B(I,z,A)}};Object.defineProperty(n,"__esModule",{value:!0}),n.DomRenderer=void 0;const d=u(3787),p=u(2550),C=u(2223),w=u(6171),m=u(4725),c=u(8055),o=u(8460),s=u(844),l=u(2585),_="xterm-dom-renderer-owner-",g="xterm-rows",E="xterm-fg-",b="xterm-bg-",v="xterm-focus",k="xterm-selection";let R=1,P=n.DomRenderer=class extends s.Disposable{constructor(A,B,I,z,U,j,x,D,T,M){super(),this._element=A,this._screenElement=B,this._viewportElement=I,this._linkifier2=z,this._charSizeService=j,this._optionsService=x,this._bufferService=D,this._coreBrowserService=T,this._themeService=M,this._terminalClass=R++,this._rowElements=[],this.onRequestRedraw=this.register(new o.EventEmitter).event,this._rowContainer=document.createElement("div"),this._rowContainer.classList.add(g),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=document.createElement("div"),this._selectionContainer.classList.add(k),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=(0,w.createRenderDimensions)(),this._updateDimensions(),this.register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this.register(this._themeService.onChangeColors(F=>this._injectCss(F))),this._injectCss(this._themeService.colors),this._rowFactory=U.createInstance(d.DomRendererRowFactory,document),this._element.classList.add(_+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this.register(this._linkifier2.onShowLinkUnderline(F=>this._handleLinkHover(F))),this.register(this._linkifier2.onHideLinkUnderline(F=>this._handleLinkLeave(F))),this.register((0,s.toDisposable)(()=>{this._element.classList.remove(_+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new p.WidthCache(document),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){const A=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*A,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*A),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/A),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/A),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(const I of this._rowElements)I.style.width=`${this.dimensions.css.canvas.width}px`,I.style.height=`${this.dimensions.css.cell.height}px`,I.style.lineHeight=`${this.dimensions.css.cell.height}px`,I.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));const B=`${this._terminalSelector} .${g} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=B,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(A){this._themeStyleElement||(this._themeStyleElement=document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let B=`${this._terminalSelector} .${g} { color: ${A.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;B+=`${this._terminalSelector} .${g} .xterm-dim { color: ${c.color.multiplyOpacity(A.foreground,.5).css};}`,B+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`,B+="@keyframes blink_box_shadow_"+this._terminalClass+" { 50% { border-bottom-style: hidden; }}",B+="@keyframes blink_block_"+this._terminalClass+` { 0% { background-color: ${A.cursor.css}; color: ${A.cursorAccent.css}; } 50% { background-color: inherit; color: ${A.cursor.css}; }}`,B+=`${this._terminalSelector} .${g}.${v} .xterm-cursor.xterm-cursor-blink:not(.xterm-cursor-block) { animation: blink_box_shadow_`+this._terminalClass+` 1s step-end infinite;}${this._terminalSelector} .${g}.${v} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: blink_block_`+this._terminalClass+` 1s step-end infinite;}${this._terminalSelector} .${g} .xterm-cursor.xterm-cursor-block { background-color: ${A.cursor.css}; color: ${A.cursorAccent.css};}${this._terminalSelector} .${g} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${A.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${g} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${A.cursor.css} inset;}${this._terminalSelector} .${g} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${A.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,B+=`${this._terminalSelector} .${k} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${k} div { position: absolute; background-color: ${A.selectionBackgroundOpaque.css};}${this._terminalSelector} .${k} div { position: absolute; background-color: ${A.selectionInactiveBackgroundOpaque.css};}`;for(const[I,z]of A.ansi.entries())B+=`${this._terminalSelector} .${E}${I} { color: ${z.css}; }${this._terminalSelector} .${E}${I}.xterm-dim { color: ${c.color.multiplyOpacity(z,.5).css}; }${this._terminalSelector} .${b}${I} { background-color: ${z.css}; }`;B+=`${this._terminalSelector} .${E}${C.INVERTED_DEFAULT_COLOR} { color: ${c.color.opaque(A.background).css}; }${this._terminalSelector} .${E}${C.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${c.color.multiplyOpacity(c.color.opaque(A.background),.5).css}; }${this._terminalSelector} .${b}${C.INVERTED_DEFAULT_COLOR} { background-color: ${A.foreground.css}; }`,this._themeStyleElement.textContent=B}_setDefaultSpacing(){const A=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${A}px`,this._rowFactory.defaultSpacing=A}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(A,B){for(let I=this._rowElements.length;I<=B;I++){const z=document.createElement("div");this._rowContainer.appendChild(z),this._rowElements.push(z)}for(;this._rowElements.length>B;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(A,B){this._refreshRowElements(A,B),this._updateDimensions()}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(v)}handleFocus(){this._rowContainer.classList.add(v),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(A,B,I){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(A,B,I),this.renderRows(0,this._bufferService.rows-1),!A||!B)return;const z=A[1]-this._bufferService.buffer.ydisp,U=B[1]-this._bufferService.buffer.ydisp,j=Math.max(z,0),x=Math.min(U,this._bufferService.rows-1);if(j>=this._bufferService.rows||x<0)return;const D=document.createDocumentFragment();if(I){const T=A[0]>B[0];D.appendChild(this._createSelectionElement(j,T?B[0]:A[0],T?A[0]:B[0],x-j+1))}else{const T=z===j?A[0]:0,M=j===U?B[0]:this._bufferService.cols;D.appendChild(this._createSelectionElement(j,T,M));const F=x-j-1;if(D.appendChild(this._createSelectionElement(j+1,0,this._bufferService.cols,F)),j!==x){const $=U===x?B[0]:this._bufferService.cols;D.appendChild(this._createSelectionElement(x,0,$))}}this._selectionContainer.appendChild(D)}_createSelectionElement(A,B,I,z=1){const U=document.createElement("div");return U.style.height=z*this.dimensions.css.cell.height+"px",U.style.top=A*this.dimensions.css.cell.height+"px",U.style.left=B*this.dimensions.css.cell.width+"px",U.style.width=this.dimensions.css.cell.width*(I-B)+"px",U}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(const A of this._rowElements)A.replaceChildren()}renderRows(A,B){const I=this._bufferService.buffer,z=I.ybase+I.y,U=Math.min(I.x,this._bufferService.cols-1),j=this._optionsService.rawOptions.cursorBlink,x=this._optionsService.rawOptions.cursorStyle,D=this._optionsService.rawOptions.cursorInactiveStyle;for(let T=A;T<=B;T++){const M=T+I.ydisp,F=this._rowElements[T],$=I.lines.get(M);if(!F||!$)break;F.replaceChildren(...this._rowFactory.createRow($,M,M===z,x,D,U,j,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${_}${this._terminalClass}`}_handleLinkHover(A){this._setCellUnderline(A.x1,A.x2,A.y1,A.y2,A.cols,!0)}_handleLinkLeave(A){this._setCellUnderline(A.x1,A.x2,A.y1,A.y2,A.cols,!1)}_setCellUnderline(A,B,I,z,U,j){I<0&&(A=0),z<0&&(B=0);const x=this._bufferService.rows-1;I=Math.max(Math.min(I,x),0),z=Math.max(Math.min(z,x),0),U=Math.min(U,this._bufferService.cols);const D=this._bufferService.buffer,T=D.ybase+D.y,M=Math.min(D.x,U-1),F=this._optionsService.rawOptions.cursorBlink,$=this._optionsService.rawOptions.cursorStyle,G=this._optionsService.rawOptions.cursorInactiveStyle;for(let X=I;X<=z;++X){const ee=X+D.ydisp,L=this._rowElements[X],O=D.lines.get(ee);if(!L||!O)break;L.replaceChildren(...this._rowFactory.createRow(O,ee,ee===T,$,G,M,F,this.dimensions.css.cell.width,this._widthCache,j?X===I?A:0:-1,j?(X===z?B:U)-1:-1))}}};n.DomRenderer=P=f([S(4,l.IInstantiationService),S(5,m.ICharSizeService),S(6,l.IOptionsService),S(7,l.IBufferService),S(8,m.ICoreBrowserService),S(9,m.IThemeService)],P)},3787:function(y,n,u){var f=this&&this.__decorate||function(E,b,v,k){var R,P=arguments.length,A=P<3?b:k===null?k=Object.getOwnPropertyDescriptor(b,v):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(E,b,v,k);else for(var B=E.length-1;B>=0;B--)(R=E[B])&&(A=(P<3?R(A):P>3?R(b,v,A):R(b,v))||A);return P>3&&A&&Object.defineProperty(b,v,A),A},S=this&&this.__param||function(E,b){return function(v,k){b(v,k,E)}};Object.defineProperty(n,"__esModule",{value:!0}),n.DomRendererRowFactory=void 0;const d=u(2223),p=u(643),C=u(511),w=u(2585),m=u(8055),c=u(4725),o=u(4269),s=u(6171),l=u(3734);let _=n.DomRendererRowFactory=class{constructor(E,b,v,k,R,P,A){this._document=E,this._characterJoinerService=b,this._optionsService=v,this._coreBrowserService=k,this._coreService=R,this._decorationService=P,this._themeService=A,this._workCell=new C.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(E,b,v){this._selectionStart=E,this._selectionEnd=b,this._columnSelectMode=v}createRow(E,b,v,k,R,P,A,B,I,z,U){const j=[],x=this._characterJoinerService.getJoinedCharacters(b),D=this._themeService.colors;let T,M=E.getNoBgTrimmedLength();v&&M0&&te===x[0][0]){Te=!0;const le=x.shift();Y=new o.JoinedCellData(this._workCell,E.translateToString(!0,le[0],le[1]),le[1]-le[0]),tr=le[1]-1,me=Y.getWidth()}const Pr=this._isCellInSelection(te,b),Xs=v&&te===P,Gs=V&&te>=z&&te<=U;let Qs=!1;this._decorationService.forEachDecorationAtCell(te,b,void 0,le=>{Qs=!0});let Li=Y.getChars()||p.WHITESPACE_CELL_CHAR;if(Li===" "&&(Y.isUnderline()||Y.isOverline())&&(Li=" "),H=me*B-I.get(Li,Y.isBold(),Y.isItalic()),T){if(F&&(Pr&&N||!Pr&&!N&&Y.bg===G)&&(Pr&&N&&D.selectionForeground||Y.fg===X)&&Y.extended.ext===ee&&Gs===L&&H===O&&!Xs&&!Te&&!Qs){$+=Li,F++;continue}F&&(T.textContent=$),T=this._document.createElement("span"),F=0,$=""}else T=this._document.createElement("span");if(G=Y.bg,X=Y.fg,ee=Y.extended.ext,L=Gs,O=H,N=Pr,Te&&P>=te&&P<=tr&&(P=te),!this._coreService.isCursorHidden&&Xs){if(Q.push("xterm-cursor"),this._coreBrowserService.isFocused)A&&Q.push("xterm-cursor-blink"),Q.push(k==="bar"?"xterm-cursor-bar":k==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(R)switch(R){case"outline":Q.push("xterm-cursor-outline");break;case"block":Q.push("xterm-cursor-block");break;case"bar":Q.push("xterm-cursor-bar");break;case"underline":Q.push("xterm-cursor-underline")}}if(Y.isBold()&&Q.push("xterm-bold"),Y.isItalic()&&Q.push("xterm-italic"),Y.isDim()&&Q.push("xterm-dim"),$=Y.isInvisible()?p.WHITESPACE_CELL_CHAR:Y.getChars()||p.WHITESPACE_CELL_CHAR,Y.isUnderline()&&(Q.push(`xterm-underline-${Y.extended.underlineStyle}`),$===" "&&($=" "),!Y.isUnderlineColorDefault()))if(Y.isUnderlineColorRGB())T.style.textDecorationColor=`rgb(${l.AttributeData.toColorRGB(Y.getUnderlineColor()).join(",")})`;else{let le=Y.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&Y.isBold()&&le<8&&(le+=8),T.style.textDecorationColor=D.ansi[le].css}Y.isOverline()&&(Q.push("xterm-overline"),$===" "&&($=" ")),Y.isStrikethrough()&&Q.push("xterm-strikethrough"),Gs&&(T.style.textDecoration="underline");let Ue=Y.getFgColor(),Mr=Y.getFgColorMode(),rt=Y.getBgColor(),Br=Y.getBgColorMode();const Ys=!!Y.isInverse();if(Ys){const le=Ue;Ue=rt,rt=le;const Qu=Mr;Mr=Br,Br=Qu}let St,Js,yt,Or=!1;switch(this._decorationService.forEachDecorationAtCell(te,b,void 0,le=>{le.options.layer!=="top"&&Or||(le.backgroundColorRGB&&(Br=50331648,rt=le.backgroundColorRGB.rgba>>8&16777215,St=le.backgroundColorRGB),le.foregroundColorRGB&&(Mr=50331648,Ue=le.foregroundColorRGB.rgba>>8&16777215,Js=le.foregroundColorRGB),Or=le.options.layer==="top")}),!Or&&Pr&&(St=this._coreBrowserService.isFocused?D.selectionBackgroundOpaque:D.selectionInactiveBackgroundOpaque,rt=St.rgba>>8&16777215,Br=50331648,Or=!0,D.selectionForeground&&(Mr=50331648,Ue=D.selectionForeground.rgba>>8&16777215,Js=D.selectionForeground)),Or&&Q.push("xterm-decoration-top"),Br){case 16777216:case 33554432:yt=D.ansi[rt],Q.push(`xterm-bg-${rt}`);break;case 50331648:yt=m.rgba.toColor(rt>>16,rt>>8&255,255&rt),this._addStyle(T,`background-color:#${g((rt>>>0).toString(16),"0",6)}`);break;default:Ys?(yt=D.foreground,Q.push(`xterm-bg-${d.INVERTED_DEFAULT_COLOR}`)):yt=D.background}switch(St||Y.isDim()&&(St=m.color.multiplyOpacity(yt,.5)),Mr){case 16777216:case 33554432:Y.isBold()&&Ue<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Ue+=8),this._applyMinimumContrast(T,yt,D.ansi[Ue],Y,St,void 0)||Q.push(`xterm-fg-${Ue}`);break;case 50331648:const le=m.rgba.toColor(Ue>>16&255,Ue>>8&255,255&Ue);this._applyMinimumContrast(T,yt,le,Y,St,Js)||this._addStyle(T,`color:#${g(Ue.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(T,yt,D.foreground,Y,St,void 0)||Ys&&Q.push(`xterm-fg-${d.INVERTED_DEFAULT_COLOR}`)}Q.length&&(T.className=Q.join(" "),Q.length=0),Xs||Te||Qs?T.textContent=$:F++,H!==this.defaultSpacing&&(T.style.letterSpacing=`${H}px`),j.push(T),te=tr}return T&&F&&(T.textContent=$),j}_applyMinimumContrast(E,b,v,k,R,P){if(this._optionsService.rawOptions.minimumContrastRatio===1||(0,s.excludeFromContrastRatioDemands)(k.getCode()))return!1;const A=this._getContrastCache(k);let B;if(R||P||(B=A.getColor(b.rgba,v.rgba)),B===void 0){const I=this._optionsService.rawOptions.minimumContrastRatio/(k.isDim()?2:1);B=m.color.ensureContrastRatio(R||b,P||v,I),A.setColor((R||b).rgba,(P||v).rgba,B??null)}return!!B&&(this._addStyle(E,`color:${B.css}`),!0)}_getContrastCache(E){return E.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(E,b){E.setAttribute("style",`${E.getAttribute("style")||""}${b};`)}_isCellInSelection(E,b){const v=this._selectionStart,k=this._selectionEnd;return!(!v||!k)&&(this._columnSelectMode?v[0]<=k[0]?E>=v[0]&&b>=v[1]&&E=v[1]&&E>=k[0]&&b<=k[1]:b>v[1]&&b=v[0]&&E=v[0])}};function g(E,b,v){for(;E.length{Object.defineProperty(n,"__esModule",{value:!0}),n.WidthCache=void 0,n.WidthCache=class{constructor(u){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=u.createElement("div"),this._container.style.position="absolute",this._container.style.top="-50000px",this._container.style.width="50000px",this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";const f=u.createElement("span"),S=u.createElement("span");S.style.fontWeight="bold";const d=u.createElement("span");d.style.fontStyle="italic";const p=u.createElement("span");p.style.fontWeight="bold",p.style.fontStyle="italic",this._measureElements=[f,S,d,p],this._container.appendChild(f),this._container.appendChild(S),this._container.appendChild(d),this._container.appendChild(p),u.body.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(u,f,S,d){u===this._font&&f===this._fontSize&&S===this._weight&&d===this._weightBold||(this._font=u,this._fontSize=f,this._weight=S,this._weightBold=d,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${S}`,this._measureElements[1].style.fontWeight=`${d}`,this._measureElements[2].style.fontWeight=`${S}`,this._measureElements[3].style.fontWeight=`${d}`,this.clear())}get(u,f,S){let d=0;if(!f&&!S&&u.length===1&&(d=u.charCodeAt(0))<256)return this._flat[d]!==-9999?this._flat[d]:this._flat[d]=this._measure(u,0);let p=u;f&&(p+="B"),S&&(p+="I");let C=this._holey.get(p);if(C===void 0){let w=0;f&&(w|=1),S&&(w|=2),C=this._measure(u,w),this._holey.set(p,C)}return C}_measure(u,f){const S=this._measureElements[f];return S.textContent=u.repeat(32),S.offsetWidth/32}}},2223:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.TEXT_BASELINE=n.DIM_OPACITY=n.INVERTED_DEFAULT_COLOR=void 0;const f=u(6114);n.INVERTED_DEFAULT_COLOR=257,n.DIM_OPACITY=.5,n.TEXT_BASELINE=f.isFirefox||f.isLegacyEdge?"bottom":"ideographic"},6171:(y,n)=>{function u(f){return 57508<=f&&f<=57558}Object.defineProperty(n,"__esModule",{value:!0}),n.createRenderDimensions=n.excludeFromContrastRatioDemands=n.isRestrictedPowerlineGlyph=n.isPowerlineGlyph=n.throwIfFalsy=void 0,n.throwIfFalsy=function(f){if(!f)throw new Error("value must not be falsy");return f},n.isPowerlineGlyph=u,n.isRestrictedPowerlineGlyph=function(f){return 57520<=f&&f<=57527},n.excludeFromContrastRatioDemands=function(f){return u(f)||function(S){return 9472<=S&&S<=9631}(f)},n.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}}},456:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SelectionModel=void 0,n.SelectionModel=class{constructor(u){this._bufferService=u,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){const u=this.selectionStart[0]+this.selectionStartLength;return u>this._bufferService.cols?u%this._bufferService.cols==0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(u/this._bufferService.cols)-1]:[u%this._bufferService.cols,this.selectionStart[1]+Math.floor(u/this._bufferService.cols)]:[u,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){const u=this.selectionStart[0]+this.selectionStartLength;return u>this._bufferService.cols?[u%this._bufferService.cols,this.selectionStart[1]+Math.floor(u/this._bufferService.cols)]:[Math.max(u,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){const u=this.selectionStart,f=this.selectionEnd;return!(!u||!f)&&(u[1]>f[1]||u[1]===f[1]&&u[0]>f[0])}handleTrim(u){return this.selectionStart&&(this.selectionStart[1]-=u),this.selectionEnd&&(this.selectionEnd[1]-=u),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}}},428:function(y,n,u){var f=this&&this.__decorate||function(c,o,s,l){var _,g=arguments.length,E=g<3?o:l===null?l=Object.getOwnPropertyDescriptor(o,s):l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(c,o,s,l);else for(var b=c.length-1;b>=0;b--)(_=c[b])&&(E=(g<3?_(E):g>3?_(o,s,E):_(o,s))||E);return g>3&&E&&Object.defineProperty(o,s,E),E},S=this&&this.__param||function(c,o){return function(s,l){o(s,l,c)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CharSizeService=void 0;const d=u(2585),p=u(8460),C=u(844);let w=n.CharSizeService=class extends C.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(c,o,s){super(),this._optionsService=s,this.width=0,this.height=0,this._onCharSizeChange=this.register(new p.EventEmitter),this.onCharSizeChange=this._onCharSizeChange.event,this._measureStrategy=new m(c,o,this._optionsService),this.register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}measure(){const c=this._measureStrategy.measure();c.width===this.width&&c.height===this.height||(this.width=c.width,this.height=c.height,this._onCharSizeChange.fire())}};n.CharSizeService=w=f([S(2,d.IOptionsService)],w);class m{constructor(o,s,l){this._document=o,this._parentElement=s,this._optionsService=l,this._result={width:0,height:0},this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`;const o={height:Number(this._measureElement.offsetHeight),width:Number(this._measureElement.offsetWidth)};return o.width!==0&&o.height!==0&&(this._result.width=o.width/32,this._result.height=Math.ceil(o.height)),this._result}}},4269:function(y,n,u){var f=this&&this.__decorate||function(o,s,l,_){var g,E=arguments.length,b=E<3?s:_===null?_=Object.getOwnPropertyDescriptor(s,l):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")b=Reflect.decorate(o,s,l,_);else for(var v=o.length-1;v>=0;v--)(g=o[v])&&(b=(E<3?g(b):E>3?g(s,l,b):g(s,l))||b);return E>3&&b&&Object.defineProperty(s,l,b),b},S=this&&this.__param||function(o,s){return function(l,_){s(l,_,o)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CharacterJoinerService=n.JoinedCellData=void 0;const d=u(3734),p=u(643),C=u(511),w=u(2585);class m extends d.AttributeData{constructor(s,l,_){super(),this.content=0,this.combinedData="",this.fg=s.fg,this.bg=s.bg,this.combinedData=l,this._width=_}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(s){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}n.JoinedCellData=m;let c=n.CharacterJoinerService=class Gu{constructor(s){this._bufferService=s,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new C.CellData}register(s){const l={id:this._nextCharacterJoinerId++,handler:s};return this._characterJoiners.push(l),l.id}deregister(s){for(let l=0;l1){const A=this._getJoinedRanges(g,v,b,l,E);for(let B=0;B1){const P=this._getJoinedRanges(g,v,b,l,E);for(let A=0;A{Object.defineProperty(n,"__esModule",{value:!0}),n.CoreBrowserService=void 0,n.CoreBrowserService=class{constructor(u,f){this._textarea=u,this.window=f,this._isFocused=!1,this._cachedIsFocused=void 0,this._textarea.addEventListener("focus",()=>this._isFocused=!0),this._textarea.addEventListener("blur",()=>this._isFocused=!1)}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}}},8934:function(y,n,u){var f=this&&this.__decorate||function(w,m,c,o){var s,l=arguments.length,_=l<3?m:o===null?o=Object.getOwnPropertyDescriptor(m,c):o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")_=Reflect.decorate(w,m,c,o);else for(var g=w.length-1;g>=0;g--)(s=w[g])&&(_=(l<3?s(_):l>3?s(m,c,_):s(m,c))||_);return l>3&&_&&Object.defineProperty(m,c,_),_},S=this&&this.__param||function(w,m){return function(c,o){m(c,o,w)}};Object.defineProperty(n,"__esModule",{value:!0}),n.MouseService=void 0;const d=u(4725),p=u(9806);let C=n.MouseService=class{constructor(w,m){this._renderService=w,this._charSizeService=m}getCoords(w,m,c,o,s){return(0,p.getCoords)(window,w,m,c,o,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,s)}getMouseReportCoords(w,m){const c=(0,p.getCoordsRelativeToElement)(window,w,m);if(this._charSizeService.hasValidSize)return c[0]=Math.min(Math.max(c[0],0),this._renderService.dimensions.css.canvas.width-1),c[1]=Math.min(Math.max(c[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(c[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(c[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(c[0]),y:Math.floor(c[1])}}};n.MouseService=C=f([S(0,d.IRenderService),S(1,d.ICharSizeService)],C)},3230:function(y,n,u){var f=this&&this.__decorate||function(_,g,E,b){var v,k=arguments.length,R=k<3?g:b===null?b=Object.getOwnPropertyDescriptor(g,E):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")R=Reflect.decorate(_,g,E,b);else for(var P=_.length-1;P>=0;P--)(v=_[P])&&(R=(k<3?v(R):k>3?v(g,E,R):v(g,E))||R);return k>3&&R&&Object.defineProperty(g,E,R),R},S=this&&this.__param||function(_,g){return function(E,b){g(E,b,_)}};Object.defineProperty(n,"__esModule",{value:!0}),n.RenderService=void 0;const d=u(3656),p=u(6193),C=u(5596),w=u(4725),m=u(8460),c=u(844),o=u(7226),s=u(2585);let l=n.RenderService=class extends c.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(_,g,E,b,v,k,R,P){if(super(),this._rowCount=_,this._charSizeService=b,this._renderer=this.register(new c.MutableDisposable),this._pausedResizeTask=new o.DebouncedIdleTask,this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this.register(new m.EventEmitter),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this.register(new m.EventEmitter),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this.register(new m.EventEmitter),this.onRender=this._onRender.event,this._onRefreshRequest=this.register(new m.EventEmitter),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new p.RenderDebouncer(R.window,(A,B)=>this._renderRows(A,B)),this.register(this._renderDebouncer),this._screenDprMonitor=new C.ScreenDprMonitor(R.window),this._screenDprMonitor.setListener(()=>this.handleDevicePixelRatioChange()),this.register(this._screenDprMonitor),this.register(k.onResize(()=>this._fullRefresh())),this.register(k.buffers.onBufferActivate(()=>{var A;return(A=this._renderer.value)===null||A===void 0?void 0:A.clear()})),this.register(E.onOptionChange(()=>this._handleOptionsChanged())),this.register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this.register(v.onDecorationRegistered(()=>this._fullRefresh())),this.register(v.onDecorationRemoved(()=>this._fullRefresh())),this.register(E.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio"],()=>{this.clear(),this.handleResize(k.cols,k.rows),this._fullRefresh()})),this.register(E.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(k.buffer.y,k.buffer.y,!0))),this.register((0,d.addDisposableDomListener)(R.window,"resize",()=>this.handleDevicePixelRatioChange())),this.register(P.onChangeColors(()=>this._fullRefresh())),"IntersectionObserver"in R.window){const A=new R.window.IntersectionObserver(B=>this._handleIntersectionChange(B[B.length-1]),{threshold:0});A.observe(g),this.register({dispose:()=>A.disconnect()})}}_handleIntersectionChange(_){this._isPaused=_.isIntersecting===void 0?_.intersectionRatio===0:!_.isIntersecting,this._isPaused||this._charSizeService.hasValidSize||this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(_,g,E=!1){this._isPaused?this._needsFullRefresh=!0:(E||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(_,g,this._rowCount))}_renderRows(_,g){this._renderer.value&&(_=Math.min(_,this._rowCount-1),g=Math.min(g,this._rowCount-1),this._renderer.value.renderRows(_,g),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:_,end:g}),this._onRender.fire({start:_,end:g}),this._isNextRenderRedrawOnly=!0)}resize(_,g){this._rowCount=g,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(_){this._renderer.value=_,this._renderer.value.onRequestRedraw(g=>this.refreshRows(g.start,g.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh()}addRefreshCallback(_){return this._renderDebouncer.addRefreshCallback(_)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var _,g;this._renderer.value&&((g=(_=this._renderer.value).clearTextureAtlas)===null||g===void 0||g.call(_),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(_,g){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value.handleResize(_,g)):this._renderer.value.handleResize(_,g),this._fullRefresh())}handleCharSizeChanged(){var _;(_=this._renderer.value)===null||_===void 0||_.handleCharSizeChanged()}handleBlur(){var _;(_=this._renderer.value)===null||_===void 0||_.handleBlur()}handleFocus(){var _;(_=this._renderer.value)===null||_===void 0||_.handleFocus()}handleSelectionChanged(_,g,E){var b;this._selectionState.start=_,this._selectionState.end=g,this._selectionState.columnSelectMode=E,(b=this._renderer.value)===null||b===void 0||b.handleSelectionChanged(_,g,E)}handleCursorMove(){var _;(_=this._renderer.value)===null||_===void 0||_.handleCursorMove()}clear(){var _;(_=this._renderer.value)===null||_===void 0||_.clear()}};n.RenderService=l=f([S(2,s.IOptionsService),S(3,w.ICharSizeService),S(4,s.IDecorationService),S(5,s.IBufferService),S(6,w.ICoreBrowserService),S(7,w.IThemeService)],l)},9312:function(y,n,u){var f=this&&this.__decorate||function(v,k,R,P){var A,B=arguments.length,I=B<3?k:P===null?P=Object.getOwnPropertyDescriptor(k,R):P;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")I=Reflect.decorate(v,k,R,P);else for(var z=v.length-1;z>=0;z--)(A=v[z])&&(I=(B<3?A(I):B>3?A(k,R,I):A(k,R))||I);return B>3&&I&&Object.defineProperty(k,R,I),I},S=this&&this.__param||function(v,k){return function(R,P){k(R,P,v)}};Object.defineProperty(n,"__esModule",{value:!0}),n.SelectionService=void 0;const d=u(9806),p=u(9504),C=u(456),w=u(4725),m=u(8460),c=u(844),o=u(6114),s=u(4841),l=u(511),_=u(2585),g=" ",E=new RegExp(g,"g");let b=n.SelectionService=class extends c.Disposable{constructor(v,k,R,P,A,B,I,z,U){super(),this._element=v,this._screenElement=k,this._linkifier=R,this._bufferService=P,this._coreService=A,this._mouseService=B,this._optionsService=I,this._renderService=z,this._coreBrowserService=U,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new l.CellData,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this.register(new m.EventEmitter),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this.register(new m.EventEmitter),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this.register(new m.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this.register(new m.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=j=>this._handleMouseMove(j),this._mouseUpListener=j=>this._handleMouseUp(j),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(j=>this._handleTrim(j)),this.register(this._bufferService.buffers.onBufferActivate(j=>this._handleBufferActivate(j))),this.enable(),this._model=new C.SelectionModel(this._bufferService),this._activeSelectionMode=0,this.register((0,c.toDisposable)(()=>{this._removeMouseDownListeners()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){const v=this._model.finalSelectionStart,k=this._model.finalSelectionEnd;return!(!v||!k||v[0]===k[0]&&v[1]===k[1])}get selectionText(){const v=this._model.finalSelectionStart,k=this._model.finalSelectionEnd;if(!v||!k)return"";const R=this._bufferService.buffer,P=[];if(this._activeSelectionMode===3){if(v[0]===k[0])return"";const A=v[0]A.replace(E," ")).join(o.isWindows?`\r +`:` +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(v){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),o.isLinux&&v&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(v){const k=this._getMouseBufferCoords(v),R=this._model.finalSelectionStart,P=this._model.finalSelectionEnd;return!!(R&&P&&k)&&this._areCoordsInSelection(k,R,P)}isCellInSelection(v,k){const R=this._model.finalSelectionStart,P=this._model.finalSelectionEnd;return!(!R||!P)&&this._areCoordsInSelection([v,k],R,P)}_areCoordsInSelection(v,k,R){return v[1]>k[1]&&v[1]=k[0]&&v[0]=k[0]}_selectWordAtCursor(v,k){var R,P;const A=(P=(R=this._linkifier.currentLink)===null||R===void 0?void 0:R.link)===null||P===void 0?void 0:P.range;if(A)return this._model.selectionStart=[A.start.x-1,A.start.y-1],this._model.selectionStartLength=(0,s.getRangeLength)(A,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const B=this._getMouseBufferCoords(v);return!!B&&(this._selectWordAt(B,k),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(v,k){this._model.clearSelection(),v=Math.max(v,0),k=Math.min(k,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,v],this._model.selectionEnd=[this._bufferService.cols,k],this.refresh(),this._onSelectionChange.fire()}_handleTrim(v){this._model.handleTrim(v)&&this.refresh()}_getMouseBufferCoords(v){const k=this._mouseService.getCoords(v,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(k)return k[0]--,k[1]--,k[1]+=this._bufferService.buffer.ydisp,k}_getMouseEventScrollAmount(v){let k=(0,d.getCoordsRelativeToElement)(this._coreBrowserService.window,v,this._screenElement)[1];const R=this._renderService.dimensions.css.canvas.height;return k>=0&&k<=R?0:(k>R&&(k-=R),k=Math.min(Math.max(k,-50),50),k/=50,k/Math.abs(k)+Math.round(14*k))}shouldForceSelection(v){return o.isMac?v.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:v.shiftKey}handleMouseDown(v){if(this._mouseDownTimeStamp=v.timeStamp,(v.button!==2||!this.hasSelection)&&v.button===0){if(!this._enabled){if(!this.shouldForceSelection(v))return;v.stopPropagation()}v.preventDefault(),this._dragScrollAmount=0,this._enabled&&v.shiftKey?this._handleIncrementalClick(v):v.detail===1?this._handleSingleClick(v):v.detail===2?this._handleDoubleClick(v):v.detail===3&&this._handleTripleClick(v),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(v){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(v))}_handleSingleClick(v){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(v)?3:0,this._model.selectionStart=this._getMouseBufferCoords(v),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const k=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);k&&k.length!==this._model.selectionStart[0]&&k.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(v){this._selectWordAtCursor(v,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(v){const k=this._getMouseBufferCoords(v);k&&(this._activeSelectionMode=2,this._selectLineAt(k[1]))}shouldColumnSelect(v){return v.altKey&&!(o.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(v){if(v.stopImmediatePropagation(),!this._model.selectionStart)return;const k=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(v),!this._model.selectionEnd)return void this.refresh(!0);this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const R=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(v.ydisp+this._bufferService.rows,v.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=v.ydisp),this.refresh()}}_handleMouseUp(v){const k=v.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&k<500&&v.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const R=this._mouseService.getCoords(v,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(R&&R[0]!==void 0&&R[1]!==void 0){const P=(0,p.moveToCellSequence)(R[0]-1,R[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(P,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const v=this._model.finalSelectionStart,k=this._model.finalSelectionEnd,R=!(!v||!k||v[0]===k[0]&&v[1]===k[1]);R?v&&k&&(this._oldSelectionStart&&this._oldSelectionEnd&&v[0]===this._oldSelectionStart[0]&&v[1]===this._oldSelectionStart[1]&&k[0]===this._oldSelectionEnd[0]&&k[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(v,k,R)):this._oldHasSelection&&this._fireOnSelectionChange(v,k,R)}_fireOnSelectionChange(v,k,R){this._oldSelectionStart=v,this._oldSelectionEnd=k,this._oldHasSelection=R,this._onSelectionChange.fire()}_handleBufferActivate(v){this.clearSelection(),this._trimListener.dispose(),this._trimListener=v.activeBuffer.lines.onTrim(k=>this._handleTrim(k))}_convertViewportColToCharacterIndex(v,k){let R=k;for(let P=0;k>=P;P++){const A=v.loadCell(P,this._workCell).getChars().length;this._workCell.getWidth()===0?R--:A>1&&k!==P&&(R+=A-1)}return R}setSelection(v,k,R){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[v,k],this._model.selectionStartLength=R,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(v){this._isClickInSelection(v)||(this._selectWordAtCursor(v,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(v,k,R=!0,P=!0){if(v[0]>=this._bufferService.cols)return;const A=this._bufferService.buffer,B=A.lines.get(v[1]);if(!B)return;const I=A.translateBufferLineToString(v[1],!1);let z=this._convertViewportColToCharacterIndex(B,v[0]),U=z;const j=v[0]-z;let x=0,D=0,T=0,M=0;if(I.charAt(z)===" "){for(;z>0&&I.charAt(z-1)===" ";)z--;for(;U1&&(M+=ee-1,U+=ee-1);G>0&&z>0&&!this._isCharWordSeparator(B.loadCell(G-1,this._workCell));){B.loadCell(G-1,this._workCell);const L=this._workCell.getChars().length;this._workCell.getWidth()===0?(x++,G--):L>1&&(T+=L-1,z-=L-1),z--,G--}for(;X1&&(M+=L-1,U+=L-1),U++,X++}}U++;let F=z+j-x+T,$=Math.min(this._bufferService.cols,U-z+x+D-T-M);if(k||I.slice(z,U).trim()!==""){if(R&&F===0&&B.getCodePoint(0)!==32){const G=A.lines.get(v[1]-1);if(G&&B.isWrapped&&G.getCodePoint(this._bufferService.cols-1)!==32){const X=this._getWordAt([this._bufferService.cols-1,v[1]-1],!1,!0,!1);if(X){const ee=this._bufferService.cols-X.start;F-=ee,$+=ee}}}if(P&&F+$===this._bufferService.cols&&B.getCodePoint(this._bufferService.cols-1)!==32){const G=A.lines.get(v[1]+1);if(G!=null&&G.isWrapped&&G.getCodePoint(0)!==32){const X=this._getWordAt([0,v[1]+1],!1,!1,!0);X&&($+=X.length)}}return{start:F,length:$}}}_selectWordAt(v,k){const R=this._getWordAt(v,k);if(R){for(;R.start<0;)R.start+=this._bufferService.cols,v[1]--;this._model.selectionStart=[R.start,v[1]],this._model.selectionStartLength=R.length}}_selectToWordAt(v){const k=this._getWordAt(v,!0);if(k){let R=v[1];for(;k.start<0;)k.start+=this._bufferService.cols,R--;if(!this._model.areSelectionValuesReversed())for(;k.start+k.length>this._bufferService.cols;)k.length-=this._bufferService.cols,R++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?k.start:k.start+k.length,R]}}_isCharWordSeparator(v){return v.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(v.getChars())>=0}_selectLineAt(v){const k=this._bufferService.buffer.getWrappedRangeForLine(v),R={start:{x:0,y:k.first},end:{x:this._bufferService.cols-1,y:k.last}};this._model.selectionStart=[0,k.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,s.getRangeLength)(R,this._bufferService.cols)}};n.SelectionService=b=f([S(3,_.IBufferService),S(4,_.ICoreService),S(5,w.IMouseService),S(6,_.IOptionsService),S(7,w.IRenderService),S(8,w.ICoreBrowserService)],b)},4725:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.IThemeService=n.ICharacterJoinerService=n.ISelectionService=n.IRenderService=n.IMouseService=n.ICoreBrowserService=n.ICharSizeService=void 0;const f=u(8343);n.ICharSizeService=(0,f.createDecorator)("CharSizeService"),n.ICoreBrowserService=(0,f.createDecorator)("CoreBrowserService"),n.IMouseService=(0,f.createDecorator)("MouseService"),n.IRenderService=(0,f.createDecorator)("RenderService"),n.ISelectionService=(0,f.createDecorator)("SelectionService"),n.ICharacterJoinerService=(0,f.createDecorator)("CharacterJoinerService"),n.IThemeService=(0,f.createDecorator)("ThemeService")},6731:function(y,n,u){var f=this&&this.__decorate||function(b,v,k,R){var P,A=arguments.length,B=A<3?v:R===null?R=Object.getOwnPropertyDescriptor(v,k):R;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")B=Reflect.decorate(b,v,k,R);else for(var I=b.length-1;I>=0;I--)(P=b[I])&&(B=(A<3?P(B):A>3?P(v,k,B):P(v,k))||B);return A>3&&B&&Object.defineProperty(v,k,B),B},S=this&&this.__param||function(b,v){return function(k,R){v(k,R,b)}};Object.defineProperty(n,"__esModule",{value:!0}),n.ThemeService=n.DEFAULT_ANSI_COLORS=void 0;const d=u(7239),p=u(8055),C=u(8460),w=u(844),m=u(2585),c=p.css.toColor("#ffffff"),o=p.css.toColor("#000000"),s=p.css.toColor("#ffffff"),l=p.css.toColor("#000000"),_={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};n.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const b=[p.css.toColor("#2e3436"),p.css.toColor("#cc0000"),p.css.toColor("#4e9a06"),p.css.toColor("#c4a000"),p.css.toColor("#3465a4"),p.css.toColor("#75507b"),p.css.toColor("#06989a"),p.css.toColor("#d3d7cf"),p.css.toColor("#555753"),p.css.toColor("#ef2929"),p.css.toColor("#8ae234"),p.css.toColor("#fce94f"),p.css.toColor("#729fcf"),p.css.toColor("#ad7fa8"),p.css.toColor("#34e2e2"),p.css.toColor("#eeeeec")],v=[0,95,135,175,215,255];for(let k=0;k<216;k++){const R=v[k/36%6|0],P=v[k/6%6|0],A=v[k%6];b.push({css:p.channels.toCss(R,P,A),rgba:p.channels.toRgba(R,P,A)})}for(let k=0;k<24;k++){const R=8+10*k;b.push({css:p.channels.toCss(R,R,R),rgba:p.channels.toRgba(R,R,R)})}return b})());let g=n.ThemeService=class extends w.Disposable{get colors(){return this._colors}constructor(b){super(),this._optionsService=b,this._contrastCache=new d.ColorContrastCache,this._halfContrastCache=new d.ColorContrastCache,this._onChangeColors=this.register(new C.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:c,background:o,cursor:s,cursorAccent:l,selectionForeground:void 0,selectionBackgroundTransparent:_,selectionBackgroundOpaque:p.color.blend(o,_),selectionInactiveBackgroundTransparent:_,selectionInactiveBackgroundOpaque:p.color.blend(o,_),ansi:n.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this.register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this.register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}_setTheme(b={}){const v=this._colors;if(v.foreground=E(b.foreground,c),v.background=E(b.background,o),v.cursor=E(b.cursor,s),v.cursorAccent=E(b.cursorAccent,l),v.selectionBackgroundTransparent=E(b.selectionBackground,_),v.selectionBackgroundOpaque=p.color.blend(v.background,v.selectionBackgroundTransparent),v.selectionInactiveBackgroundTransparent=E(b.selectionInactiveBackground,v.selectionBackgroundTransparent),v.selectionInactiveBackgroundOpaque=p.color.blend(v.background,v.selectionInactiveBackgroundTransparent),v.selectionForeground=b.selectionForeground?E(b.selectionForeground,p.NULL_COLOR):void 0,v.selectionForeground===p.NULL_COLOR&&(v.selectionForeground=void 0),p.color.isOpaque(v.selectionBackgroundTransparent)&&(v.selectionBackgroundTransparent=p.color.opacity(v.selectionBackgroundTransparent,.3)),p.color.isOpaque(v.selectionInactiveBackgroundTransparent)&&(v.selectionInactiveBackgroundTransparent=p.color.opacity(v.selectionInactiveBackgroundTransparent,.3)),v.ansi=n.DEFAULT_ANSI_COLORS.slice(),v.ansi[0]=E(b.black,n.DEFAULT_ANSI_COLORS[0]),v.ansi[1]=E(b.red,n.DEFAULT_ANSI_COLORS[1]),v.ansi[2]=E(b.green,n.DEFAULT_ANSI_COLORS[2]),v.ansi[3]=E(b.yellow,n.DEFAULT_ANSI_COLORS[3]),v.ansi[4]=E(b.blue,n.DEFAULT_ANSI_COLORS[4]),v.ansi[5]=E(b.magenta,n.DEFAULT_ANSI_COLORS[5]),v.ansi[6]=E(b.cyan,n.DEFAULT_ANSI_COLORS[6]),v.ansi[7]=E(b.white,n.DEFAULT_ANSI_COLORS[7]),v.ansi[8]=E(b.brightBlack,n.DEFAULT_ANSI_COLORS[8]),v.ansi[9]=E(b.brightRed,n.DEFAULT_ANSI_COLORS[9]),v.ansi[10]=E(b.brightGreen,n.DEFAULT_ANSI_COLORS[10]),v.ansi[11]=E(b.brightYellow,n.DEFAULT_ANSI_COLORS[11]),v.ansi[12]=E(b.brightBlue,n.DEFAULT_ANSI_COLORS[12]),v.ansi[13]=E(b.brightMagenta,n.DEFAULT_ANSI_COLORS[13]),v.ansi[14]=E(b.brightCyan,n.DEFAULT_ANSI_COLORS[14]),v.ansi[15]=E(b.brightWhite,n.DEFAULT_ANSI_COLORS[15]),b.extendedAnsi){const k=Math.min(v.ansi.length-16,b.extendedAnsi.length);for(let R=0;R{Object.defineProperty(n,"__esModule",{value:!0}),n.CircularList=void 0;const f=u(8460),S=u(844);class d extends S.Disposable{constructor(C){super(),this._maxLength=C,this.onDeleteEmitter=this.register(new f.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new f.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new f.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(C){if(this._maxLength===C)return;const w=new Array(C);for(let m=0;mthis._length)for(let w=this._length;w=C;c--)this._array[this._getCyclicIndex(c+m.length)]=this._array[this._getCyclicIndex(c)];for(let c=0;cthis._maxLength){const c=this._length+m.length-this._maxLength;this._startIndex+=c,this._length=this._maxLength,this.onTrimEmitter.fire(c)}else this._length+=m.length}trimStart(C){C>this._length&&(C=this._length),this._startIndex+=C,this._length-=C,this.onTrimEmitter.fire(C)}shiftElements(C,w,m){if(!(w<=0)){if(C<0||C>=this._length)throw new Error("start argument out of range");if(C+m<0)throw new Error("Cannot shift elements in list beyond index 0");if(m>0){for(let o=w-1;o>=0;o--)this.set(C+o+m,this.get(C+o));const c=C+w+m-this._length;if(c>0)for(this._length+=c;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let c=0;c{Object.defineProperty(n,"__esModule",{value:!0}),n.clone=void 0,n.clone=function u(f,S=5){if(typeof f!="object")return f;const d=Array.isArray(f)?[]:{};for(const p in f)d[p]=S<=1?f[p]:f[p]&&u(f[p],S-1);return d}},8055:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.contrastRatio=n.toPaddedHex=n.rgba=n.rgb=n.css=n.color=n.channels=n.NULL_COLOR=void 0;const f=u(6114);let S=0,d=0,p=0,C=0;var w,m,c,o,s;function l(g){const E=g.toString(16);return E.length<2?"0"+E:E}function _(g,E){return g>>0}}(w||(n.channels=w={})),function(g){function E(b,v){return C=Math.round(255*v),[S,d,p]=s.toChannels(b.rgba),{css:w.toCss(S,d,p,C),rgba:w.toRgba(S,d,p,C)}}g.blend=function(b,v){if(C=(255&v.rgba)/255,C===1)return{css:v.css,rgba:v.rgba};const k=v.rgba>>24&255,R=v.rgba>>16&255,P=v.rgba>>8&255,A=b.rgba>>24&255,B=b.rgba>>16&255,I=b.rgba>>8&255;return S=A+Math.round((k-A)*C),d=B+Math.round((R-B)*C),p=I+Math.round((P-I)*C),{css:w.toCss(S,d,p),rgba:w.toRgba(S,d,p)}},g.isOpaque=function(b){return(255&b.rgba)==255},g.ensureContrastRatio=function(b,v,k){const R=s.ensureContrastRatio(b.rgba,v.rgba,k);if(R)return s.toColor(R>>24&255,R>>16&255,R>>8&255)},g.opaque=function(b){const v=(255|b.rgba)>>>0;return[S,d,p]=s.toChannels(v),{css:w.toCss(S,d,p),rgba:v}},g.opacity=E,g.multiplyOpacity=function(b,v){return C=255&b.rgba,E(b,C*v/255)},g.toColorRGB=function(b){return[b.rgba>>24&255,b.rgba>>16&255,b.rgba>>8&255]}}(m||(n.color=m={})),function(g){let E,b;if(!f.isNode){const v=document.createElement("canvas");v.width=1,v.height=1;const k=v.getContext("2d",{willReadFrequently:!0});k&&(E=k,E.globalCompositeOperation="copy",b=E.createLinearGradient(0,0,1,1))}g.toColor=function(v){if(v.match(/#[\da-f]{3,8}/i))switch(v.length){case 4:return S=parseInt(v.slice(1,2).repeat(2),16),d=parseInt(v.slice(2,3).repeat(2),16),p=parseInt(v.slice(3,4).repeat(2),16),s.toColor(S,d,p);case 5:return S=parseInt(v.slice(1,2).repeat(2),16),d=parseInt(v.slice(2,3).repeat(2),16),p=parseInt(v.slice(3,4).repeat(2),16),C=parseInt(v.slice(4,5).repeat(2),16),s.toColor(S,d,p,C);case 7:return{css:v,rgba:(parseInt(v.slice(1),16)<<8|255)>>>0};case 9:return{css:v,rgba:parseInt(v.slice(1),16)>>>0}}const k=v.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(k)return S=parseInt(k[1]),d=parseInt(k[2]),p=parseInt(k[3]),C=Math.round(255*(k[5]===void 0?1:parseFloat(k[5]))),s.toColor(S,d,p,C);if(!E||!b)throw new Error("css.toColor: Unsupported css format");if(E.fillStyle=b,E.fillStyle=v,typeof E.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(E.fillRect(0,0,1,1),[S,d,p,C]=E.getImageData(0,0,1,1).data,C!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:w.toRgba(S,d,p,C),css:v}}}(c||(n.css=c={})),function(g){function E(b,v,k){const R=b/255,P=v/255,A=k/255;return .2126*(R<=.03928?R/12.92:Math.pow((R+.055)/1.055,2.4))+.7152*(P<=.03928?P/12.92:Math.pow((P+.055)/1.055,2.4))+.0722*(A<=.03928?A/12.92:Math.pow((A+.055)/1.055,2.4))}g.relativeLuminance=function(b){return E(b>>16&255,b>>8&255,255&b)},g.relativeLuminance2=E}(o||(n.rgb=o={})),function(g){function E(v,k,R){const P=v>>24&255,A=v>>16&255,B=v>>8&255;let I=k>>24&255,z=k>>16&255,U=k>>8&255,j=_(o.relativeLuminance2(I,z,U),o.relativeLuminance2(P,A,B));for(;j0||z>0||U>0);)I-=Math.max(0,Math.ceil(.1*I)),z-=Math.max(0,Math.ceil(.1*z)),U-=Math.max(0,Math.ceil(.1*U)),j=_(o.relativeLuminance2(I,z,U),o.relativeLuminance2(P,A,B));return(I<<24|z<<16|U<<8|255)>>>0}function b(v,k,R){const P=v>>24&255,A=v>>16&255,B=v>>8&255;let I=k>>24&255,z=k>>16&255,U=k>>8&255,j=_(o.relativeLuminance2(I,z,U),o.relativeLuminance2(P,A,B));for(;j>>0}g.ensureContrastRatio=function(v,k,R){const P=o.relativeLuminance(v>>8),A=o.relativeLuminance(k>>8);if(_(P,A)>8));if(U_(P,o.relativeLuminance(j>>8))?z:j}return z}const B=b(v,k,R),I=_(P,o.relativeLuminance(B>>8));if(I_(P,o.relativeLuminance(z>>8))?B:z}return B}},g.reduceLuminance=E,g.increaseLuminance=b,g.toChannels=function(v){return[v>>24&255,v>>16&255,v>>8&255,255&v]},g.toColor=function(v,k,R,P){return{css:w.toCss(v,k,R,P),rgba:w.toRgba(v,k,R,P)}}}(s||(n.rgba=s={})),n.toPaddedHex=l,n.contrastRatio=_},8969:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CoreTerminal=void 0;const f=u(844),S=u(2585),d=u(4348),p=u(7866),C=u(744),w=u(7302),m=u(6975),c=u(8460),o=u(1753),s=u(1480),l=u(7994),_=u(9282),g=u(5435),E=u(5981),b=u(2660);let v=!1;class k extends f.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new c.EventEmitter),this._onScroll.event(P=>{var A;(A=this._onScrollApi)===null||A===void 0||A.fire(P.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(P){for(const A in P)this.optionsService.options[A]=P[A]}constructor(P){super(),this._windowsWrappingHeuristics=this.register(new f.MutableDisposable),this._onBinary=this.register(new c.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new c.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new c.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new c.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new c.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new c.EventEmitter),this._instantiationService=new d.InstantiationService,this.optionsService=this.register(new w.OptionsService(P)),this._instantiationService.setService(S.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(C.BufferService)),this._instantiationService.setService(S.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(p.LogService)),this._instantiationService.setService(S.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(m.CoreService)),this._instantiationService.setService(S.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(o.CoreMouseService)),this._instantiationService.setService(S.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(s.UnicodeService)),this._instantiationService.setService(S.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(l.CharsetService),this._instantiationService.setService(S.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(b.OscLinkService),this._instantiationService.setService(S.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new g.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,c.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,c.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,c.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,c.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom())),this.register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this.register(this._bufferService.onScroll(A=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this.register(this._inputHandler.onScroll(A=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this.register(new E.WriteBuffer((A,B)=>this._inputHandler.parse(A,B))),this.register((0,c.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(P,A){this._writeBuffer.write(P,A)}writeSync(P,A){this._logService.logLevel<=S.LogLevelEnum.WARN&&!v&&(this._logService.warn("writeSync is unreliable and will be removed soon."),v=!0),this._writeBuffer.writeSync(P,A)}resize(P,A){isNaN(P)||isNaN(A)||(P=Math.max(P,C.MINIMUM_COLS),A=Math.max(A,C.MINIMUM_ROWS),this._bufferService.resize(P,A))}scroll(P,A=!1){this._bufferService.scroll(P,A)}scrollLines(P,A,B){this._bufferService.scrollLines(P,A,B)}scrollPages(P){this.scrollLines(P*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(P){const A=P-this._bufferService.buffer.ydisp;A!==0&&this.scrollLines(A)}registerEscHandler(P,A){return this._inputHandler.registerEscHandler(P,A)}registerDcsHandler(P,A){return this._inputHandler.registerDcsHandler(P,A)}registerCsiHandler(P,A){return this._inputHandler.registerCsiHandler(P,A)}registerOscHandler(P,A){return this._inputHandler.registerOscHandler(P,A)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let P=!1;const A=this.optionsService.rawOptions.windowsPty;A&&A.buildNumber!==void 0&&A.buildNumber!==void 0?P=A.backend==="conpty"&&A.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(P=!0),P?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const P=[];P.push(this.onLineFeed(_.updateWindowsModeWrappedState.bind(null,this._bufferService))),P.push(this.registerCsiHandler({final:"H"},()=>((0,_.updateWindowsModeWrappedState)(this._bufferService),!1))),this._windowsWrappingHeuristics.value=(0,f.toDisposable)(()=>{for(const A of P)A.dispose()})}}}n.CoreTerminal=k},8460:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.forwardEvent=n.EventEmitter=void 0,n.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=u=>(this._listeners.push(u),{dispose:()=>{if(!this._disposed){for(let f=0;ff.fire(S))}},5435:function(y,n,u){var f=this&&this.__decorate||function(j,x,D,T){var M,F=arguments.length,$=F<3?x:T===null?T=Object.getOwnPropertyDescriptor(x,D):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")$=Reflect.decorate(j,x,D,T);else for(var G=j.length-1;G>=0;G--)(M=j[G])&&($=(F<3?M($):F>3?M(x,D,$):M(x,D))||$);return F>3&&$&&Object.defineProperty(x,D,$),$},S=this&&this.__param||function(j,x){return function(D,T){x(D,T,j)}};Object.defineProperty(n,"__esModule",{value:!0}),n.InputHandler=n.WindowsOptionsReportType=void 0;const d=u(2584),p=u(7116),C=u(2015),w=u(844),m=u(482),c=u(8437),o=u(8460),s=u(643),l=u(511),_=u(3734),g=u(2585),E=u(6242),b=u(6351),v=u(5941),k={"(":0,")":1,"*":2,"+":3,"-":1,".":2},R=131072;function P(j,x){if(j>24)return x.setWinLines||!1;switch(j){case 1:return!!x.restoreWin;case 2:return!!x.minimizeWin;case 3:return!!x.setWinPosition;case 4:return!!x.setWinSizePixels;case 5:return!!x.raiseWin;case 6:return!!x.lowerWin;case 7:return!!x.refreshWin;case 8:return!!x.setWinSizeChars;case 9:return!!x.maximizeWin;case 10:return!!x.fullscreenWin;case 11:return!!x.getWinState;case 13:return!!x.getWinPosition;case 14:return!!x.getWinSizePixels;case 15:return!!x.getScreenSizePixels;case 16:return!!x.getCellSizePixels;case 18:return!!x.getWinSizeChars;case 19:return!!x.getScreenSizeChars;case 20:return!!x.getIconTitle;case 21:return!!x.getWinTitle;case 22:return!!x.pushTitle;case 23:return!!x.popTitle;case 24:return!!x.setWinLines}return!1}var A;(function(j){j[j.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",j[j.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(A||(n.WindowsOptionsReportType=A={}));let B=0;class I extends w.Disposable{getAttrData(){return this._curAttrData}constructor(x,D,T,M,F,$,G,X,ee=new C.EscapeSequenceParser){super(),this._bufferService=x,this._charsetService=D,this._coreService=T,this._logService=M,this._optionsService=F,this._oscLinkService=$,this._coreMouseService=G,this._unicodeService=X,this._parser=ee,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new m.StringToUtf32,this._utf8Decoder=new m.Utf8ToUtf32,this._workCell=new l.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=c.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new o.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new o.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new o.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new o.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new o.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new o.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new o.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new o.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new o.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new o.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new o.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new o.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new o.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new z(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate(L=>this._activeBuffer=L.activeBuffer)),this._parser.setCsiHandlerFallback((L,O)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(L),params:O.toArray()})}),this._parser.setEscHandlerFallback(L=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(L)})}),this._parser.setExecuteHandlerFallback(L=>{this._logService.debug("Unknown EXECUTE code: ",{code:L})}),this._parser.setOscHandlerFallback((L,O,N)=>{this._logService.debug("Unknown OSC code: ",{identifier:L,action:O,data:N})}),this._parser.setDcsHandlerFallback((L,O,N)=>{O==="HOOK"&&(N=N.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(L),action:O,payload:N})}),this._parser.setPrintHandler((L,O,N)=>this.print(L,O,N)),this._parser.registerCsiHandler({final:"@"},L=>this.insertChars(L)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},L=>this.scrollLeft(L)),this._parser.registerCsiHandler({final:"A"},L=>this.cursorUp(L)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},L=>this.scrollRight(L)),this._parser.registerCsiHandler({final:"B"},L=>this.cursorDown(L)),this._parser.registerCsiHandler({final:"C"},L=>this.cursorForward(L)),this._parser.registerCsiHandler({final:"D"},L=>this.cursorBackward(L)),this._parser.registerCsiHandler({final:"E"},L=>this.cursorNextLine(L)),this._parser.registerCsiHandler({final:"F"},L=>this.cursorPrecedingLine(L)),this._parser.registerCsiHandler({final:"G"},L=>this.cursorCharAbsolute(L)),this._parser.registerCsiHandler({final:"H"},L=>this.cursorPosition(L)),this._parser.registerCsiHandler({final:"I"},L=>this.cursorForwardTab(L)),this._parser.registerCsiHandler({final:"J"},L=>this.eraseInDisplay(L,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},L=>this.eraseInDisplay(L,!0)),this._parser.registerCsiHandler({final:"K"},L=>this.eraseInLine(L,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},L=>this.eraseInLine(L,!0)),this._parser.registerCsiHandler({final:"L"},L=>this.insertLines(L)),this._parser.registerCsiHandler({final:"M"},L=>this.deleteLines(L)),this._parser.registerCsiHandler({final:"P"},L=>this.deleteChars(L)),this._parser.registerCsiHandler({final:"S"},L=>this.scrollUp(L)),this._parser.registerCsiHandler({final:"T"},L=>this.scrollDown(L)),this._parser.registerCsiHandler({final:"X"},L=>this.eraseChars(L)),this._parser.registerCsiHandler({final:"Z"},L=>this.cursorBackwardTab(L)),this._parser.registerCsiHandler({final:"`"},L=>this.charPosAbsolute(L)),this._parser.registerCsiHandler({final:"a"},L=>this.hPositionRelative(L)),this._parser.registerCsiHandler({final:"b"},L=>this.repeatPrecedingCharacter(L)),this._parser.registerCsiHandler({final:"c"},L=>this.sendDeviceAttributesPrimary(L)),this._parser.registerCsiHandler({prefix:">",final:"c"},L=>this.sendDeviceAttributesSecondary(L)),this._parser.registerCsiHandler({final:"d"},L=>this.linePosAbsolute(L)),this._parser.registerCsiHandler({final:"e"},L=>this.vPositionRelative(L)),this._parser.registerCsiHandler({final:"f"},L=>this.hVPosition(L)),this._parser.registerCsiHandler({final:"g"},L=>this.tabClear(L)),this._parser.registerCsiHandler({final:"h"},L=>this.setMode(L)),this._parser.registerCsiHandler({prefix:"?",final:"h"},L=>this.setModePrivate(L)),this._parser.registerCsiHandler({final:"l"},L=>this.resetMode(L)),this._parser.registerCsiHandler({prefix:"?",final:"l"},L=>this.resetModePrivate(L)),this._parser.registerCsiHandler({final:"m"},L=>this.charAttributes(L)),this._parser.registerCsiHandler({final:"n"},L=>this.deviceStatus(L)),this._parser.registerCsiHandler({prefix:"?",final:"n"},L=>this.deviceStatusPrivate(L)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},L=>this.softReset(L)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},L=>this.setCursorStyle(L)),this._parser.registerCsiHandler({final:"r"},L=>this.setScrollRegion(L)),this._parser.registerCsiHandler({final:"s"},L=>this.saveCursor(L)),this._parser.registerCsiHandler({final:"t"},L=>this.windowOptions(L)),this._parser.registerCsiHandler({final:"u"},L=>this.restoreCursor(L)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},L=>this.insertColumns(L)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},L=>this.deleteColumns(L)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},L=>this.selectProtected(L)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},L=>this.requestMode(L,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},L=>this.requestMode(L,!1)),this._parser.setExecuteHandler(d.C0.BEL,()=>this.bell()),this._parser.setExecuteHandler(d.C0.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(d.C0.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(d.C0.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(d.C0.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(d.C0.BS,()=>this.backspace()),this._parser.setExecuteHandler(d.C0.HT,()=>this.tab()),this._parser.setExecuteHandler(d.C0.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(d.C0.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(d.C1.IND,()=>this.index()),this._parser.setExecuteHandler(d.C1.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(d.C1.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new E.OscHandler(L=>(this.setTitle(L),this.setIconName(L),!0))),this._parser.registerOscHandler(1,new E.OscHandler(L=>this.setIconName(L))),this._parser.registerOscHandler(2,new E.OscHandler(L=>this.setTitle(L))),this._parser.registerOscHandler(4,new E.OscHandler(L=>this.setOrReportIndexedColor(L))),this._parser.registerOscHandler(8,new E.OscHandler(L=>this.setHyperlink(L))),this._parser.registerOscHandler(10,new E.OscHandler(L=>this.setOrReportFgColor(L))),this._parser.registerOscHandler(11,new E.OscHandler(L=>this.setOrReportBgColor(L))),this._parser.registerOscHandler(12,new E.OscHandler(L=>this.setOrReportCursorColor(L))),this._parser.registerOscHandler(104,new E.OscHandler(L=>this.restoreIndexedColor(L))),this._parser.registerOscHandler(110,new E.OscHandler(L=>this.restoreFgColor(L))),this._parser.registerOscHandler(111,new E.OscHandler(L=>this.restoreBgColor(L))),this._parser.registerOscHandler(112,new E.OscHandler(L=>this.restoreCursorColor(L))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(const L in p.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:L},()=>this.selectCharset("("+L)),this._parser.registerEscHandler({intermediates:")",final:L},()=>this.selectCharset(")"+L)),this._parser.registerEscHandler({intermediates:"*",final:L},()=>this.selectCharset("*"+L)),this._parser.registerEscHandler({intermediates:"+",final:L},()=>this.selectCharset("+"+L)),this._parser.registerEscHandler({intermediates:"-",final:L},()=>this.selectCharset("-"+L)),this._parser.registerEscHandler({intermediates:".",final:L},()=>this.selectCharset("."+L)),this._parser.registerEscHandler({intermediates:"/",final:L},()=>this.selectCharset("/"+L));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(L=>(this._logService.error("Parsing error: ",L),L)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new b.DcsHandler((L,O)=>this.requestStatusString(L,O)))}_preserveStack(x,D,T,M){this._parseStack.paused=!0,this._parseStack.cursorStartX=x,this._parseStack.cursorStartY=D,this._parseStack.decodedLength=T,this._parseStack.position=M}_logSlowResolvingAsync(x){this._logService.logLevel<=g.LogLevelEnum.WARN&&Promise.race([x,new Promise((D,T)=>setTimeout(()=>T("#SLOW_TIMEOUT"),5e3))]).catch(D=>{if(D!=="#SLOW_TIMEOUT")throw D;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(x,D){let T,M=this._activeBuffer.x,F=this._activeBuffer.y,$=0;const G=this._parseStack.paused;if(G){if(T=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,D))return this._logSlowResolvingAsync(T),T;M=this._parseStack.cursorStartX,F=this._parseStack.cursorStartY,this._parseStack.paused=!1,x.length>R&&($=this._parseStack.position+R)}if(this._logService.logLevel<=g.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof x=="string"?` "${x}"`:` "${Array.prototype.map.call(x,X=>String.fromCharCode(X)).join("")}"`),typeof x=="string"?x.split("").map(X=>X.charCodeAt(0)):x),this._parseBuffer.lengthR)for(let X=$;X0&&N.getWidth(this._activeBuffer.x-1)===2&&N.setCellFromCodePoint(this._activeBuffer.x-1,0,1,O.fg,O.bg,O.extended);for(let H=D;H=X){if(ee){for(;this._activeBuffer.x=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),N=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)}else if(this._activeBuffer.x=X-1,F===2)continue}if(L&&(N.insertCells(this._activeBuffer.x,F,this._activeBuffer.getNullCell(O),O),N.getWidth(X-1)===2&&N.setCellFromCodePoint(X-1,s.NULL_CELL_CODE,s.NULL_CELL_WIDTH,O.fg,O.bg,O.extended)),N.setCellFromCodePoint(this._activeBuffer.x++,M,F,O.fg,O.bg,O.extended),F>0)for(;--F;)N.setCellFromCodePoint(this._activeBuffer.x++,0,0,O.fg,O.bg,O.extended)}else N.getWidth(this._activeBuffer.x-1)?N.addCodepointToCell(this._activeBuffer.x-1,M):N.addCodepointToCell(this._activeBuffer.x-2,M)}T-D>0&&(N.loadCell(this._activeBuffer.x-1,this._workCell),this._workCell.getWidth()===2||this._workCell.getCode()>65535?this._parser.precedingCodepoint=0:this._workCell.isCombined()?this._parser.precedingCodepoint=this._workCell.getChars().charCodeAt(0):this._parser.precedingCodepoint=this._workCell.content),this._activeBuffer.x0&&N.getWidth(this._activeBuffer.x)===0&&!N.hasContent(this._activeBuffer.x)&&N.setCellFromCodePoint(this._activeBuffer.x,0,1,O.fg,O.bg,O.extended),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(x,D){return x.final!=="t"||x.prefix||x.intermediates?this._parser.registerCsiHandler(x,D):this._parser.registerCsiHandler(x,T=>!P(T.params[0],this._optionsService.rawOptions.windowOptions)||D(T))}registerDcsHandler(x,D){return this._parser.registerDcsHandler(x,new b.DcsHandler(D))}registerEscHandler(x,D){return this._parser.registerEscHandler(x,D)}registerOscHandler(x,D){return this._parser.registerOscHandler(x,new E.OscHandler(D))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var x;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&(!((x=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))===null||x===void 0)&&x.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const D=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);D.hasWidth(this._activeBuffer.x)&&!D.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const x=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-x),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(x=this._bufferService.cols-1){this._activeBuffer.x=Math.min(x,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(x,D){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=x,this._activeBuffer.y=this._activeBuffer.scrollTop+D):(this._activeBuffer.x=x,this._activeBuffer.y=D),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(x,D){this._restrictCursor(),this._setCursor(this._activeBuffer.x+x,this._activeBuffer.y+D)}cursorUp(x){const D=this._activeBuffer.y-this._activeBuffer.scrollTop;return D>=0?this._moveCursor(0,-Math.min(D,x.params[0]||1)):this._moveCursor(0,-(x.params[0]||1)),!0}cursorDown(x){const D=this._activeBuffer.scrollBottom-this._activeBuffer.y;return D>=0?this._moveCursor(0,Math.min(D,x.params[0]||1)):this._moveCursor(0,x.params[0]||1),!0}cursorForward(x){return this._moveCursor(x.params[0]||1,0),!0}cursorBackward(x){return this._moveCursor(-(x.params[0]||1),0),!0}cursorNextLine(x){return this.cursorDown(x),this._activeBuffer.x=0,!0}cursorPrecedingLine(x){return this.cursorUp(x),this._activeBuffer.x=0,!0}cursorCharAbsolute(x){return this._setCursor((x.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(x){return this._setCursor(x.length>=2?(x.params[1]||1)-1:0,(x.params[0]||1)-1),!0}charPosAbsolute(x){return this._setCursor((x.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(x){return this._moveCursor(x.params[0]||1,0),!0}linePosAbsolute(x){return this._setCursor(this._activeBuffer.x,(x.params[0]||1)-1),!0}vPositionRelative(x){return this._moveCursor(0,x.params[0]||1),!0}hVPosition(x){return this.cursorPosition(x),!0}tabClear(x){const D=x.params[0];return D===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:D===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(x){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let D=x.params[0]||1;for(;D--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(x){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let D=x.params[0]||1;for(;D--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(x){const D=x.params[0];return D===1&&(this._curAttrData.bg|=536870912),D!==2&&D!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(x,D,T,M=!1,F=!1){const $=this._activeBuffer.lines.get(this._activeBuffer.ybase+x);$.replaceCells(D,T,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData(),F),M&&($.isWrapped=!1)}_resetBufferLine(x,D=!1){const T=this._activeBuffer.lines.get(this._activeBuffer.ybase+x);T&&(T.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),D),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+x),T.isWrapped=!1)}eraseInDisplay(x,D=!1){let T;switch(this._restrictCursor(this._bufferService.cols),x.params[0]){case 0:for(T=this._activeBuffer.y,this._dirtyRowTracker.markDirty(T),this._eraseInBufferLine(T++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,D);T=this._bufferService.cols&&(this._activeBuffer.lines.get(T+1).isWrapped=!1);T--;)this._resetBufferLine(T,D);this._dirtyRowTracker.markDirty(0);break;case 2:for(T=this._bufferService.rows,this._dirtyRowTracker.markDirty(T-1);T--;)this._resetBufferLine(T,D);this._dirtyRowTracker.markDirty(0);break;case 3:const M=this._activeBuffer.lines.length-this._bufferService.rows;M>0&&(this._activeBuffer.lines.trimStart(M),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-M,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-M,0),this._onScroll.fire(0))}return!0}eraseInLine(x,D=!1){switch(this._restrictCursor(this._bufferService.cols),x.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,D);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,D);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,D)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(x){this._restrictCursor();let D=x.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(d.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(d.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(x){return x.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(d.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(d.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(x.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(d.C0.ESC+"[>83;40003;0c")),!0}_is(x){return(this._optionsService.rawOptions.termName+"").indexOf(x)===0}setMode(x){for(let D=0;Dte?1:2,H=x.params[0];return Q=H,V=D?H===2?4:H===4?N($.modes.insertMode):H===12?3:H===20?N(O.convertEol):0:H===1?N(T.applicationCursorKeys):H===3?O.windowOptions.setWinLines?X===80?2:X===132?1:0:0:H===6?N(T.origin):H===7?N(T.wraparound):H===8?3:H===9?N(M==="X10"):H===12?N(O.cursorBlink):H===25?N(!$.isCursorHidden):H===45?N(T.reverseWraparound):H===66?N(T.applicationKeypad):H===67?4:H===1e3?N(M==="VT200"):H===1002?N(M==="DRAG"):H===1003?N(M==="ANY"):H===1004?N(T.sendFocus):H===1005?4:H===1006?N(F==="SGR"):H===1015?4:H===1016?N(F==="SGR_PIXELS"):H===1048?1:H===47||H===1047||H===1049?N(ee===L):H===2004?N(T.bracketedPasteMode):0,$.triggerDataEvent(`${d.C0.ESC}[${D?"":"?"}${Q};${V}$y`),!0;var Q,V}_updateAttrColor(x,D,T,M,F){return D===2?(x|=50331648,x&=-16777216,x|=_.AttributeData.fromColorRGB([T,M,F])):D===5&&(x&=-50331904,x|=33554432|255&T),x}_extractColor(x,D,T){const M=[0,0,-1,0,0,0];let F=0,$=0;do{if(M[$+F]=x.params[D+$],x.hasSubParams(D+$)){const G=x.getSubParams(D+$);let X=0;do M[1]===5&&(F=1),M[$+X+1+F]=G[X];while(++X=2||M[1]===2&&$+F>=5)break;M[1]&&(F=1)}while(++$+D5)&&(x=1),D.extended.underlineStyle=x,D.fg|=268435456,x===0&&(D.fg&=-268435457),D.updateExtended()}_processSGR0(x){x.fg=c.DEFAULT_ATTR_DATA.fg,x.bg=c.DEFAULT_ATTR_DATA.bg,x.extended=x.extended.clone(),x.extended.underlineStyle=0,x.extended.underlineColor&=-67108864,x.updateExtended()}charAttributes(x){if(x.length===1&&x.params[0]===0)return this._processSGR0(this._curAttrData),!0;const D=x.length;let T;const M=this._curAttrData;for(let F=0;F=30&&T<=37?(M.fg&=-50331904,M.fg|=16777216|T-30):T>=40&&T<=47?(M.bg&=-50331904,M.bg|=16777216|T-40):T>=90&&T<=97?(M.fg&=-50331904,M.fg|=16777224|T-90):T>=100&&T<=107?(M.bg&=-50331904,M.bg|=16777224|T-100):T===0?this._processSGR0(M):T===1?M.fg|=134217728:T===3?M.bg|=67108864:T===4?(M.fg|=268435456,this._processUnderline(x.hasSubParams(F)?x.getSubParams(F)[0]:1,M)):T===5?M.fg|=536870912:T===7?M.fg|=67108864:T===8?M.fg|=1073741824:T===9?M.fg|=2147483648:T===2?M.bg|=134217728:T===21?this._processUnderline(2,M):T===22?(M.fg&=-134217729,M.bg&=-134217729):T===23?M.bg&=-67108865:T===24?(M.fg&=-268435457,this._processUnderline(0,M)):T===25?M.fg&=-536870913:T===27?M.fg&=-67108865:T===28?M.fg&=-1073741825:T===29?M.fg&=2147483647:T===39?(M.fg&=-67108864,M.fg|=16777215&c.DEFAULT_ATTR_DATA.fg):T===49?(M.bg&=-67108864,M.bg|=16777215&c.DEFAULT_ATTR_DATA.bg):T===38||T===48||T===58?F+=this._extractColor(x,F,M):T===53?M.bg|=1073741824:T===55?M.bg&=-1073741825:T===59?(M.extended=M.extended.clone(),M.extended.underlineColor=-1,M.updateExtended()):T===100?(M.fg&=-67108864,M.fg|=16777215&c.DEFAULT_ATTR_DATA.fg,M.bg&=-67108864,M.bg|=16777215&c.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",T);return!0}deviceStatus(x){switch(x.params[0]){case 5:this._coreService.triggerDataEvent(`${d.C0.ESC}[0n`);break;case 6:const D=this._activeBuffer.y+1,T=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${d.C0.ESC}[${D};${T}R`)}return!0}deviceStatusPrivate(x){if(x.params[0]===6){const D=this._activeBuffer.y+1,T=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${d.C0.ESC}[?${D};${T}R`)}return!0}softReset(x){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(x){const D=x.params[0]||1;switch(D){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}const T=D%2==1;return this._optionsService.options.cursorBlink=T,!0}setScrollRegion(x){const D=x.params[0]||1;let T;return(x.length<2||(T=x.params[1])>this._bufferService.rows||T===0)&&(T=this._bufferService.rows),T>D&&(this._activeBuffer.scrollTop=D-1,this._activeBuffer.scrollBottom=T-1,this._setCursor(0,0)),!0}windowOptions(x){if(!P(x.params[0],this._optionsService.rawOptions.windowOptions))return!0;const D=x.length>1?x.params[1]:0;switch(x.params[0]){case 14:D!==2&&this._onRequestWindowsOptionsReport.fire(A.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(A.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${d.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:D!==0&&D!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),D!==0&&D!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:D!==0&&D!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),D!==0&&D!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(x){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(x){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(x){return this._windowTitle=x,this._onTitleChange.fire(x),!0}setIconName(x){return this._iconName=x,!0}setOrReportIndexedColor(x){const D=[],T=x.split(";");for(;T.length>1;){const M=T.shift(),F=T.shift();if(/^\d+$/.exec(M)){const $=parseInt(M);if(U($))if(F==="?")D.push({type:0,index:$});else{const G=(0,v.parseColor)(F);G&&D.push({type:1,index:$,color:G})}}}return D.length&&this._onColor.fire(D),!0}setHyperlink(x){const D=x.split(";");return!(D.length<2)&&(D[1]?this._createHyperlink(D[0],D[1]):!D[0]&&this._finishHyperlink())}_createHyperlink(x,D){this._getCurrentLinkId()&&this._finishHyperlink();const T=x.split(":");let M;const F=T.findIndex($=>$.startsWith("id="));return F!==-1&&(M=T[F].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:M,uri:D}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(x,D){const T=x.split(";");for(let M=0;M=this._specialColors.length);++M,++D)if(T[M]==="?")this._onColor.fire([{type:0,index:this._specialColors[D]}]);else{const F=(0,v.parseColor)(T[M]);F&&this._onColor.fire([{type:1,index:this._specialColors[D],color:F}])}return!0}setOrReportFgColor(x){return this._setOrReportSpecialColor(x,0)}setOrReportBgColor(x){return this._setOrReportSpecialColor(x,1)}setOrReportCursorColor(x){return this._setOrReportSpecialColor(x,2)}restoreIndexedColor(x){if(!x)return this._onColor.fire([{type:2}]),!0;const D=[],T=x.split(";");for(let M=0;M=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){const x=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,x,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=c.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(x){return this._charsetService.setgLevel(x),!0}screenAlignmentPattern(){const x=new l.CellData;x.content=4194373,x.fg=this._curAttrData.fg,x.bg=this._curAttrData.bg,this._setCursor(0,0);for(let D=0;D(this._coreService.triggerDataEvent(`${d.C0.ESC}${F}${d.C0.ESC}\\`),!0))(x==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:x==='"p'?'P1$r61;1"p':x==="r"?`P1$r${T.scrollTop+1};${T.scrollBottom+1}r`:x==="m"?"P1$r0m":x===" q"?`P1$r${{block:2,underline:4,bar:6}[M.cursorStyle]-(M.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(x,D){this._dirtyRowTracker.markRangeDirty(x,D)}}n.InputHandler=I;let z=class{constructor(j){this._bufferService=j,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(j){jthis.end&&(this.end=j)}markRangeDirty(j,x){j>x&&(B=j,j=x,x=B),jthis.end&&(this.end=x)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function U(j){return 0<=j&&j<256}z=f([S(0,g.IBufferService)],z)},844:(y,n)=>{function u(f){for(const S of f)S.dispose();f.length=0}Object.defineProperty(n,"__esModule",{value:!0}),n.getDisposeArrayDisposable=n.disposeArray=n.toDisposable=n.MutableDisposable=n.Disposable=void 0,n.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const f of this._disposables)f.dispose();this._disposables.length=0}register(f){return this._disposables.push(f),f}unregister(f){const S=this._disposables.indexOf(f);S!==-1&&this._disposables.splice(S,1)}},n.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(f){var S;this._isDisposed||f===this._value||((S=this._value)===null||S===void 0||S.dispose(),this._value=f)}clear(){this.value=void 0}dispose(){var f;this._isDisposed=!0,(f=this._value)===null||f===void 0||f.dispose(),this._value=void 0}},n.toDisposable=function(f){return{dispose:f}},n.disposeArray=u,n.getDisposeArrayDisposable=function(f){return{dispose:()=>u(f)}}},1505:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.FourKeyMap=n.TwoKeyMap=void 0;class u{constructor(){this._data={}}set(S,d,p){this._data[S]||(this._data[S]={}),this._data[S][d]=p}get(S,d){return this._data[S]?this._data[S][d]:void 0}clear(){this._data={}}}n.TwoKeyMap=u,n.FourKeyMap=class{constructor(){this._data=new u}set(f,S,d,p,C){this._data.get(f,S)||this._data.set(f,S,new u),this._data.get(f,S).set(d,p,C)}get(f,S,d,p){var C;return(C=this._data.get(f,S))===null||C===void 0?void 0:C.get(d,p)}clear(){this._data.clear()}}},6114:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.isChromeOS=n.isLinux=n.isWindows=n.isIphone=n.isIpad=n.isMac=n.getSafariVersion=n.isSafari=n.isLegacyEdge=n.isFirefox=n.isNode=void 0,n.isNode=typeof navigator>"u";const u=n.isNode?"node":navigator.userAgent,f=n.isNode?"node":navigator.platform;n.isFirefox=u.includes("Firefox"),n.isLegacyEdge=u.includes("Edge"),n.isSafari=/^((?!chrome|android).)*safari/i.test(u),n.getSafariVersion=function(){if(!n.isSafari)return 0;const S=u.match(/Version\/(\d+)/);return S===null||S.length<2?0:parseInt(S[1])},n.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(f),n.isIpad=f==="iPad",n.isIphone=f==="iPhone",n.isWindows=["Windows","Win16","Win32","WinCE"].includes(f),n.isLinux=f.indexOf("Linux")>=0,n.isChromeOS=/\bCrOS\b/.test(u)},6106:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SortedList=void 0;let u=0;n.SortedList=class{constructor(f){this._getKey=f,this._array=[]}clear(){this._array.length=0}insert(f){this._array.length!==0?(u=this._search(this._getKey(f)),this._array.splice(u,0,f)):this._array.push(f)}delete(f){if(this._array.length===0)return!1;const S=this._getKey(f);if(S===void 0||(u=this._search(S),u===-1)||this._getKey(this._array[u])!==S)return!1;do if(this._array[u]===f)return this._array.splice(u,1),!0;while(++u=this._array.length)&&this._getKey(this._array[u])===f))do yield this._array[u];while(++u=this._array.length)&&this._getKey(this._array[u])===f))do S(this._array[u]);while(++u=S;){let p=S+d>>1;const C=this._getKey(this._array[p]);if(C>f)d=p-1;else{if(!(C0&&this._getKey(this._array[p-1])===f;)p--;return p}S=p+1}}return S}}},7226:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DebouncedIdleTask=n.IdleTaskQueue=n.PriorityTaskQueue=void 0;const f=u(6114);class S{constructor(){this._tasks=[],this._i=0}enqueue(C){this._tasks.push(C),this._start()}flush(){for(;this._io)return c-w<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(c-w))}ms`),void this._start();c=o}this.clear()}}class d extends S{_requestCallback(C){return setTimeout(()=>C(this._createDeadline(16)))}_cancelCallback(C){clearTimeout(C)}_createDeadline(C){const w=Date.now()+C;return{timeRemaining:()=>Math.max(0,w-Date.now())}}}n.PriorityTaskQueue=d,n.IdleTaskQueue=!f.isNode&&"requestIdleCallback"in window?class extends S{_requestCallback(p){return requestIdleCallback(p)}_cancelCallback(p){cancelIdleCallback(p)}}:d,n.DebouncedIdleTask=class{constructor(){this._queue=new n.IdleTaskQueue}set(p){this._queue.clear(),this._queue.enqueue(p)}flush(){this._queue.flush()}}},9282:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.updateWindowsModeWrappedState=void 0;const f=u(643);n.updateWindowsModeWrappedState=function(S){const d=S.buffer.lines.get(S.buffer.ybase+S.buffer.y-1),p=d==null?void 0:d.get(S.cols-1),C=S.buffer.lines.get(S.buffer.ybase+S.buffer.y);C&&p&&(C.isWrapped=p[f.CHAR_DATA_CODE_INDEX]!==f.NULL_CELL_CODE&&p[f.CHAR_DATA_CODE_INDEX]!==f.WHITESPACE_CELL_CODE)}},3734:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ExtendedAttrs=n.AttributeData=void 0;class u{constructor(){this.fg=0,this.bg=0,this.extended=new f}static toColorRGB(d){return[d>>>16&255,d>>>8&255,255&d]}static fromColorRGB(d){return(255&d[0])<<16|(255&d[1])<<8|255&d[2]}clone(){const d=new u;return d.fg=this.fg,d.bg=this.bg,d.extended=this.extended.clone(),d}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}}n.AttributeData=u;class f{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(d){this._ext=d}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(d){this._ext&=-469762049,this._ext|=d<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(d){this._ext&=-67108864,this._ext|=67108863&d}get urlId(){return this._urlId}set urlId(d){this._urlId=d}constructor(d=0,p=0){this._ext=0,this._urlId=0,this._ext=d,this._urlId=p}clone(){return new f(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}n.ExtendedAttrs=f},9092:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Buffer=n.MAX_BUFFER_SIZE=void 0;const f=u(6349),S=u(7226),d=u(3734),p=u(8437),C=u(4634),w=u(511),m=u(643),c=u(4863),o=u(7116);n.MAX_BUFFER_SIZE=4294967295,n.Buffer=class{constructor(s,l,_){this._hasScrollback=s,this._optionsService=l,this._bufferService=_,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=p.DEFAULT_ATTR_DATA.clone(),this.savedCharset=o.DEFAULT_CHARSET,this.markers=[],this._nullCell=w.CellData.fromCharData([0,m.NULL_CELL_CHAR,m.NULL_CELL_WIDTH,m.NULL_CELL_CODE]),this._whitespaceCell=w.CellData.fromCharData([0,m.WHITESPACE_CELL_CHAR,m.WHITESPACE_CELL_WIDTH,m.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new S.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new f.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(s){return s?(this._nullCell.fg=s.fg,this._nullCell.bg=s.bg,this._nullCell.extended=s.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new d.ExtendedAttrs),this._nullCell}getWhitespaceCell(s){return s?(this._whitespaceCell.fg=s.fg,this._whitespaceCell.bg=s.bg,this._whitespaceCell.extended=s.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new d.ExtendedAttrs),this._whitespaceCell}getBlankLine(s,l){return new p.BufferLine(this._bufferService.cols,this.getNullCell(s),l)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const s=this.ybase+this.y-this.ydisp;return s>=0&&sn.MAX_BUFFER_SIZE?n.MAX_BUFFER_SIZE:l}fillViewportRows(s){if(this.lines.length===0){s===void 0&&(s=p.DEFAULT_ATTR_DATA);let l=this._rows;for(;l--;)this.lines.push(this.getBlankLine(s))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new f.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(s,l){const _=this.getNullCell(p.DEFAULT_ATTR_DATA);let g=0;const E=this._getCorrectBufferLength(l);if(E>this.lines.maxLength&&(this.lines.maxLength=E),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+b+1?(this.ybase--,b++,this.ydisp>0&&this.ydisp--):this.lines.push(new p.BufferLine(s,_)));else for(let v=this._rows;v>l;v--)this.lines.length>l+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(E0&&(this.lines.trimStart(v),this.ybase=Math.max(this.ybase-v,0),this.ydisp=Math.max(this.ydisp-v,0),this.savedY=Math.max(this.savedY-v,0)),this.lines.maxLength=E}this.x=Math.min(this.x,s-1),this.y=Math.min(this.y,l-1),b&&(this.y+=b),this.savedX=Math.min(this.savedX,s-1),this.scrollTop=0}if(this.scrollBottom=l-1,this._isReflowEnabled&&(this._reflow(s,l),this._cols>s))for(let b=0;b.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let s=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,s=!1);let l=0;for(;this._memoryCleanupPosition100)return!0;return s}get _isReflowEnabled(){const s=this._optionsService.rawOptions.windowsPty;return s&&s.buildNumber?this._hasScrollback&&s.backend==="conpty"&&s.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(s,l){this._cols!==s&&(s>this._cols?this._reflowLarger(s,l):this._reflowSmaller(s,l))}_reflowLarger(s,l){const _=(0,C.reflowLargerGetLinesToRemove)(this.lines,this._cols,s,this.ybase+this.y,this.getNullCell(p.DEFAULT_ATTR_DATA));if(_.length>0){const g=(0,C.reflowLargerCreateNewLayout)(this.lines,_);(0,C.reflowLargerApplyNewLayout)(this.lines,g.layout),this._reflowLargerAdjustViewport(s,l,g.countRemoved)}}_reflowLargerAdjustViewport(s,l,_){const g=this.getNullCell(p.DEFAULT_ATTR_DATA);let E=_;for(;E-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;b--){let v=this.lines.get(b);if(!v||!v.isWrapped&&v.getTrimmedLength()<=s)continue;const k=[v];for(;v.isWrapped&&b>0;)v=this.lines.get(--b),k.unshift(v);const R=this.ybase+this.y;if(R>=b&&R0&&(g.push({start:b+k.length+E,newLines:z}),E+=z.length),k.push(...z);let U=A.length-1,j=A[U];j===0&&(U--,j=A[U]);let x=k.length-B-1,D=P;for(;x>=0;){const M=Math.min(D,j);if(k[U]===void 0)break;if(k[U].copyCellsFrom(k[x],D-M,j-M,M,!0),j-=M,j===0&&(U--,j=A[U]),D-=M,D===0){x--;const F=Math.max(x,0);D=(0,C.getWrappedLineTrimmedLength)(k,F,this._cols)}}for(let M=0;M0;)this.ybase===0?this.y0){const b=[],v=[];for(let U=0;U=0;U--)if(A&&A.start>R+B){for(let j=A.newLines.length-1;j>=0;j--)this.lines.set(U--,A.newLines[j]);U++,b.push({index:R+1,amount:A.newLines.length}),B+=A.newLines.length,A=g[++P]}else this.lines.set(U,v[R--]);let I=0;for(let U=b.length-1;U>=0;U--)b[U].index+=I,this.lines.onInsertEmitter.fire(b[U]),I+=b[U].amount;const z=Math.max(0,k+E-this.lines.maxLength);z>0&&this.lines.onTrimEmitter.fire(z)}}translateBufferLineToString(s,l,_=0,g){const E=this.lines.get(s);return E?E.translateToString(l,_,g):""}getWrappedRangeForLine(s){let l=s,_=s;for(;l>0&&this.lines.get(l).isWrapped;)l--;for(;_+10;);return s>=this._cols?this._cols-1:s<0?0:s}nextStop(s){for(s==null&&(s=this.x);!this.tabs[++s]&&s=this._cols?this._cols-1:s<0?0:s}clearMarkers(s){this._isClearing=!0;for(let l=0;l{l.line-=_,l.line<0&&l.dispose()})),l.register(this.lines.onInsert(_=>{l.line>=_.index&&(l.line+=_.amount)})),l.register(this.lines.onDelete(_=>{l.line>=_.index&&l.line<_.index+_.amount&&l.dispose(),l.line>_.index&&(l.line-=_.amount)})),l.register(l.onDispose(()=>this._removeMarker(l))),l}_removeMarker(s){this._isClearing||this.markers.splice(this.markers.indexOf(s),1)}}},8437:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferLine=n.DEFAULT_ATTR_DATA=void 0;const f=u(3734),S=u(511),d=u(643),p=u(482);n.DEFAULT_ATTR_DATA=Object.freeze(new f.AttributeData);let C=0;class w{constructor(c,o,s=!1){this.isWrapped=s,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*c);const l=o||S.CellData.fromCharData([0,d.NULL_CELL_CHAR,d.NULL_CELL_WIDTH,d.NULL_CELL_CODE]);for(let _=0;_>22,2097152&o?this._combined[c].charCodeAt(this._combined[c].length-1):s]}set(c,o){this._data[3*c+1]=o[d.CHAR_DATA_ATTR_INDEX],o[d.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[c]=o[1],this._data[3*c+0]=2097152|c|o[d.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*c+0]=o[d.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|o[d.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(c){return this._data[3*c+0]>>22}hasWidth(c){return 12582912&this._data[3*c+0]}getFg(c){return this._data[3*c+1]}getBg(c){return this._data[3*c+2]}hasContent(c){return 4194303&this._data[3*c+0]}getCodePoint(c){const o=this._data[3*c+0];return 2097152&o?this._combined[c].charCodeAt(this._combined[c].length-1):2097151&o}isCombined(c){return 2097152&this._data[3*c+0]}getString(c){const o=this._data[3*c+0];return 2097152&o?this._combined[c]:2097151&o?(0,p.stringFromCodePoint)(2097151&o):""}isProtected(c){return 536870912&this._data[3*c+2]}loadCell(c,o){return C=3*c,o.content=this._data[C+0],o.fg=this._data[C+1],o.bg=this._data[C+2],2097152&o.content&&(o.combinedData=this._combined[c]),268435456&o.bg&&(o.extended=this._extendedAttrs[c]),o}setCell(c,o){2097152&o.content&&(this._combined[c]=o.combinedData),268435456&o.bg&&(this._extendedAttrs[c]=o.extended),this._data[3*c+0]=o.content,this._data[3*c+1]=o.fg,this._data[3*c+2]=o.bg}setCellFromCodePoint(c,o,s,l,_,g){268435456&_&&(this._extendedAttrs[c]=g),this._data[3*c+0]=o|s<<22,this._data[3*c+1]=l,this._data[3*c+2]=_}addCodepointToCell(c,o){let s=this._data[3*c+0];2097152&s?this._combined[c]+=(0,p.stringFromCodePoint)(o):(2097151&s?(this._combined[c]=(0,p.stringFromCodePoint)(2097151&s)+(0,p.stringFromCodePoint)(o),s&=-2097152,s|=2097152):s=o|4194304,this._data[3*c+0]=s)}insertCells(c,o,s,l){if((c%=this.length)&&this.getWidth(c-1)===2&&this.setCellFromCodePoint(c-1,0,1,(l==null?void 0:l.fg)||0,(l==null?void 0:l.bg)||0,(l==null?void 0:l.extended)||new f.ExtendedAttrs),o=0;--g)this.setCell(c+o+g,this.loadCell(c+g,_));for(let g=0;gthis.length){if(this._data.buffer.byteLength>=4*s)this._data=new Uint32Array(this._data.buffer,0,s);else{const l=new Uint32Array(s);l.set(this._data),this._data=l}for(let l=this.length;l=c&&delete this._combined[E]}const _=Object.keys(this._extendedAttrs);for(let g=0;g<_.length;g++){const E=parseInt(_[g],10);E>=c&&delete this._extendedAttrs[E]}}return this.length=c,4*s*2=0;--c)if(4194303&this._data[3*c+0])return c+(this._data[3*c+0]>>22);return 0}getNoBgTrimmedLength(){for(let c=this.length-1;c>=0;--c)if(4194303&this._data[3*c+0]||50331648&this._data[3*c+2])return c+(this._data[3*c+0]>>22);return 0}copyCellsFrom(c,o,s,l,_){const g=c._data;if(_)for(let b=l-1;b>=0;b--){for(let v=0;v<3;v++)this._data[3*(s+b)+v]=g[3*(o+b)+v];268435456&g[3*(o+b)+2]&&(this._extendedAttrs[s+b]=c._extendedAttrs[o+b])}else for(let b=0;b=o&&(this._combined[v-o+s]=c._combined[v])}}translateToString(c=!1,o=0,s=this.length){c&&(s=Math.min(s,this.getTrimmedLength()));let l="";for(;o>22||1}return l}}n.BufferLine=w},4841:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.getRangeLength=void 0,n.getRangeLength=function(u,f){if(u.start.y>u.end.y)throw new Error(`Buffer range end (${u.end.x}, ${u.end.y}) cannot be before start (${u.start.x}, ${u.start.y})`);return f*(u.end.y-u.start.y)+(u.end.x-u.start.x+1)}},4634:(y,n)=>{function u(f,S,d){if(S===f.length-1)return f[S].getTrimmedLength();const p=!f[S].hasContent(d-1)&&f[S].getWidth(d-1)===1,C=f[S+1].getWidth(0)===2;return p&&C?d-1:d}Object.defineProperty(n,"__esModule",{value:!0}),n.getWrappedLineTrimmedLength=n.reflowSmallerGetNewLineLengths=n.reflowLargerApplyNewLayout=n.reflowLargerCreateNewLayout=n.reflowLargerGetLinesToRemove=void 0,n.reflowLargerGetLinesToRemove=function(f,S,d,p,C){const w=[];for(let m=0;m=m&&p0&&(v>l||s[v].getTrimmedLength()===0);v--)b++;b>0&&(w.push(m+s.length-b),w.push(b)),m+=s.length-1}return w},n.reflowLargerCreateNewLayout=function(f,S){const d=[];let p=0,C=S[p],w=0;for(let m=0;mu(f,s,S)).reduce((o,s)=>o+s);let w=0,m=0,c=0;for(;co&&(w-=o,m++);const s=f[m].getWidth(w-1)===2;s&&w--;const l=s?d-1:d;p.push(l),c+=l}return p},n.getWrappedLineTrimmedLength=u},5295:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferSet=void 0;const f=u(8460),S=u(844),d=u(9092);class p extends S.Disposable{constructor(w,m){super(),this._optionsService=w,this._bufferService=m,this._onBufferActivate=this.register(new f.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this.register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new d.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new d.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(w){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(w),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(w,m){this._normal.resize(w,m),this._alt.resize(w,m),this.setupTabStops(w)}setupTabStops(w){this._normal.setupTabStops(w),this._alt.setupTabStops(w)}}n.BufferSet=p},511:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CellData=void 0;const f=u(482),S=u(643),d=u(3734);class p extends d.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new d.ExtendedAttrs,this.combinedData=""}static fromCharData(w){const m=new p;return m.setFromCharData(w),m}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,f.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(w){this.fg=w[S.CHAR_DATA_ATTR_INDEX],this.bg=0;let m=!1;if(w[S.CHAR_DATA_CHAR_INDEX].length>2)m=!0;else if(w[S.CHAR_DATA_CHAR_INDEX].length===2){const c=w[S.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=c&&c<=56319){const o=w[S.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=o&&o<=57343?this.content=1024*(c-55296)+o-56320+65536|w[S.CHAR_DATA_WIDTH_INDEX]<<22:m=!0}else m=!0}else this.content=w[S.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|w[S.CHAR_DATA_WIDTH_INDEX]<<22;m&&(this.combinedData=w[S.CHAR_DATA_CHAR_INDEX],this.content=2097152|w[S.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}n.CellData=p},643:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WHITESPACE_CELL_CODE=n.WHITESPACE_CELL_WIDTH=n.WHITESPACE_CELL_CHAR=n.NULL_CELL_CODE=n.NULL_CELL_WIDTH=n.NULL_CELL_CHAR=n.CHAR_DATA_CODE_INDEX=n.CHAR_DATA_WIDTH_INDEX=n.CHAR_DATA_CHAR_INDEX=n.CHAR_DATA_ATTR_INDEX=n.DEFAULT_EXT=n.DEFAULT_ATTR=n.DEFAULT_COLOR=void 0,n.DEFAULT_COLOR=0,n.DEFAULT_ATTR=256|n.DEFAULT_COLOR<<9,n.DEFAULT_EXT=0,n.CHAR_DATA_ATTR_INDEX=0,n.CHAR_DATA_CHAR_INDEX=1,n.CHAR_DATA_WIDTH_INDEX=2,n.CHAR_DATA_CODE_INDEX=3,n.NULL_CELL_CHAR="",n.NULL_CELL_WIDTH=1,n.NULL_CELL_CODE=0,n.WHITESPACE_CELL_CHAR=" ",n.WHITESPACE_CELL_WIDTH=1,n.WHITESPACE_CELL_CODE=32},4863:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Marker=void 0;const f=u(8460),S=u(844);class d{get id(){return this._id}constructor(C){this.line=C,this.isDisposed=!1,this._disposables=[],this._id=d._nextId++,this._onDispose=this.register(new f.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,S.disposeArray)(this._disposables),this._disposables.length=0)}register(C){return this._disposables.push(C),C}}n.Marker=d,d._nextId=1},7116:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DEFAULT_CHARSET=n.CHARSETS=void 0,n.CHARSETS={},n.DEFAULT_CHARSET=n.CHARSETS.B,n.CHARSETS[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},n.CHARSETS.A={"#":"£"},n.CHARSETS.B=void 0,n.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},n.CHARSETS.C=n.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},n.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},n.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},n.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},n.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},n.CHARSETS.E=n.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},n.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},n.CHARSETS.H=n.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},n.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},2584:(y,n)=>{var u,f,S;Object.defineProperty(n,"__esModule",{value:!0}),n.C1_ESCAPED=n.C1=n.C0=void 0,function(d){d.NUL="\0",d.SOH="",d.STX="",d.ETX="",d.EOT="",d.ENQ="",d.ACK="",d.BEL="\x07",d.BS="\b",d.HT=" ",d.LF=` +`,d.VT="\v",d.FF="\f",d.CR="\r",d.SO="",d.SI="",d.DLE="",d.DC1="",d.DC2="",d.DC3="",d.DC4="",d.NAK="",d.SYN="",d.ETB="",d.CAN="",d.EM="",d.SUB="",d.ESC="\x1B",d.FS="",d.GS="",d.RS="",d.US="",d.SP=" ",d.DEL=""}(u||(n.C0=u={})),function(d){d.PAD="€",d.HOP="",d.BPH="‚",d.NBH="ƒ",d.IND="„",d.NEL="…",d.SSA="†",d.ESA="‡",d.HTS="ˆ",d.HTJ="‰",d.VTS="Š",d.PLD="‹",d.PLU="Œ",d.RI="",d.SS2="Ž",d.SS3="",d.DCS="",d.PU1="‘",d.PU2="’",d.STS="“",d.CCH="”",d.MW="•",d.SPA="–",d.EPA="—",d.SOS="˜",d.SGCI="™",d.SCI="š",d.CSI="›",d.ST="œ",d.OSC="",d.PM="ž",d.APC="Ÿ"}(f||(n.C1=f={})),function(d){d.ST=`${u.ESC}\\`}(S||(n.C1_ESCAPED=S={}))},7399:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.evaluateKeyboardEvent=void 0;const f=u(2584),S={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};n.evaluateKeyboardEvent=function(d,p,C,w){const m={type:0,cancel:!1,key:void 0},c=(d.shiftKey?1:0)|(d.altKey?2:0)|(d.ctrlKey?4:0)|(d.metaKey?8:0);switch(d.keyCode){case 0:d.key==="UIKeyInputUpArrow"?m.key=p?f.C0.ESC+"OA":f.C0.ESC+"[A":d.key==="UIKeyInputLeftArrow"?m.key=p?f.C0.ESC+"OD":f.C0.ESC+"[D":d.key==="UIKeyInputRightArrow"?m.key=p?f.C0.ESC+"OC":f.C0.ESC+"[C":d.key==="UIKeyInputDownArrow"&&(m.key=p?f.C0.ESC+"OB":f.C0.ESC+"[B");break;case 8:if(d.altKey){m.key=f.C0.ESC+f.C0.DEL;break}m.key=f.C0.DEL;break;case 9:if(d.shiftKey){m.key=f.C0.ESC+"[Z";break}m.key=f.C0.HT,m.cancel=!0;break;case 13:m.key=d.altKey?f.C0.ESC+f.C0.CR:f.C0.CR,m.cancel=!0;break;case 27:m.key=f.C0.ESC,d.altKey&&(m.key=f.C0.ESC+f.C0.ESC),m.cancel=!0;break;case 37:if(d.metaKey)break;c?(m.key=f.C0.ESC+"[1;"+(c+1)+"D",m.key===f.C0.ESC+"[1;3D"&&(m.key=f.C0.ESC+(C?"b":"[1;5D"))):m.key=p?f.C0.ESC+"OD":f.C0.ESC+"[D";break;case 39:if(d.metaKey)break;c?(m.key=f.C0.ESC+"[1;"+(c+1)+"C",m.key===f.C0.ESC+"[1;3C"&&(m.key=f.C0.ESC+(C?"f":"[1;5C"))):m.key=p?f.C0.ESC+"OC":f.C0.ESC+"[C";break;case 38:if(d.metaKey)break;c?(m.key=f.C0.ESC+"[1;"+(c+1)+"A",C||m.key!==f.C0.ESC+"[1;3A"||(m.key=f.C0.ESC+"[1;5A")):m.key=p?f.C0.ESC+"OA":f.C0.ESC+"[A";break;case 40:if(d.metaKey)break;c?(m.key=f.C0.ESC+"[1;"+(c+1)+"B",C||m.key!==f.C0.ESC+"[1;3B"||(m.key=f.C0.ESC+"[1;5B")):m.key=p?f.C0.ESC+"OB":f.C0.ESC+"[B";break;case 45:d.shiftKey||d.ctrlKey||(m.key=f.C0.ESC+"[2~");break;case 46:m.key=c?f.C0.ESC+"[3;"+(c+1)+"~":f.C0.ESC+"[3~";break;case 36:m.key=c?f.C0.ESC+"[1;"+(c+1)+"H":p?f.C0.ESC+"OH":f.C0.ESC+"[H";break;case 35:m.key=c?f.C0.ESC+"[1;"+(c+1)+"F":p?f.C0.ESC+"OF":f.C0.ESC+"[F";break;case 33:d.shiftKey?m.type=2:d.ctrlKey?m.key=f.C0.ESC+"[5;"+(c+1)+"~":m.key=f.C0.ESC+"[5~";break;case 34:d.shiftKey?m.type=3:d.ctrlKey?m.key=f.C0.ESC+"[6;"+(c+1)+"~":m.key=f.C0.ESC+"[6~";break;case 112:m.key=c?f.C0.ESC+"[1;"+(c+1)+"P":f.C0.ESC+"OP";break;case 113:m.key=c?f.C0.ESC+"[1;"+(c+1)+"Q":f.C0.ESC+"OQ";break;case 114:m.key=c?f.C0.ESC+"[1;"+(c+1)+"R":f.C0.ESC+"OR";break;case 115:m.key=c?f.C0.ESC+"[1;"+(c+1)+"S":f.C0.ESC+"OS";break;case 116:m.key=c?f.C0.ESC+"[15;"+(c+1)+"~":f.C0.ESC+"[15~";break;case 117:m.key=c?f.C0.ESC+"[17;"+(c+1)+"~":f.C0.ESC+"[17~";break;case 118:m.key=c?f.C0.ESC+"[18;"+(c+1)+"~":f.C0.ESC+"[18~";break;case 119:m.key=c?f.C0.ESC+"[19;"+(c+1)+"~":f.C0.ESC+"[19~";break;case 120:m.key=c?f.C0.ESC+"[20;"+(c+1)+"~":f.C0.ESC+"[20~";break;case 121:m.key=c?f.C0.ESC+"[21;"+(c+1)+"~":f.C0.ESC+"[21~";break;case 122:m.key=c?f.C0.ESC+"[23;"+(c+1)+"~":f.C0.ESC+"[23~";break;case 123:m.key=c?f.C0.ESC+"[24;"+(c+1)+"~":f.C0.ESC+"[24~";break;default:if(!d.ctrlKey||d.shiftKey||d.altKey||d.metaKey)if(C&&!w||!d.altKey||d.metaKey)!C||d.altKey||d.ctrlKey||d.shiftKey||!d.metaKey?d.key&&!d.ctrlKey&&!d.altKey&&!d.metaKey&&d.keyCode>=48&&d.key.length===1?m.key=d.key:d.key&&d.ctrlKey&&(d.key==="_"&&(m.key=f.C0.US),d.key==="@"&&(m.key=f.C0.NUL)):d.keyCode===65&&(m.type=1);else{const o=S[d.keyCode],s=o==null?void 0:o[d.shiftKey?1:0];if(s)m.key=f.C0.ESC+s;else if(d.keyCode>=65&&d.keyCode<=90){const l=d.ctrlKey?d.keyCode-64:d.keyCode+32;let _=String.fromCharCode(l);d.shiftKey&&(_=_.toUpperCase()),m.key=f.C0.ESC+_}else if(d.keyCode===32)m.key=f.C0.ESC+(d.ctrlKey?f.C0.NUL:" ");else if(d.key==="Dead"&&d.code.startsWith("Key")){let l=d.code.slice(3,4);d.shiftKey||(l=l.toLowerCase()),m.key=f.C0.ESC+l,m.cancel=!0}}else d.keyCode>=65&&d.keyCode<=90?m.key=String.fromCharCode(d.keyCode-64):d.keyCode===32?m.key=f.C0.NUL:d.keyCode>=51&&d.keyCode<=55?m.key=String.fromCharCode(d.keyCode-51+27):d.keyCode===56?m.key=f.C0.DEL:d.keyCode===219?m.key=f.C0.ESC:d.keyCode===220?m.key=f.C0.FS:d.keyCode===221&&(m.key=f.C0.GS)}return m}},482:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Utf8ToUtf32=n.StringToUtf32=n.utf32ToString=n.stringFromCodePoint=void 0,n.stringFromCodePoint=function(u){return u>65535?(u-=65536,String.fromCharCode(55296+(u>>10))+String.fromCharCode(u%1024+56320)):String.fromCharCode(u)},n.utf32ToString=function(u,f=0,S=u.length){let d="";for(let p=f;p65535?(C-=65536,d+=String.fromCharCode(55296+(C>>10))+String.fromCharCode(C%1024+56320)):d+=String.fromCharCode(C)}return d},n.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(u,f){const S=u.length;if(!S)return 0;let d=0,p=0;if(this._interim){const C=u.charCodeAt(p++);56320<=C&&C<=57343?f[d++]=1024*(this._interim-55296)+C-56320+65536:(f[d++]=this._interim,f[d++]=C),this._interim=0}for(let C=p;C=S)return this._interim=w,d;const m=u.charCodeAt(C);56320<=m&&m<=57343?f[d++]=1024*(w-55296)+m-56320+65536:(f[d++]=w,f[d++]=m)}else w!==65279&&(f[d++]=w)}return d}},n.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(u,f){const S=u.length;if(!S)return 0;let d,p,C,w,m=0,c=0,o=0;if(this.interim[0]){let _=!1,g=this.interim[0];g&=(224&g)==192?31:(240&g)==224?15:7;let E,b=0;for(;(E=63&this.interim[++b])&&b<4;)g<<=6,g|=E;const v=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,k=v-b;for(;o=S)return 0;if(E=u[o++],(192&E)!=128){o--,_=!0;break}this.interim[b++]=E,g<<=6,g|=63&E}_||(v===2?g<128?o--:f[m++]=g:v===3?g<2048||g>=55296&&g<=57343||g===65279||(f[m++]=g):g<65536||g>1114111||(f[m++]=g)),this.interim.fill(0)}const s=S-4;let l=o;for(;l=S)return this.interim[0]=d,m;if(p=u[l++],(192&p)!=128){l--;continue}if(c=(31&d)<<6|63&p,c<128){l--;continue}f[m++]=c}else if((240&d)==224){if(l>=S)return this.interim[0]=d,m;if(p=u[l++],(192&p)!=128){l--;continue}if(l>=S)return this.interim[0]=d,this.interim[1]=p,m;if(C=u[l++],(192&C)!=128){l--;continue}if(c=(15&d)<<12|(63&p)<<6|63&C,c<2048||c>=55296&&c<=57343||c===65279)continue;f[m++]=c}else if((248&d)==240){if(l>=S)return this.interim[0]=d,m;if(p=u[l++],(192&p)!=128){l--;continue}if(l>=S)return this.interim[0]=d,this.interim[1]=p,m;if(C=u[l++],(192&C)!=128){l--;continue}if(l>=S)return this.interim[0]=d,this.interim[1]=p,this.interim[2]=C,m;if(w=u[l++],(192&w)!=128){l--;continue}if(c=(7&d)<<18|(63&p)<<12|(63&C)<<6|63&w,c<65536||c>1114111)continue;f[m++]=c}}return m}}},225:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeV6=void 0;const u=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],f=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];let S;n.UnicodeV6=class{constructor(){if(this.version="6",!S){S=new Uint8Array(65536),S.fill(1),S[0]=0,S.fill(0,1,32),S.fill(0,127,160),S.fill(2,4352,4448),S[9001]=2,S[9002]=2,S.fill(2,11904,42192),S[12351]=1,S.fill(2,44032,55204),S.fill(2,63744,64256),S.fill(2,65040,65050),S.fill(2,65072,65136),S.fill(2,65280,65377),S.fill(2,65504,65511);for(let d=0;dC[c][1])return!1;for(;c>=m;)if(w=m+c>>1,p>C[w][1])m=w+1;else{if(!(p=131072&&d<=196605||d>=196608&&d<=262141?2:1}}},5981:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WriteBuffer=void 0;const f=u(8460),S=u(844);class d extends S.Disposable{constructor(C){super(),this._action=C,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new f.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(C,w){if(w!==void 0&&this._syncCalls>w)return void(this._syncCalls=0);if(this._pendingData+=C.length,this._writeBuffer.push(C),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let m;for(this._isSyncWriting=!0;m=this._writeBuffer.shift();){this._action(m);const c=this._callbacks.shift();c&&c()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(C,w){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=C.length,this._writeBuffer.push(C),this._callbacks.push(w),void this._innerWrite();setTimeout(()=>this._innerWrite())}this._pendingData+=C.length,this._writeBuffer.push(C),this._callbacks.push(w)}_innerWrite(C=0,w=!0){const m=C||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const c=this._writeBuffer[this._bufferOffset],o=this._action(c,w);if(o){const l=_=>Date.now()-m>=12?setTimeout(()=>this._innerWrite(0,_)):this._innerWrite(m,_);return void o.catch(_=>(queueMicrotask(()=>{throw _}),Promise.resolve(!1))).then(l)}const s=this._callbacks[this._bufferOffset];if(s&&s(),this._bufferOffset++,this._pendingData-=c.length,Date.now()-m>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}n.WriteBuffer=d},5941:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.toRgbString=n.parseColor=void 0;const u=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,f=/^[\da-f]+$/;function S(d,p){const C=d.toString(16),w=C.length<2?"0"+C:C;switch(p){case 4:return C[0];case 8:return w;case 12:return(w+w).slice(0,3);default:return w+w}}n.parseColor=function(d){if(!d)return;let p=d.toLowerCase();if(p.indexOf("rgb:")===0){p=p.slice(4);const C=u.exec(p);if(C){const w=C[1]?15:C[4]?255:C[7]?4095:65535;return[Math.round(parseInt(C[1]||C[4]||C[7]||C[10],16)/w*255),Math.round(parseInt(C[2]||C[5]||C[8]||C[11],16)/w*255),Math.round(parseInt(C[3]||C[6]||C[9]||C[12],16)/w*255)]}}else if(p.indexOf("#")===0&&(p=p.slice(1),f.exec(p)&&[3,6,9,12].includes(p.length))){const C=p.length/3,w=[0,0,0];for(let m=0;m<3;++m){const c=parseInt(p.slice(C*m,C*m+C),16);w[m]=C===1?c<<4:C===2?c:C===3?c>>4:c>>8}return w}},n.toRgbString=function(d,p=16){const[C,w,m]=d;return`rgb:${S(C,p)}/${S(w,p)}/${S(m,p)}`}},5770:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.PAYLOAD_LIMIT=void 0,n.PAYLOAD_LIMIT=1e7},6351:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DcsHandler=n.DcsParser=void 0;const f=u(482),S=u(8742),d=u(5770),p=[];n.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=p,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=p}registerHandler(w,m){this._handlers[w]===void 0&&(this._handlers[w]=[]);const c=this._handlers[w];return c.push(m),{dispose:()=>{const o=c.indexOf(m);o!==-1&&c.splice(o,1)}}}clearHandler(w){this._handlers[w]&&delete this._handlers[w]}setHandlerFallback(w){this._handlerFb=w}reset(){if(this._active.length)for(let w=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;w>=0;--w)this._active[w].unhook(!1);this._stack.paused=!1,this._active=p,this._ident=0}hook(w,m){if(this.reset(),this._ident=w,this._active=this._handlers[w]||p,this._active.length)for(let c=this._active.length-1;c>=0;c--)this._active[c].hook(m);else this._handlerFb(this._ident,"HOOK",m)}put(w,m,c){if(this._active.length)for(let o=this._active.length-1;o>=0;o--)this._active[o].put(w,m,c);else this._handlerFb(this._ident,"PUT",(0,f.utf32ToString)(w,m,c))}unhook(w,m=!0){if(this._active.length){let c=!1,o=this._active.length-1,s=!1;if(this._stack.paused&&(o=this._stack.loopPosition-1,c=m,s=this._stack.fallThrough,this._stack.paused=!1),!s&&c===!1){for(;o>=0&&(c=this._active[o].unhook(w),c!==!0);o--)if(c instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=o,this._stack.fallThrough=!1,c;o--}for(;o>=0;o--)if(c=this._active[o].unhook(!1),c instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=o,this._stack.fallThrough=!0,c}else this._handlerFb(this._ident,"UNHOOK",w);this._active=p,this._ident=0}};const C=new S.Params;C.addParam(0),n.DcsHandler=class{constructor(w){this._handler=w,this._data="",this._params=C,this._hitLimit=!1}hook(w){this._params=w.length>1||w.params[0]?w.clone():C,this._data="",this._hitLimit=!1}put(w,m,c){this._hitLimit||(this._data+=(0,f.utf32ToString)(w,m,c),this._data.length>d.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(w){let m=!1;if(this._hitLimit)m=!1;else if(w&&(m=this._handler(this._data,this._params),m instanceof Promise))return m.then(c=>(this._params=C,this._data="",this._hitLimit=!1,c));return this._params=C,this._data="",this._hitLimit=!1,m}}},2015:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.EscapeSequenceParser=n.VT500_TRANSITION_TABLE=n.TransitionTable=void 0;const f=u(844),S=u(8742),d=u(6242),p=u(6351);class C{constructor(o){this.table=new Uint8Array(o)}setDefault(o,s){this.table.fill(o<<4|s)}add(o,s,l,_){this.table[s<<8|o]=l<<4|_}addMany(o,s,l,_){for(let g=0;gv),s=(b,v)=>o.slice(b,v),l=s(32,127),_=s(0,24);_.push(25),_.push.apply(_,s(28,32));const g=s(0,14);let E;for(E in c.setDefault(1,0),c.addMany(l,0,2,0),g)c.addMany([24,26,153,154],E,3,0),c.addMany(s(128,144),E,3,0),c.addMany(s(144,152),E,3,0),c.add(156,E,0,0),c.add(27,E,11,1),c.add(157,E,4,8),c.addMany([152,158,159],E,0,7),c.add(155,E,11,3),c.add(144,E,11,9);return c.addMany(_,0,3,0),c.addMany(_,1,3,1),c.add(127,1,0,1),c.addMany(_,8,0,8),c.addMany(_,3,3,3),c.add(127,3,0,3),c.addMany(_,4,3,4),c.add(127,4,0,4),c.addMany(_,6,3,6),c.addMany(_,5,3,5),c.add(127,5,0,5),c.addMany(_,2,3,2),c.add(127,2,0,2),c.add(93,1,4,8),c.addMany(l,8,5,8),c.add(127,8,5,8),c.addMany([156,27,24,26,7],8,6,0),c.addMany(s(28,32),8,0,8),c.addMany([88,94,95],1,0,7),c.addMany(l,7,0,7),c.addMany(_,7,0,7),c.add(156,7,0,0),c.add(127,7,0,7),c.add(91,1,11,3),c.addMany(s(64,127),3,7,0),c.addMany(s(48,60),3,8,4),c.addMany([60,61,62,63],3,9,4),c.addMany(s(48,60),4,8,4),c.addMany(s(64,127),4,7,0),c.addMany([60,61,62,63],4,0,6),c.addMany(s(32,64),6,0,6),c.add(127,6,0,6),c.addMany(s(64,127),6,0,0),c.addMany(s(32,48),3,9,5),c.addMany(s(32,48),5,9,5),c.addMany(s(48,64),5,0,6),c.addMany(s(64,127),5,7,0),c.addMany(s(32,48),4,9,5),c.addMany(s(32,48),1,9,2),c.addMany(s(32,48),2,9,2),c.addMany(s(48,127),2,10,0),c.addMany(s(48,80),1,10,0),c.addMany(s(81,88),1,10,0),c.addMany([89,90,92],1,10,0),c.addMany(s(96,127),1,10,0),c.add(80,1,11,9),c.addMany(_,9,0,9),c.add(127,9,0,9),c.addMany(s(28,32),9,0,9),c.addMany(s(32,48),9,9,12),c.addMany(s(48,60),9,8,10),c.addMany([60,61,62,63],9,9,10),c.addMany(_,11,0,11),c.addMany(s(32,128),11,0,11),c.addMany(s(28,32),11,0,11),c.addMany(_,10,0,10),c.add(127,10,0,10),c.addMany(s(28,32),10,0,10),c.addMany(s(48,60),10,8,10),c.addMany([60,61,62,63],10,0,11),c.addMany(s(32,48),10,9,12),c.addMany(_,12,0,12),c.add(127,12,0,12),c.addMany(s(28,32),12,0,12),c.addMany(s(32,48),12,9,12),c.addMany(s(48,64),12,0,11),c.addMany(s(64,127),12,12,13),c.addMany(s(64,127),10,12,13),c.addMany(s(64,127),9,12,13),c.addMany(_,13,13,13),c.addMany(l,13,13,13),c.add(127,13,0,13),c.addMany([27,156,24,26],13,14,0),c.add(w,0,2,0),c.add(w,8,5,8),c.add(w,6,0,6),c.add(w,11,0,11),c.add(w,13,13,13),c}();class m extends f.Disposable{constructor(o=n.VT500_TRANSITION_TABLE){super(),this._transitions=o,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new S.Params,this._params.addParam(0),this._collect=0,this.precedingCodepoint=0,this._printHandlerFb=(s,l,_)=>{},this._executeHandlerFb=s=>{},this._csiHandlerFb=(s,l)=>{},this._escHandlerFb=s=>{},this._errorHandlerFb=s=>s,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,f.toDisposable)(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this.register(new d.OscParser),this._dcsParser=this.register(new p.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(o,s=[64,126]){let l=0;if(o.prefix){if(o.prefix.length>1)throw new Error("only one byte as prefix supported");if(l=o.prefix.charCodeAt(0),l&&60>l||l>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(o.intermediates){if(o.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let g=0;gE||E>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");l<<=8,l|=E}}if(o.final.length!==1)throw new Error("final must be a single byte");const _=o.final.charCodeAt(0);if(s[0]>_||_>s[1])throw new Error(`final must be in range ${s[0]} .. ${s[1]}`);return l<<=8,l|=_,l}identToString(o){const s=[];for(;o;)s.push(String.fromCharCode(255&o)),o>>=8;return s.reverse().join("")}setPrintHandler(o){this._printHandler=o}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(o,s){const l=this._identifier(o,[48,126]);this._escHandlers[l]===void 0&&(this._escHandlers[l]=[]);const _=this._escHandlers[l];return _.push(s),{dispose:()=>{const g=_.indexOf(s);g!==-1&&_.splice(g,1)}}}clearEscHandler(o){this._escHandlers[this._identifier(o,[48,126])]&&delete this._escHandlers[this._identifier(o,[48,126])]}setEscHandlerFallback(o){this._escHandlerFb=o}setExecuteHandler(o,s){this._executeHandlers[o.charCodeAt(0)]=s}clearExecuteHandler(o){this._executeHandlers[o.charCodeAt(0)]&&delete this._executeHandlers[o.charCodeAt(0)]}setExecuteHandlerFallback(o){this._executeHandlerFb=o}registerCsiHandler(o,s){const l=this._identifier(o);this._csiHandlers[l]===void 0&&(this._csiHandlers[l]=[]);const _=this._csiHandlers[l];return _.push(s),{dispose:()=>{const g=_.indexOf(s);g!==-1&&_.splice(g,1)}}}clearCsiHandler(o){this._csiHandlers[this._identifier(o)]&&delete this._csiHandlers[this._identifier(o)]}setCsiHandlerFallback(o){this._csiHandlerFb=o}registerDcsHandler(o,s){return this._dcsParser.registerHandler(this._identifier(o),s)}clearDcsHandler(o){this._dcsParser.clearHandler(this._identifier(o))}setDcsHandlerFallback(o){this._dcsParser.setHandlerFallback(o)}registerOscHandler(o,s){return this._oscParser.registerHandler(o,s)}clearOscHandler(o){this._oscParser.clearHandler(o)}setOscHandlerFallback(o){this._oscParser.setHandlerFallback(o)}setErrorHandler(o){this._errorHandler=o}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingCodepoint=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(o,s,l,_,g){this._parseStack.state=o,this._parseStack.handlers=s,this._parseStack.handlerPos=l,this._parseStack.transition=_,this._parseStack.chunkPos=g}parse(o,s,l){let _,g=0,E=0,b=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,b=this._parseStack.chunkPos+1;else{if(l===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const v=this._parseStack.handlers;let k=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(l===!1&&k>-1){for(;k>=0&&(_=v[k](this._params),_!==!0);k--)if(_ instanceof Promise)return this._parseStack.handlerPos=k,_}this._parseStack.handlers=[];break;case 4:if(l===!1&&k>-1){for(;k>=0&&(_=v[k](),_!==!0);k--)if(_ instanceof Promise)return this._parseStack.handlerPos=k,_}this._parseStack.handlers=[];break;case 6:if(g=o[this._parseStack.chunkPos],_=this._dcsParser.unhook(g!==24&&g!==26,l),_)return _;g===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(g=o[this._parseStack.chunkPos],_=this._oscParser.end(g!==24&&g!==26,l),_)return _;g===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,b=this._parseStack.chunkPos+1,this.precedingCodepoint=0,this.currentState=15&this._parseStack.transition}for(let v=b;v>4){case 2:for(let B=v+1;;++B){if(B>=s||(g=o[B])<32||g>126&&g=s||(g=o[B])<32||g>126&&g=s||(g=o[B])<32||g>126&&g=s||(g=o[B])<32||g>126&&g=0&&(_=k[R](this._params),_!==!0);R--)if(_ instanceof Promise)return this._preserveStack(3,k,R,E,v),_;R<0&&this._csiHandlerFb(this._collect<<8|g,this._params),this.precedingCodepoint=0;break;case 8:do switch(g){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(g-48)}while(++v47&&g<60);v--;break;case 9:this._collect<<=8,this._collect|=g;break;case 10:const P=this._escHandlers[this._collect<<8|g];let A=P?P.length-1:-1;for(;A>=0&&(_=P[A](),_!==!0);A--)if(_ instanceof Promise)return this._preserveStack(4,P,A,E,v),_;A<0&&this._escHandlerFb(this._collect<<8|g),this.precedingCodepoint=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|g,this._params);break;case 13:for(let B=v+1;;++B)if(B>=s||(g=o[B])===24||g===26||g===27||g>127&&g=s||(g=o[B])<32||g>127&&g{Object.defineProperty(n,"__esModule",{value:!0}),n.OscHandler=n.OscParser=void 0;const f=u(5770),S=u(482),d=[];n.OscParser=class{constructor(){this._state=0,this._active=d,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(p,C){this._handlers[p]===void 0&&(this._handlers[p]=[]);const w=this._handlers[p];return w.push(C),{dispose:()=>{const m=w.indexOf(C);m!==-1&&w.splice(m,1)}}}clearHandler(p){this._handlers[p]&&delete this._handlers[p]}setHandlerFallback(p){this._handlerFb=p}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=d}reset(){if(this._state===2)for(let p=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;p>=0;--p)this._active[p].end(!1);this._stack.paused=!1,this._active=d,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||d,this._active.length)for(let p=this._active.length-1;p>=0;p--)this._active[p].start();else this._handlerFb(this._id,"START")}_put(p,C,w){if(this._active.length)for(let m=this._active.length-1;m>=0;m--)this._active[m].put(p,C,w);else this._handlerFb(this._id,"PUT",(0,S.utf32ToString)(p,C,w))}start(){this.reset(),this._state=1}put(p,C,w){if(this._state!==3){if(this._state===1)for(;C0&&this._put(p,C,w)}}end(p,C=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let w=!1,m=this._active.length-1,c=!1;if(this._stack.paused&&(m=this._stack.loopPosition-1,w=C,c=this._stack.fallThrough,this._stack.paused=!1),!c&&w===!1){for(;m>=0&&(w=this._active[m].end(p),w!==!0);m--)if(w instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=m,this._stack.fallThrough=!1,w;m--}for(;m>=0;m--)if(w=this._active[m].end(!1),w instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=m,this._stack.fallThrough=!0,w}else this._handlerFb(this._id,"END",p);this._active=d,this._id=-1,this._state=0}}},n.OscHandler=class{constructor(p){this._handler=p,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(p,C,w){this._hitLimit||(this._data+=(0,S.utf32ToString)(p,C,w),this._data.length>f.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(p){let C=!1;if(this._hitLimit)C=!1;else if(p&&(C=this._handler(this._data),C instanceof Promise))return C.then(w=>(this._data="",this._hitLimit=!1,w));return this._data="",this._hitLimit=!1,C}}},8742:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Params=void 0;const u=2147483647;class f{static fromArray(d){const p=new f;if(!d.length)return p;for(let C=Array.isArray(d[0])?1:0;C256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(d),this.length=0,this._subParams=new Int32Array(p),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(d),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const d=new f(this.maxLength,this.maxSubParamsLength);return d.params.set(this.params),d.length=this.length,d._subParams.set(this._subParams),d._subParamsLength=this._subParamsLength,d._subParamsIdx.set(this._subParamsIdx),d._rejectDigits=this._rejectDigits,d._rejectSubDigits=this._rejectSubDigits,d._digitIsSub=this._digitIsSub,d}toArray(){const d=[];for(let p=0;p>8,w=255&this._subParamsIdx[p];w-C>0&&d.push(Array.prototype.slice.call(this._subParams,C,w))}return d}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(d){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(d<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=d>u?u:d}}addSubParam(d){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(d<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=d>u?u:d,this._subParamsIdx[this.length-1]++}}hasSubParams(d){return(255&this._subParamsIdx[d])-(this._subParamsIdx[d]>>8)>0}getSubParams(d){const p=this._subParamsIdx[d]>>8,C=255&this._subParamsIdx[d];return C-p>0?this._subParams.subarray(p,C):null}getSubParamsAll(){const d={};for(let p=0;p>8,w=255&this._subParamsIdx[p];w-C>0&&(d[p]=this._subParams.slice(C,w))}return d}addDigit(d){let p;if(this._rejectDigits||!(p=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const C=this._digitIsSub?this._subParams:this.params,w=C[p-1];C[p-1]=~w?Math.min(10*w+d,u):d}}n.Params=f},5741:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.AddonManager=void 0,n.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let u=this._addons.length-1;u>=0;u--)this._addons[u].instance.dispose()}loadAddon(u,f){const S={instance:f,dispose:f.dispose,isDisposed:!1};this._addons.push(S),f.dispose=()=>this._wrappedAddonDispose(S),f.activate(u)}_wrappedAddonDispose(u){if(u.isDisposed)return;let f=-1;for(let S=0;S{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferApiView=void 0;const f=u(3785),S=u(511);n.BufferApiView=class{constructor(d,p){this._buffer=d,this.type=p}init(d){return this._buffer=d,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(d){const p=this._buffer.lines.get(d);if(p)return new f.BufferLineApiView(p)}getNullCell(){return new S.CellData}}},3785:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferLineApiView=void 0;const f=u(511);n.BufferLineApiView=class{constructor(S){this._line=S}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(S,d){if(!(S<0||S>=this._line.length))return d?(this._line.loadCell(S,d),d):this._line.loadCell(S,new f.CellData)}translateToString(S,d,p){return this._line.translateToString(S,d,p)}}},8285:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferNamespaceApi=void 0;const f=u(8771),S=u(8460),d=u(844);class p extends d.Disposable{constructor(w){super(),this._core=w,this._onBufferChange=this.register(new S.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new f.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new f.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}n.BufferNamespaceApi=p},7975:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ParserApi=void 0,n.ParserApi=class{constructor(u){this._core=u}registerCsiHandler(u,f){return this._core.registerCsiHandler(u,S=>f(S.toArray()))}addCsiHandler(u,f){return this.registerCsiHandler(u,f)}registerDcsHandler(u,f){return this._core.registerDcsHandler(u,(S,d)=>f(S,d.toArray()))}addDcsHandler(u,f){return this.registerDcsHandler(u,f)}registerEscHandler(u,f){return this._core.registerEscHandler(u,f)}addEscHandler(u,f){return this.registerEscHandler(u,f)}registerOscHandler(u,f){return this._core.registerOscHandler(u,f)}addOscHandler(u,f){return this.registerOscHandler(u,f)}}},7090:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeApi=void 0,n.UnicodeApi=class{constructor(u){this._core=u}register(u){this._core.unicodeService.register(u)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(u){this._core.unicodeService.activeVersion=u}}},744:function(y,n,u){var f=this&&this.__decorate||function(c,o,s,l){var _,g=arguments.length,E=g<3?o:l===null?l=Object.getOwnPropertyDescriptor(o,s):l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(c,o,s,l);else for(var b=c.length-1;b>=0;b--)(_=c[b])&&(E=(g<3?_(E):g>3?_(o,s,E):_(o,s))||E);return g>3&&E&&Object.defineProperty(o,s,E),E},S=this&&this.__param||function(c,o){return function(s,l){o(s,l,c)}};Object.defineProperty(n,"__esModule",{value:!0}),n.BufferService=n.MINIMUM_ROWS=n.MINIMUM_COLS=void 0;const d=u(8460),p=u(844),C=u(5295),w=u(2585);n.MINIMUM_COLS=2,n.MINIMUM_ROWS=1;let m=n.BufferService=class extends p.Disposable{get buffer(){return this.buffers.active}constructor(c){super(),this.isUserScrolling=!1,this._onResize=this.register(new d.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new d.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(c.rawOptions.cols||0,n.MINIMUM_COLS),this.rows=Math.max(c.rawOptions.rows||0,n.MINIMUM_ROWS),this.buffers=this.register(new C.BufferSet(c,this))}resize(c,o){this.cols=c,this.rows=o,this.buffers.resize(c,o),this._onResize.fire({cols:c,rows:o})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(c,o=!1){const s=this.buffer;let l;l=this._cachedBlankLine,l&&l.length===this.cols&&l.getFg(0)===c.fg&&l.getBg(0)===c.bg||(l=s.getBlankLine(c,o),this._cachedBlankLine=l),l.isWrapped=o;const _=s.ybase+s.scrollTop,g=s.ybase+s.scrollBottom;if(s.scrollTop===0){const E=s.lines.isFull;g===s.lines.length-1?E?s.lines.recycle().copyFrom(l):s.lines.push(l.clone()):s.lines.splice(g+1,0,l.clone()),E?this.isUserScrolling&&(s.ydisp=Math.max(s.ydisp-1,0)):(s.ybase++,this.isUserScrolling||s.ydisp++)}else{const E=g-_+1;s.lines.shiftElements(_+1,E-1,-1),s.lines.set(g,l.clone())}this.isUserScrolling||(s.ydisp=s.ybase),this._onScroll.fire(s.ydisp)}scrollLines(c,o,s){const l=this.buffer;if(c<0){if(l.ydisp===0)return;this.isUserScrolling=!0}else c+l.ydisp>=l.ybase&&(this.isUserScrolling=!1);const _=l.ydisp;l.ydisp=Math.max(Math.min(l.ydisp+c,l.ybase),0),_!==l.ydisp&&(o||this._onScroll.fire(l.ydisp))}};n.BufferService=m=f([S(0,w.IOptionsService)],m)},7994:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CharsetService=void 0,n.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(u){this.glevel=u,this.charset=this._charsets[u]}setgCharset(u,f){this._charsets[u]=f,this.glevel===u&&(this.charset=f)}}},1753:function(y,n,u){var f=this&&this.__decorate||function(l,_,g,E){var b,v=arguments.length,k=v<3?_:E===null?E=Object.getOwnPropertyDescriptor(_,g):E;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(l,_,g,E);else for(var R=l.length-1;R>=0;R--)(b=l[R])&&(k=(v<3?b(k):v>3?b(_,g,k):b(_,g))||k);return v>3&&k&&Object.defineProperty(_,g,k),k},S=this&&this.__param||function(l,_){return function(g,E){_(g,E,l)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CoreMouseService=void 0;const d=u(2585),p=u(8460),C=u(844),w={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:l=>l.button!==4&&l.action===1&&(l.ctrl=!1,l.alt=!1,l.shift=!1,!0)},VT200:{events:19,restrict:l=>l.action!==32},DRAG:{events:23,restrict:l=>l.action!==32||l.button!==3},ANY:{events:31,restrict:l=>!0}};function m(l,_){let g=(l.ctrl?16:0)|(l.shift?4:0)|(l.alt?8:0);return l.button===4?(g|=64,g|=l.action):(g|=3&l.button,4&l.button&&(g|=64),8&l.button&&(g|=128),l.action===32?g|=32:l.action!==0||_||(g|=3)),g}const c=String.fromCharCode,o={DEFAULT:l=>{const _=[m(l,!1)+32,l.col+32,l.row+32];return _[0]>255||_[1]>255||_[2]>255?"":`\x1B[M${c(_[0])}${c(_[1])}${c(_[2])}`},SGR:l=>{const _=l.action===0&&l.button!==4?"m":"M";return`\x1B[<${m(l,!0)};${l.col};${l.row}${_}`},SGR_PIXELS:l=>{const _=l.action===0&&l.button!==4?"m":"M";return`\x1B[<${m(l,!0)};${l.x};${l.y}${_}`}};let s=n.CoreMouseService=class extends C.Disposable{constructor(l,_){super(),this._bufferService=l,this._coreService=_,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new p.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const g of Object.keys(w))this.addProtocol(g,w[g]);for(const g of Object.keys(o))this.addEncoding(g,o[g]);this.reset()}addProtocol(l,_){this._protocols[l]=_}addEncoding(l,_){this._encodings[l]=_}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(l){if(!this._protocols[l])throw new Error(`unknown protocol "${l}"`);this._activeProtocol=l,this._onProtocolChange.fire(this._protocols[l].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(l){if(!this._encodings[l])throw new Error(`unknown encoding "${l}"`);this._activeEncoding=l}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(l){if(l.col<0||l.col>=this._bufferService.cols||l.row<0||l.row>=this._bufferService.rows||l.button===4&&l.action===32||l.button===3&&l.action!==32||l.button!==4&&(l.action===2||l.action===3)||(l.col++,l.row++,l.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,l,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(l))return!1;const _=this._encodings[this._activeEncoding](l);return _&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(_):this._coreService.triggerDataEvent(_,!0)),this._lastEvent=l,!0}explainEvents(l){return{down:!!(1&l),up:!!(2&l),drag:!!(4&l),move:!!(8&l),wheel:!!(16&l)}}_equalEvents(l,_,g){if(g){if(l.x!==_.x||l.y!==_.y)return!1}else if(l.col!==_.col||l.row!==_.row)return!1;return l.button===_.button&&l.action===_.action&&l.ctrl===_.ctrl&&l.alt===_.alt&&l.shift===_.shift}};n.CoreMouseService=s=f([S(0,d.IBufferService),S(1,d.ICoreService)],s)},6975:function(y,n,u){var f=this&&this.__decorate||function(s,l,_,g){var E,b=arguments.length,v=b<3?l:g===null?g=Object.getOwnPropertyDescriptor(l,_):g;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")v=Reflect.decorate(s,l,_,g);else for(var k=s.length-1;k>=0;k--)(E=s[k])&&(v=(b<3?E(v):b>3?E(l,_,v):E(l,_))||v);return b>3&&v&&Object.defineProperty(l,_,v),v},S=this&&this.__param||function(s,l){return function(_,g){l(_,g,s)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CoreService=void 0;const d=u(1439),p=u(8460),C=u(844),w=u(2585),m=Object.freeze({insertMode:!1}),c=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0});let o=n.CoreService=class extends C.Disposable{constructor(s,l,_){super(),this._bufferService=s,this._logService=l,this._optionsService=_,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new p.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new p.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new p.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new p.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,d.clone)(m),this.decPrivateModes=(0,d.clone)(c)}reset(){this.modes=(0,d.clone)(m),this.decPrivateModes=(0,d.clone)(c)}triggerDataEvent(s,l=!1){if(this._optionsService.rawOptions.disableStdin)return;const _=this._bufferService.buffer;l&&this._optionsService.rawOptions.scrollOnUserInput&&_.ybase!==_.ydisp&&this._onRequestScrollToBottom.fire(),l&&this._onUserInput.fire(),this._logService.debug(`sending data "${s}"`,()=>s.split("").map(g=>g.charCodeAt(0))),this._onData.fire(s)}triggerBinaryEvent(s){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${s}"`,()=>s.split("").map(l=>l.charCodeAt(0))),this._onBinary.fire(s))}};n.CoreService=o=f([S(0,w.IBufferService),S(1,w.ILogService),S(2,w.IOptionsService)],o)},9074:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DecorationService=void 0;const f=u(8055),S=u(8460),d=u(844),p=u(6106);let C=0,w=0;class m extends d.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new p.SortedList(s=>s==null?void 0:s.marker.line),this._onDecorationRegistered=this.register(new S.EventEmitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this.register(new S.EventEmitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this.register((0,d.toDisposable)(()=>this.reset()))}registerDecoration(s){if(s.marker.isDisposed)return;const l=new c(s);if(l){const _=l.marker.onDispose(()=>l.dispose());l.onDispose(()=>{l&&(this._decorations.delete(l)&&this._onDecorationRemoved.fire(l),_.dispose())}),this._decorations.insert(l),this._onDecorationRegistered.fire(l)}return l}reset(){for(const s of this._decorations.values())s.dispose();this._decorations.clear()}*getDecorationsAtCell(s,l,_){var g,E,b;let v=0,k=0;for(const R of this._decorations.getKeyIterator(l))v=(g=R.options.x)!==null&&g!==void 0?g:0,k=v+((E=R.options.width)!==null&&E!==void 0?E:1),s>=v&&s{var b,v,k;C=(b=E.options.x)!==null&&b!==void 0?b:0,w=C+((v=E.options.width)!==null&&v!==void 0?v:1),s>=C&&s{Object.defineProperty(n,"__esModule",{value:!0}),n.InstantiationService=n.ServiceCollection=void 0;const f=u(2585),S=u(8343);class d{constructor(...C){this._entries=new Map;for(const[w,m]of C)this.set(w,m)}set(C,w){const m=this._entries.get(C);return this._entries.set(C,w),m}forEach(C){for(const[w,m]of this._entries.entries())C(w,m)}has(C){return this._entries.has(C)}get(C){return this._entries.get(C)}}n.ServiceCollection=d,n.InstantiationService=class{constructor(){this._services=new d,this._services.set(f.IInstantiationService,this)}setService(p,C){this._services.set(p,C)}getService(p){return this._services.get(p)}createInstance(p,...C){const w=(0,S.getServiceDependencies)(p).sort((o,s)=>o.index-s.index),m=[];for(const o of w){const s=this._services.get(o.id);if(!s)throw new Error(`[createInstance] ${p.name} depends on UNKNOWN service ${o.id}.`);m.push(s)}const c=w.length>0?w[0].index:C.length;if(C.length!==c)throw new Error(`[createInstance] First service dependency of ${p.name} at position ${c+1} conflicts with ${C.length} static arguments`);return new p(...C,...m)}}},7866:function(y,n,u){var f=this&&this.__decorate||function(c,o,s,l){var _,g=arguments.length,E=g<3?o:l===null?l=Object.getOwnPropertyDescriptor(o,s):l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(c,o,s,l);else for(var b=c.length-1;b>=0;b--)(_=c[b])&&(E=(g<3?_(E):g>3?_(o,s,E):_(o,s))||E);return g>3&&E&&Object.defineProperty(o,s,E),E},S=this&&this.__param||function(c,o){return function(s,l){o(s,l,c)}};Object.defineProperty(n,"__esModule",{value:!0}),n.traceCall=n.setTraceLogger=n.LogService=void 0;const d=u(844),p=u(2585),C={trace:p.LogLevelEnum.TRACE,debug:p.LogLevelEnum.DEBUG,info:p.LogLevelEnum.INFO,warn:p.LogLevelEnum.WARN,error:p.LogLevelEnum.ERROR,off:p.LogLevelEnum.OFF};let w,m=n.LogService=class extends d.Disposable{get logLevel(){return this._logLevel}constructor(c){super(),this._optionsService=c,this._logLevel=p.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),w=this}_updateLogLevel(){this._logLevel=C[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(c){for(let o=0;oJSON.stringify(E)).join(", ")})`);const g=l.apply(this,_);return w.trace(`GlyphRenderer#${l.name} return`,g),g}}},7302:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OptionsService=n.DEFAULT_OPTIONS=void 0;const f=u(8460),S=u(844),d=u(6114);n.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rightClickSelectsWord:d.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const p=["normal","bold","100","200","300","400","500","600","700","800","900"];class C extends S.Disposable{constructor(m){super(),this._onOptionChange=this.register(new f.EventEmitter),this.onOptionChange=this._onOptionChange.event;const c=Object.assign({},n.DEFAULT_OPTIONS);for(const o in m)if(o in c)try{const s=m[o];c[o]=this._sanitizeAndValidateOption(o,s)}catch(s){console.error(s)}this.rawOptions=c,this.options=Object.assign({},c),this._setupOptions()}onSpecificOptionChange(m,c){return this.onOptionChange(o=>{o===m&&c(this.rawOptions[m])})}onMultipleOptionChange(m,c){return this.onOptionChange(o=>{m.indexOf(o)!==-1&&c()})}_setupOptions(){const m=o=>{if(!(o in n.DEFAULT_OPTIONS))throw new Error(`No option with key "${o}"`);return this.rawOptions[o]},c=(o,s)=>{if(!(o in n.DEFAULT_OPTIONS))throw new Error(`No option with key "${o}"`);s=this._sanitizeAndValidateOption(o,s),this.rawOptions[o]!==s&&(this.rawOptions[o]=s,this._onOptionChange.fire(o))};for(const o in this.rawOptions){const s={get:m.bind(this,o),set:c.bind(this,o)};Object.defineProperty(this.options,o,s)}}_sanitizeAndValidateOption(m,c){switch(m){case"cursorStyle":if(c||(c=n.DEFAULT_OPTIONS[m]),!function(o){return o==="block"||o==="underline"||o==="bar"}(c))throw new Error(`"${c}" is not a valid value for ${m}`);break;case"wordSeparator":c||(c=n.DEFAULT_OPTIONS[m]);break;case"fontWeight":case"fontWeightBold":if(typeof c=="number"&&1<=c&&c<=1e3)break;c=p.includes(c)?c:n.DEFAULT_OPTIONS[m];break;case"cursorWidth":c=Math.floor(c);case"lineHeight":case"tabStopWidth":if(c<1)throw new Error(`${m} cannot be less than 1, value: ${c}`);break;case"minimumContrastRatio":c=Math.max(1,Math.min(21,Math.round(10*c)/10));break;case"scrollback":if((c=Math.min(c,4294967295))<0)throw new Error(`${m} cannot be less than 0, value: ${c}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(c<=0)throw new Error(`${m} cannot be less than or equal to 0, value: ${c}`);break;case"rows":case"cols":if(!c&&c!==0)throw new Error(`${m} must be numeric, value: ${c}`);break;case"windowsPty":c=c??{}}return c}}n.OptionsService=C},2660:function(y,n,u){var f=this&&this.__decorate||function(C,w,m,c){var o,s=arguments.length,l=s<3?w:c===null?c=Object.getOwnPropertyDescriptor(w,m):c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")l=Reflect.decorate(C,w,m,c);else for(var _=C.length-1;_>=0;_--)(o=C[_])&&(l=(s<3?o(l):s>3?o(w,m,l):o(w,m))||l);return s>3&&l&&Object.defineProperty(w,m,l),l},S=this&&this.__param||function(C,w){return function(m,c){w(m,c,C)}};Object.defineProperty(n,"__esModule",{value:!0}),n.OscLinkService=void 0;const d=u(2585);let p=n.OscLinkService=class{constructor(C){this._bufferService=C,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(C){const w=this._bufferService.buffer;if(C.id===void 0){const _=w.addMarker(w.ybase+w.y),g={data:C,id:this._nextId++,lines:[_]};return _.onDispose(()=>this._removeMarkerFromLink(g,_)),this._dataByLinkId.set(g.id,g),g.id}const m=C,c=this._getEntryIdKey(m),o=this._entriesWithId.get(c);if(o)return this.addLineToLink(o.id,w.ybase+w.y),o.id;const s=w.addMarker(w.ybase+w.y),l={id:this._nextId++,key:this._getEntryIdKey(m),data:m,lines:[s]};return s.onDispose(()=>this._removeMarkerFromLink(l,s)),this._entriesWithId.set(l.key,l),this._dataByLinkId.set(l.id,l),l.id}addLineToLink(C,w){const m=this._dataByLinkId.get(C);if(m&&m.lines.every(c=>c.line!==w)){const c=this._bufferService.buffer.addMarker(w);m.lines.push(c),c.onDispose(()=>this._removeMarkerFromLink(m,c))}}getLinkData(C){var w;return(w=this._dataByLinkId.get(C))===null||w===void 0?void 0:w.data}_getEntryIdKey(C){return`${C.id};;${C.uri}`}_removeMarkerFromLink(C,w){const m=C.lines.indexOf(w);m!==-1&&(C.lines.splice(m,1),C.lines.length===0&&(C.data.id!==void 0&&this._entriesWithId.delete(C.key),this._dataByLinkId.delete(C.id)))}};n.OscLinkService=p=f([S(0,d.IBufferService)],p)},8343:(y,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createDecorator=n.getServiceDependencies=n.serviceRegistry=void 0;const u="di$target",f="di$dependencies";n.serviceRegistry=new Map,n.getServiceDependencies=function(S){return S[f]||[]},n.createDecorator=function(S){if(n.serviceRegistry.has(S))return n.serviceRegistry.get(S);const d=function(p,C,w){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(m,c,o){c[u]===c?c[f].push({id:m,index:o}):(c[f]=[{id:m,index:o}],c[u]=c)})(d,p,w)};return d.toString=()=>S,n.serviceRegistry.set(S,d),d}},2585:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.IDecorationService=n.IUnicodeService=n.IOscLinkService=n.IOptionsService=n.ILogService=n.LogLevelEnum=n.IInstantiationService=n.ICharsetService=n.ICoreService=n.ICoreMouseService=n.IBufferService=void 0;const f=u(8343);var S;n.IBufferService=(0,f.createDecorator)("BufferService"),n.ICoreMouseService=(0,f.createDecorator)("CoreMouseService"),n.ICoreService=(0,f.createDecorator)("CoreService"),n.ICharsetService=(0,f.createDecorator)("CharsetService"),n.IInstantiationService=(0,f.createDecorator)("InstantiationService"),function(d){d[d.TRACE=0]="TRACE",d[d.DEBUG=1]="DEBUG",d[d.INFO=2]="INFO",d[d.WARN=3]="WARN",d[d.ERROR=4]="ERROR",d[d.OFF=5]="OFF"}(S||(n.LogLevelEnum=S={})),n.ILogService=(0,f.createDecorator)("LogService"),n.IOptionsService=(0,f.createDecorator)("OptionsService"),n.IOscLinkService=(0,f.createDecorator)("OscLinkService"),n.IUnicodeService=(0,f.createDecorator)("UnicodeService"),n.IDecorationService=(0,f.createDecorator)("DecorationService")},1480:(y,n,u)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeService=void 0;const f=u(8460),S=u(225);n.UnicodeService=class{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new f.EventEmitter,this.onChange=this._onChange.event;const d=new S.UnicodeV6;this.register(d),this._active=d.version,this._activeProvider=d}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(d){if(!this._providers[d])throw new Error(`unknown Unicode version "${d}"`);this._active=d,this._activeProvider=this._providers[d],this._onChange.fire(d)}register(d){this._providers[d.version]=d}wcwidth(d){return this._activeProvider.wcwidth(d)}getStringCellWidth(d){let p=0;const C=d.length;for(let w=0;w=C)return p+this.wcwidth(m);const c=d.charCodeAt(w);56320<=c&&c<=57343?m=1024*(m-55296)+c-56320+65536:p+=this.wcwidth(c)}p+=this.wcwidth(m)}return p}}}},i={};function a(y){var n=i[y];if(n!==void 0)return n.exports;var u=i[y]={exports:{}};return r[y].call(u.exports,u,u.exports,a),u.exports}var h={};return(()=>{var y=h;Object.defineProperty(y,"__esModule",{value:!0}),y.Terminal=void 0;const n=a(9042),u=a(3236),f=a(844),S=a(5741),d=a(8285),p=a(7975),C=a(7090),w=["cols","rows"];class m extends f.Disposable{constructor(o){super(),this._core=this.register(new u.Terminal(o)),this._addonManager=this.register(new S.AddonManager),this._publicOptions=Object.assign({},this._core.options);const s=_=>this._core.options[_],l=(_,g)=>{this._checkReadonlyOptions(_),this._core.options[_]=g};for(const _ in this._core.options){const g={get:s.bind(this,_),set:l.bind(this,_)};Object.defineProperty(this._publicOptions,_,g)}}_checkReadonlyOptions(o){if(w.includes(o))throw new Error(`Option "${o}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new p.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new C.UnicodeApi(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this.register(new d.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const o=this._core.coreService.decPrivateModes;let s="none";switch(this._core.coreMouseService.activeProtocol){case"X10":s="x10";break;case"VT200":s="vt200";break;case"DRAG":s="drag";break;case"ANY":s="any"}return{applicationCursorKeysMode:o.applicationCursorKeys,applicationKeypadMode:o.applicationKeypad,bracketedPasteMode:o.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:s,originMode:o.origin,reverseWraparoundMode:o.reverseWraparound,sendFocusMode:o.sendFocus,wraparoundMode:o.wraparound}}get options(){return this._publicOptions}set options(o){for(const s in o)this._publicOptions[s]=o[s]}blur(){this._core.blur()}focus(){this._core.focus()}resize(o,s){this._verifyIntegers(o,s),this._core.resize(o,s)}open(o){this._core.open(o)}attachCustomKeyEventHandler(o){this._core.attachCustomKeyEventHandler(o)}registerLinkProvider(o){return this._core.registerLinkProvider(o)}registerCharacterJoiner(o){return this._checkProposedApi(),this._core.registerCharacterJoiner(o)}deregisterCharacterJoiner(o){this._checkProposedApi(),this._core.deregisterCharacterJoiner(o)}registerMarker(o=0){return this._verifyIntegers(o),this._core.registerMarker(o)}registerDecoration(o){var s,l,_;return this._checkProposedApi(),this._verifyPositiveIntegers((s=o.x)!==null&&s!==void 0?s:0,(l=o.width)!==null&&l!==void 0?l:0,(_=o.height)!==null&&_!==void 0?_:0),this._core.registerDecoration(o)}hasSelection(){return this._core.hasSelection()}select(o,s,l){this._verifyIntegers(o,s,l),this._core.select(o,s,l)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(o,s){this._verifyIntegers(o,s),this._core.selectLines(o,s)}dispose(){super.dispose()}scrollLines(o){this._verifyIntegers(o),this._core.scrollLines(o)}scrollPages(o){this._verifyIntegers(o),this._core.scrollPages(o)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(o){this._verifyIntegers(o),this._core.scrollToLine(o)}clear(){this._core.clear()}write(o,s){this._core.write(o,s)}writeln(o,s){this._core.write(o),this._core.write(`\r +`,s)}paste(o){this._core.paste(o)}refresh(o,s){this._verifyIntegers(o,s),this._core.refresh(o,s)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(o){this._addonManager.loadAddon(this,o)}static get strings(){return n}_verifyIntegers(...o){for(const s of o)if(s===1/0||isNaN(s)||s%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...o){for(const s of o)if(s&&(s===1/0||isNaN(s)||s%1!=0||s<0))throw new Error("This API only accepts positive integers")}}y.Terminal=m})(),h})())})(m_);var S_={exports:{}};(function(e,t){(function(r,i){e.exports=i()})(self,()=>(()=>{var r={};return(()=>{var i=r;Object.defineProperty(i,"__esModule",{value:!0}),i.FitAddon=void 0,i.FitAddon=class{activate(a){this._terminal=a}dispose(){}fit(){const a=this.proposeDimensions();if(!a||!this._terminal||isNaN(a.cols)||isNaN(a.rows))return;const h=this._terminal._core;this._terminal.rows===a.rows&&this._terminal.cols===a.cols||(h._renderService.clear(),this._terminal.resize(a.cols,a.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const a=this._terminal._core,h=a._renderService.dimensions;if(h.css.cell.width===0||h.css.cell.height===0)return;const y=this._terminal.options.scrollback===0?0:a.viewport.scrollBarWidth,n=window.getComputedStyle(this._terminal.element.parentElement),u=parseInt(n.getPropertyValue("height")),f=Math.max(0,parseInt(n.getPropertyValue("width"))),S=window.getComputedStyle(this._terminal.element),d=u-(parseInt(S.getPropertyValue("padding-top"))+parseInt(S.getPropertyValue("padding-bottom"))),p=f-(parseInt(S.getPropertyValue("padding-right"))+parseInt(S.getPropertyValue("padding-left")))-y;return{cols:Math.max(2,Math.floor(p/h.css.cell.width)),rows:Math.max(1,Math.floor(d/h.css.cell.height))}}}})(),r})())})(S_);function y_(){const{zoom:e}=Ci(),t={position:"fixed",inset:0,background:"#0b0e13",overflow:"hidden"};return K.jsxs("div",{style:t,children:[K.jsx(g_,{}),K.jsx(f_,{}),K.jsx(c_,{}),K.jsx(a_,{}),K.jsx(u_,{}),K.jsx("div",{style:{position:"absolute",left:"18px",bottom:"18px",background:"rgba(14,18,25,.82)",border:"1px solid rgba(140,165,200,.18)",borderRadius:"9px",padding:"6px 12px",backdropFilter:"blur(6px)"},children:K.jsxs("span",{style:{color:"#aaa",fontSize:"12px"},children:[Math.round(e*100),"%"]})}),K.jsxs("div",{style:{position:"absolute",right:"18px",bottom:"18px",color:"#888",fontSize:"12px",background:"rgba(14,18,25,.82)",padding:"8px 12px",borderRadius:"6px"},children:[K.jsx("span",{children:"Space + drag to pan"}),K.jsx("span",{style:{marginLeft:"12px"},children:"Scroll to pan"}),K.jsx("span",{style:{marginLeft:"12px"},children:"Click to spotlight"})]})]})}Rn.createRoot(document.getElementById("root")).render(K.jsx(ja.StrictMode,{children:K.jsx(y_,{})})); diff --git a/client/dist/index.html b/client/dist/index.html new file mode 100644 index 0000000..97c1f76 --- /dev/null +++ b/client/dist/index.html @@ -0,0 +1,39 @@ + + + + + + + Krates Yard + + + + + + + + + +
+ + diff --git a/client/node_modules/.bin/autoprefixer b/client/node_modules/.bin/autoprefixer new file mode 120000 index 0000000..e876d81 --- /dev/null +++ b/client/node_modules/.bin/autoprefixer @@ -0,0 +1 @@ +../autoprefixer/bin/autoprefixer \ No newline at end of file diff --git a/client/node_modules/.bin/jiti b/client/node_modules/.bin/jiti new file mode 120000 index 0000000..18f28cf --- /dev/null +++ b/client/node_modules/.bin/jiti @@ -0,0 +1 @@ +../jiti/lib/jiti-cli.mjs \ No newline at end of file diff --git a/client/node_modules/.package-lock.json b/client/node_modules/.package-lock.json index 27c0b37..5f4e169 100644 --- a/client/node_modules/.package-lock.json +++ b/client/node_modules/.package-lock.json @@ -4,6 +4,19 @@ "lockfileVersion": 3, "requires": true, "packages": { + "node_modules/@alloc/quick-lru": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", + "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/@babel/code-frame": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", @@ -598,6 +611,77 @@ "linux" ] }, + "node_modules/@tailwindcss/node": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.1.tgz", + "integrity": "sha512-6NDaqRoAMSXD1mr/RXu0HBvNE9a2n5tHPsxu9XHLws8o4Twes5rBM2205SUUiJ9goAtadrN6xTGX0UDEwp/N4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "5.21.6", + "jiti": "^2.7.0", + "lightningcss": "1.32.0", + "magic-string": "^0.30.21", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.1" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.1.tgz", + "integrity": "sha512-yVPyo8RNkabVr3O2EhHEE0Rewu7YKzc1DhIqfL46LKveFrmu9XbDazNOJY7/GRuvw1h6u3utWnR29H/p5JPlgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.1", + "@tailwindcss/oxide-darwin-arm64": "4.3.1", + "@tailwindcss/oxide-darwin-x64": "4.3.1", + "@tailwindcss/oxide-freebsd-x64": "4.3.1", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.1", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.1", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.1", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.1", + "@tailwindcss/oxide-linux-x64-musl": "4.3.1", + "@tailwindcss/oxide-wasm32-wasi": "4.3.1", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.1", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.1" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.1.tgz", + "integrity": "sha512-Ymi8O8T15HYQdOUWUtTI6ldN0neHP85FC+Qz32xTcZ7iJXtem/x8ITev0o1e9e5rkqj4lONZfTRLvkmin1+tKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/postcss": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@tailwindcss/postcss/-/postcss-4.3.1.tgz", + "integrity": "sha512-dNJuNbdEJT/SWRuXTYP1WSamelsz3ztkUsdtWQPjrexysrTpaEPM40P/71knXiXLYEojqPOEGitVLLpPMS5T6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "@tailwindcss/node": "4.3.1", + "@tailwindcss/oxide": "4.3.1", + "postcss": "8.5.15", + "tailwindcss": "4.3.1" + } + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -1099,6 +1183,43 @@ "license": "MIT", "optional": true }, + "node_modules/autoprefixer": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.5.0.tgz", + "integrity": "sha512-FMhOoZV4+qR6aTUALKX2rEqGG+oyATvwBt9IIzVR5rMa2HRWPkxf+P+PAJLD1I/H5/II+HuZcBJYEFBpq39ong==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/autoprefixer" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "browserslist": "^4.28.2", + "caniuse-lite": "^1.0.30001787", + "fraction.js": "^5.3.4", + "picocolors": "^1.1.1", + "postcss-value-parser": "^4.2.0" + }, + "bin": { + "autoprefixer": "bin/autoprefixer" + }, + "engines": { + "node": "^10 || ^12 || >=14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -1354,6 +1475,16 @@ "node": ">=6" } }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, "node_modules/electron-to-chromium": { "version": "1.5.373", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.373.tgz", @@ -1378,6 +1509,20 @@ "node": ">=6" } }, + "node_modules/enhanced-resolve": { + "version": "5.21.6", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.21.6.tgz", + "integrity": "sha512-aNnGCvbJ/RIyWo1IuhNdVjnNF+EjH9wpzpNHt+ci/m9He9LJvUN8wrCcXjp9cWsGNAuvSpVFTx/vraAFQ8qGjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/errno": { "version": "0.1.8", "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.8.tgz", @@ -1720,6 +1865,20 @@ "dev": true, "license": "ISC" }, + "node_modules/fraction.js": { + "version": "5.3.4", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz", + "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/rawify" + } + }, "node_modules/gensync": { "version": "1.0.0-beta.2", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", @@ -1756,6 +1915,13 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC" + }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -1878,6 +2044,16 @@ "url": "https://github.com/sponsors/dmonad" } }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -2149,6 +2325,57 @@ "url": "https://github.com/sponsors/dmonad" } }, + "node_modules/lightningcss": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", + "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.32.0", + "lightningcss-darwin-arm64": "1.32.0", + "lightningcss-darwin-x64": "1.32.0", + "lightningcss-freebsd-x64": "1.32.0", + "lightningcss-linux-arm-gnueabihf": "1.32.0", + "lightningcss-linux-arm64-gnu": "1.32.0", + "lightningcss-linux-arm64-musl": "1.32.0", + "lightningcss-linux-x64-gnu": "1.32.0", + "lightningcss-linux-x64-musl": "1.32.0", + "lightningcss-win32-arm64-msvc": "1.32.0", + "lightningcss-win32-x64-msvc": "1.32.0" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", + "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -2207,6 +2434,16 @@ "license": "MIT", "optional": true }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, "node_modules/minimatch": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", @@ -2414,6 +2651,13 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true, + "license": "MIT" + }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -2655,6 +2899,27 @@ "node": ">=8" } }, + "node_modules/tailwindcss": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.1.tgz", + "integrity": "sha512-hk+TB1m+K8CYNrP6rjQaq/Y+4Zylwpa87mLYBKCunwnnQ9p+fHb7kmSfGqyEJoxF/O6CDyABWVFEafNSYKll+Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz", + "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, "node_modules/tinyglobby": { "version": "0.2.17", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", diff --git a/client/node_modules/@alloc/quick-lru/index.d.ts b/client/node_modules/@alloc/quick-lru/index.d.ts new file mode 100644 index 0000000..eb819ba --- /dev/null +++ b/client/node_modules/@alloc/quick-lru/index.d.ts @@ -0,0 +1,128 @@ +declare namespace QuickLRU { + interface Options { + /** + The maximum number of milliseconds an item should remain in the cache. + + @default Infinity + + By default, `maxAge` will be `Infinity`, which means that items will never expire. + Lazy expiration upon the next write or read call. + + Individual expiration of an item can be specified by the `set(key, value, maxAge)` method. + */ + readonly maxAge?: number; + + /** + The maximum number of items before evicting the least recently used items. + */ + readonly maxSize: number; + + /** + Called right before an item is evicted from the cache. + + Useful for side effects or for items like object URLs that need explicit cleanup (`revokeObjectURL`). + */ + onEviction?: (key: KeyType, value: ValueType) => void; + } +} + +declare class QuickLRU + implements Iterable<[KeyType, ValueType]> { + /** + The stored item count. + */ + readonly size: number; + + /** + Simple ["Least Recently Used" (LRU) cache](https://en.m.wikipedia.org/wiki/Cache_replacement_policies#Least_Recently_Used_.28LRU.29). + + The instance is [`iterable`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols) so you can use it directly in a [`for…of`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of) loop. + + @example + ``` + import QuickLRU = require('quick-lru'); + + const lru = new QuickLRU({maxSize: 1000}); + + lru.set('🦄', '🌈'); + + lru.has('🦄'); + //=> true + + lru.get('🦄'); + //=> '🌈' + ``` + */ + constructor(options: QuickLRU.Options); + + [Symbol.iterator](): IterableIterator<[KeyType, ValueType]>; + + /** + Set an item. Returns the instance. + + Individual expiration of an item can be specified with the `maxAge` option. If not specified, the global `maxAge` value will be used in case it is specified in the constructor, otherwise the item will never expire. + + @returns The list instance. + */ + set(key: KeyType, value: ValueType, options?: {maxAge?: number}): this; + + /** + Get an item. + + @returns The stored item or `undefined`. + */ + get(key: KeyType): ValueType | undefined; + + /** + Check if an item exists. + */ + has(key: KeyType): boolean; + + /** + Get an item without marking it as recently used. + + @returns The stored item or `undefined`. + */ + peek(key: KeyType): ValueType | undefined; + + /** + Delete an item. + + @returns `true` if the item is removed or `false` if the item doesn't exist. + */ + delete(key: KeyType): boolean; + + /** + Delete all items. + */ + clear(): void; + + /** + Update the `maxSize` in-place, discarding items as necessary. Insertion order is mostly preserved, though this is not a strong guarantee. + + Useful for on-the-fly tuning of cache sizes in live systems. + */ + resize(maxSize: number): void; + + /** + Iterable for all the keys. + */ + keys(): IterableIterator; + + /** + Iterable for all the values. + */ + values(): IterableIterator; + + /** + Iterable for all entries, starting with the oldest (ascending in recency). + */ + entriesAscending(): IterableIterator<[KeyType, ValueType]>; + + /** + Iterable for all entries, starting with the newest (descending in recency). + */ + entriesDescending(): IterableIterator<[KeyType, ValueType]>; +} + +export = QuickLRU; diff --git a/client/node_modules/@alloc/quick-lru/index.js b/client/node_modules/@alloc/quick-lru/index.js new file mode 100644 index 0000000..7eeced2 --- /dev/null +++ b/client/node_modules/@alloc/quick-lru/index.js @@ -0,0 +1,263 @@ +'use strict'; + +class QuickLRU { + constructor(options = {}) { + if (!(options.maxSize && options.maxSize > 0)) { + throw new TypeError('`maxSize` must be a number greater than 0'); + } + + if (typeof options.maxAge === 'number' && options.maxAge === 0) { + throw new TypeError('`maxAge` must be a number greater than 0'); + } + + this.maxSize = options.maxSize; + this.maxAge = options.maxAge || Infinity; + this.onEviction = options.onEviction; + this.cache = new Map(); + this.oldCache = new Map(); + this._size = 0; + } + + _emitEvictions(cache) { + if (typeof this.onEviction !== 'function') { + return; + } + + for (const [key, item] of cache) { + this.onEviction(key, item.value); + } + } + + _deleteIfExpired(key, item) { + if (typeof item.expiry === 'number' && item.expiry <= Date.now()) { + if (typeof this.onEviction === 'function') { + this.onEviction(key, item.value); + } + + return this.delete(key); + } + + return false; + } + + _getOrDeleteIfExpired(key, item) { + const deleted = this._deleteIfExpired(key, item); + if (deleted === false) { + return item.value; + } + } + + _getItemValue(key, item) { + return item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value; + } + + _peek(key, cache) { + const item = cache.get(key); + + return this._getItemValue(key, item); + } + + _set(key, value) { + this.cache.set(key, value); + this._size++; + + if (this._size >= this.maxSize) { + this._size = 0; + this._emitEvictions(this.oldCache); + this.oldCache = this.cache; + this.cache = new Map(); + } + } + + _moveToRecent(key, item) { + this.oldCache.delete(key); + this._set(key, item); + } + + * _entriesAscending() { + for (const item of this.oldCache) { + const [key, value] = item; + if (!this.cache.has(key)) { + const deleted = this._deleteIfExpired(key, value); + if (deleted === false) { + yield item; + } + } + } + + for (const item of this.cache) { + const [key, value] = item; + const deleted = this._deleteIfExpired(key, value); + if (deleted === false) { + yield item; + } + } + } + + get(key) { + if (this.cache.has(key)) { + const item = this.cache.get(key); + + return this._getItemValue(key, item); + } + + if (this.oldCache.has(key)) { + const item = this.oldCache.get(key); + if (this._deleteIfExpired(key, item) === false) { + this._moveToRecent(key, item); + return item.value; + } + } + } + + set(key, value, {maxAge = this.maxAge === Infinity ? undefined : Date.now() + this.maxAge} = {}) { + if (this.cache.has(key)) { + this.cache.set(key, { + value, + maxAge + }); + } else { + this._set(key, {value, expiry: maxAge}); + } + } + + has(key) { + if (this.cache.has(key)) { + return !this._deleteIfExpired(key, this.cache.get(key)); + } + + if (this.oldCache.has(key)) { + return !this._deleteIfExpired(key, this.oldCache.get(key)); + } + + return false; + } + + peek(key) { + if (this.cache.has(key)) { + return this._peek(key, this.cache); + } + + if (this.oldCache.has(key)) { + return this._peek(key, this.oldCache); + } + } + + delete(key) { + const deleted = this.cache.delete(key); + if (deleted) { + this._size--; + } + + return this.oldCache.delete(key) || deleted; + } + + clear() { + this.cache.clear(); + this.oldCache.clear(); + this._size = 0; + } + + resize(newSize) { + if (!(newSize && newSize > 0)) { + throw new TypeError('`maxSize` must be a number greater than 0'); + } + + const items = [...this._entriesAscending()]; + const removeCount = items.length - newSize; + if (removeCount < 0) { + this.cache = new Map(items); + this.oldCache = new Map(); + this._size = items.length; + } else { + if (removeCount > 0) { + this._emitEvictions(items.slice(0, removeCount)); + } + + this.oldCache = new Map(items.slice(removeCount)); + this.cache = new Map(); + this._size = 0; + } + + this.maxSize = newSize; + } + + * keys() { + for (const [key] of this) { + yield key; + } + } + + * values() { + for (const [, value] of this) { + yield value; + } + } + + * [Symbol.iterator]() { + for (const item of this.cache) { + const [key, value] = item; + const deleted = this._deleteIfExpired(key, value); + if (deleted === false) { + yield [key, value.value]; + } + } + + for (const item of this.oldCache) { + const [key, value] = item; + if (!this.cache.has(key)) { + const deleted = this._deleteIfExpired(key, value); + if (deleted === false) { + yield [key, value.value]; + } + } + } + } + + * entriesDescending() { + let items = [...this.cache]; + for (let i = items.length - 1; i >= 0; --i) { + const item = items[i]; + const [key, value] = item; + const deleted = this._deleteIfExpired(key, value); + if (deleted === false) { + yield [key, value.value]; + } + } + + items = [...this.oldCache]; + for (let i = items.length - 1; i >= 0; --i) { + const item = items[i]; + const [key, value] = item; + if (!this.cache.has(key)) { + const deleted = this._deleteIfExpired(key, value); + if (deleted === false) { + yield [key, value.value]; + } + } + } + } + + * entriesAscending() { + for (const [key, value] of this._entriesAscending()) { + yield [key, value.value]; + } + } + + get size() { + if (!this._size) { + return this.oldCache.size; + } + + let oldCacheSize = 0; + for (const key of this.oldCache.keys()) { + if (!this.cache.has(key)) { + oldCacheSize++; + } + } + + return Math.min(this._size + oldCacheSize, this.maxSize); + } +} + +module.exports = QuickLRU; diff --git a/client/node_modules/@alloc/quick-lru/license b/client/node_modules/@alloc/quick-lru/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/client/node_modules/@alloc/quick-lru/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/client/node_modules/@alloc/quick-lru/package.json b/client/node_modules/@alloc/quick-lru/package.json new file mode 100644 index 0000000..21f1072 --- /dev/null +++ b/client/node_modules/@alloc/quick-lru/package.json @@ -0,0 +1,43 @@ +{ + "name": "@alloc/quick-lru", + "version": "5.2.0", + "description": "Simple “Least Recently Used” (LRU) cache", + "license": "MIT", + "repository": "sindresorhus/quick-lru", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && nyc ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "lru", + "quick", + "cache", + "caching", + "least", + "recently", + "used", + "fast", + "map", + "hash", + "buffer" + ], + "devDependencies": { + "ava": "^2.0.0", + "coveralls": "^3.0.3", + "nyc": "^15.0.0", + "tsd": "^0.11.0", + "xo": "^0.26.0" + } +} diff --git a/client/node_modules/@alloc/quick-lru/readme.md b/client/node_modules/@alloc/quick-lru/readme.md new file mode 100644 index 0000000..7187ba5 --- /dev/null +++ b/client/node_modules/@alloc/quick-lru/readme.md @@ -0,0 +1,139 @@ +# quick-lru [![Build Status](https://travis-ci.org/sindresorhus/quick-lru.svg?branch=master)](https://travis-ci.org/sindresorhus/quick-lru) [![Coverage Status](https://coveralls.io/repos/github/sindresorhus/quick-lru/badge.svg?branch=master)](https://coveralls.io/github/sindresorhus/quick-lru?branch=master) + +> Simple [“Least Recently Used” (LRU) cache](https://en.m.wikipedia.org/wiki/Cache_replacement_policies#Least_Recently_Used_.28LRU.29) + +Useful when you need to cache something and limit memory usage. + +Inspired by the [`hashlru` algorithm](https://github.com/dominictarr/hashlru#algorithm), but instead uses [`Map`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map) to support keys of any type, not just strings, and values can be `undefined`. + +## Install + +``` +$ npm install quick-lru +``` + +## Usage + +```js +const QuickLRU = require('quick-lru'); + +const lru = new QuickLRU({maxSize: 1000}); + +lru.set('🦄', '🌈'); + +lru.has('🦄'); +//=> true + +lru.get('🦄'); +//=> '🌈' +``` + +## API + +### new QuickLRU(options?) + +Returns a new instance. + +### options + +Type: `object` + +#### maxSize + +*Required*\ +Type: `number` + +The maximum number of items before evicting the least recently used items. + +#### maxAge + +Type: `number`\ +Default: `Infinity` + +The maximum number of milliseconds an item should remain in cache. +By default maxAge will be Infinity, which means that items will never expire. + +Lazy expiration happens upon the next `write` or `read` call. + +Individual expiration of an item can be specified by the `set(key, value, options)` method. + +#### onEviction + +*Optional*\ +Type: `(key, value) => void` + +Called right before an item is evicted from the cache. + +Useful for side effects or for items like object URLs that need explicit cleanup (`revokeObjectURL`). + +### Instance + +The instance is [`iterable`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols) so you can use it directly in a [`for…of`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of) loop. + +Both `key` and `value` can be of any type. + +#### .set(key, value, options?) + +Set an item. Returns the instance. + +Individual expiration of an item can be specified with the `maxAge` option. If not specified, the global `maxAge` value will be used in case it is specified on the constructor, otherwise the item will never expire. + +#### .get(key) + +Get an item. + +#### .has(key) + +Check if an item exists. + +#### .peek(key) + +Get an item without marking it as recently used. + +#### .delete(key) + +Delete an item. + +Returns `true` if the item is removed or `false` if the item doesn't exist. + +#### .clear() + +Delete all items. + +#### .resize(maxSize) + +Update the `maxSize`, discarding items as necessary. Insertion order is mostly preserved, though this is not a strong guarantee. + +Useful for on-the-fly tuning of cache sizes in live systems. + +#### .keys() + +Iterable for all the keys. + +#### .values() + +Iterable for all the values. + +#### .entriesAscending() + +Iterable for all entries, starting with the oldest (ascending in recency). + +#### .entriesDescending() + +Iterable for all entries, starting with the newest (descending in recency). + +#### .size + +The stored item count. + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/client/node_modules/@tailwindcss/node/LICENSE b/client/node_modules/@tailwindcss/node/LICENSE new file mode 100644 index 0000000..d6a8229 --- /dev/null +++ b/client/node_modules/@tailwindcss/node/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Tailwind Labs, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/client/node_modules/@tailwindcss/node/README.md b/client/node_modules/@tailwindcss/node/README.md new file mode 100644 index 0000000..5f53260 --- /dev/null +++ b/client/node_modules/@tailwindcss/node/README.md @@ -0,0 +1,36 @@ +

+ + + + + Tailwind CSS + + +

+ +

+ A utility-first CSS framework for rapidly building custom user interfaces. +

+ +

+ Build Status + Total Downloads + Latest Release + License +

+ +--- + +## Documentation + +For full documentation, visit [tailwindcss.com](https://tailwindcss.com). + +## Community + +For help, discussion about best practices, or feature ideas: + +[Discuss Tailwind CSS on GitHub](https://github.com/tailwindlabs/tailwindcss/discussions) + +## Contributing + +If you're interested in contributing to Tailwind CSS, please read our [contributing docs](https://github.com/tailwindlabs/tailwindcss/blob/main/.github/CONTRIBUTING.md) **before submitting a pull request**. diff --git a/client/node_modules/@tailwindcss/node/dist/esm-cache.loader.d.mts b/client/node_modules/@tailwindcss/node/dist/esm-cache.loader.d.mts new file mode 100644 index 0000000..66006c6 --- /dev/null +++ b/client/node_modules/@tailwindcss/node/dist/esm-cache.loader.d.mts @@ -0,0 +1,6 @@ +import { ResolveHook, ResolveHookSync } from 'node:module'; + +declare let resolve: ResolveHook; +declare let resolveSync: ResolveHookSync; + +export { resolve, resolveSync }; diff --git a/client/node_modules/@tailwindcss/node/dist/esm-cache.loader.mjs b/client/node_modules/@tailwindcss/node/dist/esm-cache.loader.mjs new file mode 100644 index 0000000..a616bb0 --- /dev/null +++ b/client/node_modules/@tailwindcss/node/dist/esm-cache.loader.mjs @@ -0,0 +1 @@ +import{isBuiltin as p}from"module";var u=async(r,e,t)=>{let o=await t(r,e);return n(e,o)},a=(r,e,t)=>{let o=t(r,e);return n(e,o)};function n(r,e){if(e.url===import.meta.url||p(e.url)||!r.parentURL)return e;let o=new URL(r.parentURL).searchParams.get("id");if(o===null)return e;let l=new URL(e.url);return l.searchParams.set("id",o),{...e,url:`${l}`}}export{u as resolve,a as resolveSync}; diff --git a/client/node_modules/@tailwindcss/node/dist/index.d.mts b/client/node_modules/@tailwindcss/node/dist/index.d.mts new file mode 100644 index 0000000..23a898b --- /dev/null +++ b/client/node_modules/@tailwindcss/node/dist/index.d.mts @@ -0,0 +1,262 @@ +import { AstNode as AstNode$1 } from './ast'; +import { Candidate, Variant } from './candidate'; +import { compileAstNodes } from './compile'; +import { ClassEntry, VariantEntry, CanonicalizeOptions } from './intellisense'; +import { Theme } from './theme'; +import { Utilities } from './utilities'; +import { Variants } from './variants'; +import * as tailwindcss from 'tailwindcss'; +import { Polyfills, Features } from 'tailwindcss'; +export { Features, Polyfills } from 'tailwindcss'; + +declare const DEBUG: boolean; + +declare const env_DEBUG: typeof DEBUG; +declare namespace env { + export { env_DEBUG as DEBUG }; +} + +declare const enum CompileAstFlags { + None = 0, + RespectImportant = 1 +} +type DesignSystem = { + theme: Theme; + utilities: Utilities; + variants: Variants; + invalidCandidates: Set; + important: boolean; + getClassOrder(classes: string[]): [string, bigint | null][]; + getClassList(): ClassEntry[]; + getVariants(): VariantEntry[]; + parseCandidate(candidate: string): Readonly[]; + parseVariant(variant: string): Readonly | null; + compileAstNodes(candidate: Candidate, flags?: CompileAstFlags): ReturnType; + printCandidate(candidate: Candidate): string; + printVariant(variant: Variant): string; + getVariantOrder(): Map; + resolveThemeValue(path: string, forceInline?: boolean): string | undefined; + trackUsedVariables(raw: string): void; + canonicalizeCandidates(candidates: string[], options?: CanonicalizeOptions): string[]; + candidatesToCss(classes: string[]): (string | null)[]; + candidatesToAst(classes: string[]): AstNode$1[][]; + storage: Record; +}; + +/** + * The source code for one or more nodes in the AST + * + * This generally corresponds to a stylesheet + */ +interface Source { + /** + * The path to the file that contains the referenced source code + * + * If this references the *output* source code, this is `null`. + */ + file: string | null; + /** + * The referenced source code + */ + code: string; +} +/** + * The file and offsets within it that this node covers + * + * This can represent either: + * - A location in the original CSS which caused this node to be created + * - A location in the output CSS where this node resides + */ +type SourceLocation = [source: Source, start: number, end: number]; + +/** + * Line offset tables are the key to generating our source maps. They allow us + * to store indexes with our AST nodes and later convert them into positions as + * when given the source that the indexes refer to. + */ +/** + * A position in source code + * + * https://tc39.es/ecma426/#sec-position-record-type + */ +interface Position { + /** The line number, one-based */ + line: number; + /** The column/character number, one-based */ + column: number; +} + +interface OriginalPosition extends Position { + source: DecodedSource; +} +/** + * A "decoded" sourcemap + * + * @see https://tc39.es/ecma426/#decoded-source-map-record + */ +interface DecodedSourceMap { + file: string | null; + sources: DecodedSource[]; + mappings: DecodedMapping[]; +} +/** + * A "decoded" source + * + * @see https://tc39.es/ecma426/#decoded-source-record + */ +interface DecodedSource { + url: string | null; + content: string | null; + ignore: boolean; +} +/** + * A "decoded" mapping + * + * @see https://tc39.es/ecma426/#decoded-mapping-record + */ +interface DecodedMapping { + originalPosition: OriginalPosition | null; + generatedPosition: Position; + name: string | null; +} + +type StyleRule = { + kind: 'rule'; + selector: string; + nodes: AstNode[]; + src?: SourceLocation; + dst?: SourceLocation; +}; +type AtRule = { + kind: 'at-rule'; + name: string; + params: string; + nodes: AstNode[]; + src?: SourceLocation; + dst?: SourceLocation; +}; +type Declaration = { + kind: 'declaration'; + property: string; + value: string | undefined; + important: boolean; + src?: SourceLocation; + dst?: SourceLocation; +}; +type Comment = { + kind: 'comment'; + value: string; + src?: SourceLocation; + dst?: SourceLocation; +}; +type Context = { + kind: 'context'; + context: Record; + nodes: AstNode[]; + src?: undefined; + dst?: undefined; +}; +type AtRoot = { + kind: 'at-root'; + nodes: AstNode[]; + src?: undefined; + dst?: undefined; +}; +type AstNode = StyleRule | AtRule | Declaration | Comment | Context | AtRoot; + +type Resolver = (id: string, base: string) => Promise; +interface CompileOptions { + base: string; + from?: string; + onDependency: (path: string) => void; + shouldRewriteUrls?: boolean; + polyfills?: Polyfills; + customCssResolver?: Resolver; + customJsResolver?: Resolver; +} +declare function compileAst(ast: AstNode[], options: CompileOptions): Promise<{ + sources: { + base: string; + pattern: string; + negated: boolean; + }[]; + root: "none" | { + base: string; + pattern: string; + } | null; + features: Features; + build(candidates: string[]): AstNode[]; +}>; +declare function compile(css: string, options: CompileOptions): Promise<{ + sources: { + base: string; + pattern: string; + negated: boolean; + }[]; + root: "none" | { + base: string; + pattern: string; + } | null; + features: Features; + build(candidates: string[]): string; + buildSourceMap(): tailwindcss.DecodedSourceMap; +}>; +declare function __unstable__loadDesignSystem(css: string, { base }: { + base: string; +}): Promise; +declare function loadModule(id: string, base: string, onDependency: (path: string) => void, customJsResolver?: Resolver): Promise<{ + path: string; + base: string; + module: any; +}>; + +declare class Instrumentation implements Disposable { + #private; + private shouldReport; + private defaultFlush; + constructor(shouldReport?: boolean, defaultFlush?: (message: string) => undefined); + hit(label: string): void; + start(label: string): void; + end(label: string): void; + track(label: string): { + [Symbol.dispose]: () => void; + [Symbol.asyncDispose]: () => void; + }; + span(label: string, fn: () => T): T; + reset(): void; + report(flush?: (message: string) => undefined): void; + [Symbol.dispose](): void; +} + +declare function normalizePath(originalPath: string): string; + +interface OptimizeOptions { + /** + * The file being transformed + */ + file?: string; + /** + * Enabled minified output + */ + minify?: boolean; + /** + * The output source map before optimization + * + * If omitted a resulting source map will not be available + */ + map?: string; +} +interface TransformResult { + code: string; + map: string | undefined; +} +declare function optimize(input: string, { file, minify, map }?: OptimizeOptions): TransformResult; + +interface SourceMap { + readonly raw: string; + readonly inline: string; + comment(url: string): string; +} +declare function toSourceMap(map: DecodedSourceMap | string): SourceMap; + +export { type CompileOptions, type DecodedSource, type DecodedSourceMap, Instrumentation, type OptimizeOptions, type Resolver, type SourceMap, type TransformResult, __unstable__loadDesignSystem, compile, compileAst, env, loadModule, normalizePath, optimize, toSourceMap }; diff --git a/client/node_modules/@tailwindcss/node/dist/index.d.ts b/client/node_modules/@tailwindcss/node/dist/index.d.ts new file mode 100644 index 0000000..23a898b --- /dev/null +++ b/client/node_modules/@tailwindcss/node/dist/index.d.ts @@ -0,0 +1,262 @@ +import { AstNode as AstNode$1 } from './ast'; +import { Candidate, Variant } from './candidate'; +import { compileAstNodes } from './compile'; +import { ClassEntry, VariantEntry, CanonicalizeOptions } from './intellisense'; +import { Theme } from './theme'; +import { Utilities } from './utilities'; +import { Variants } from './variants'; +import * as tailwindcss from 'tailwindcss'; +import { Polyfills, Features } from 'tailwindcss'; +export { Features, Polyfills } from 'tailwindcss'; + +declare const DEBUG: boolean; + +declare const env_DEBUG: typeof DEBUG; +declare namespace env { + export { env_DEBUG as DEBUG }; +} + +declare const enum CompileAstFlags { + None = 0, + RespectImportant = 1 +} +type DesignSystem = { + theme: Theme; + utilities: Utilities; + variants: Variants; + invalidCandidates: Set; + important: boolean; + getClassOrder(classes: string[]): [string, bigint | null][]; + getClassList(): ClassEntry[]; + getVariants(): VariantEntry[]; + parseCandidate(candidate: string): Readonly[]; + parseVariant(variant: string): Readonly | null; + compileAstNodes(candidate: Candidate, flags?: CompileAstFlags): ReturnType; + printCandidate(candidate: Candidate): string; + printVariant(variant: Variant): string; + getVariantOrder(): Map; + resolveThemeValue(path: string, forceInline?: boolean): string | undefined; + trackUsedVariables(raw: string): void; + canonicalizeCandidates(candidates: string[], options?: CanonicalizeOptions): string[]; + candidatesToCss(classes: string[]): (string | null)[]; + candidatesToAst(classes: string[]): AstNode$1[][]; + storage: Record; +}; + +/** + * The source code for one or more nodes in the AST + * + * This generally corresponds to a stylesheet + */ +interface Source { + /** + * The path to the file that contains the referenced source code + * + * If this references the *output* source code, this is `null`. + */ + file: string | null; + /** + * The referenced source code + */ + code: string; +} +/** + * The file and offsets within it that this node covers + * + * This can represent either: + * - A location in the original CSS which caused this node to be created + * - A location in the output CSS where this node resides + */ +type SourceLocation = [source: Source, start: number, end: number]; + +/** + * Line offset tables are the key to generating our source maps. They allow us + * to store indexes with our AST nodes and later convert them into positions as + * when given the source that the indexes refer to. + */ +/** + * A position in source code + * + * https://tc39.es/ecma426/#sec-position-record-type + */ +interface Position { + /** The line number, one-based */ + line: number; + /** The column/character number, one-based */ + column: number; +} + +interface OriginalPosition extends Position { + source: DecodedSource; +} +/** + * A "decoded" sourcemap + * + * @see https://tc39.es/ecma426/#decoded-source-map-record + */ +interface DecodedSourceMap { + file: string | null; + sources: DecodedSource[]; + mappings: DecodedMapping[]; +} +/** + * A "decoded" source + * + * @see https://tc39.es/ecma426/#decoded-source-record + */ +interface DecodedSource { + url: string | null; + content: string | null; + ignore: boolean; +} +/** + * A "decoded" mapping + * + * @see https://tc39.es/ecma426/#decoded-mapping-record + */ +interface DecodedMapping { + originalPosition: OriginalPosition | null; + generatedPosition: Position; + name: string | null; +} + +type StyleRule = { + kind: 'rule'; + selector: string; + nodes: AstNode[]; + src?: SourceLocation; + dst?: SourceLocation; +}; +type AtRule = { + kind: 'at-rule'; + name: string; + params: string; + nodes: AstNode[]; + src?: SourceLocation; + dst?: SourceLocation; +}; +type Declaration = { + kind: 'declaration'; + property: string; + value: string | undefined; + important: boolean; + src?: SourceLocation; + dst?: SourceLocation; +}; +type Comment = { + kind: 'comment'; + value: string; + src?: SourceLocation; + dst?: SourceLocation; +}; +type Context = { + kind: 'context'; + context: Record; + nodes: AstNode[]; + src?: undefined; + dst?: undefined; +}; +type AtRoot = { + kind: 'at-root'; + nodes: AstNode[]; + src?: undefined; + dst?: undefined; +}; +type AstNode = StyleRule | AtRule | Declaration | Comment | Context | AtRoot; + +type Resolver = (id: string, base: string) => Promise; +interface CompileOptions { + base: string; + from?: string; + onDependency: (path: string) => void; + shouldRewriteUrls?: boolean; + polyfills?: Polyfills; + customCssResolver?: Resolver; + customJsResolver?: Resolver; +} +declare function compileAst(ast: AstNode[], options: CompileOptions): Promise<{ + sources: { + base: string; + pattern: string; + negated: boolean; + }[]; + root: "none" | { + base: string; + pattern: string; + } | null; + features: Features; + build(candidates: string[]): AstNode[]; +}>; +declare function compile(css: string, options: CompileOptions): Promise<{ + sources: { + base: string; + pattern: string; + negated: boolean; + }[]; + root: "none" | { + base: string; + pattern: string; + } | null; + features: Features; + build(candidates: string[]): string; + buildSourceMap(): tailwindcss.DecodedSourceMap; +}>; +declare function __unstable__loadDesignSystem(css: string, { base }: { + base: string; +}): Promise; +declare function loadModule(id: string, base: string, onDependency: (path: string) => void, customJsResolver?: Resolver): Promise<{ + path: string; + base: string; + module: any; +}>; + +declare class Instrumentation implements Disposable { + #private; + private shouldReport; + private defaultFlush; + constructor(shouldReport?: boolean, defaultFlush?: (message: string) => undefined); + hit(label: string): void; + start(label: string): void; + end(label: string): void; + track(label: string): { + [Symbol.dispose]: () => void; + [Symbol.asyncDispose]: () => void; + }; + span(label: string, fn: () => T): T; + reset(): void; + report(flush?: (message: string) => undefined): void; + [Symbol.dispose](): void; +} + +declare function normalizePath(originalPath: string): string; + +interface OptimizeOptions { + /** + * The file being transformed + */ + file?: string; + /** + * Enabled minified output + */ + minify?: boolean; + /** + * The output source map before optimization + * + * If omitted a resulting source map will not be available + */ + map?: string; +} +interface TransformResult { + code: string; + map: string | undefined; +} +declare function optimize(input: string, { file, minify, map }?: OptimizeOptions): TransformResult; + +interface SourceMap { + readonly raw: string; + readonly inline: string; + comment(url: string): string; +} +declare function toSourceMap(map: DecodedSourceMap | string): SourceMap; + +export { type CompileOptions, type DecodedSource, type DecodedSourceMap, Instrumentation, type OptimizeOptions, type Resolver, type SourceMap, type TransformResult, __unstable__loadDesignSystem, compile, compileAst, env, loadModule, normalizePath, optimize, toSourceMap }; diff --git a/client/node_modules/@tailwindcss/node/dist/index.js b/client/node_modules/@tailwindcss/node/dist/index.js new file mode 100644 index 0000000..8759666 --- /dev/null +++ b/client/node_modules/@tailwindcss/node/dist/index.js @@ -0,0 +1,18 @@ +"use strict";var zt=Object.create;var ae=Object.defineProperty;var Kt=Object.getOwnPropertyDescriptor;var Mt=Object.getOwnPropertyNames;var Ft=Object.getPrototypeOf,jt=Object.prototype.hasOwnProperty;var Fe=(e,r)=>{for(var t in r)ae(e,t,{get:r[t],enumerable:!0})},je=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Mt(r))!jt.call(e,i)&&i!==t&&ae(e,i,{get:()=>r[i],enumerable:!(n=Kt(r,i))||n.enumerable});return e};var T=(e,r,t)=>(t=e!=null?zt(Ft(e)):{},je(r||!e||!e.__esModule?ae(t,"default",{value:e,enumerable:!0}):t,e)),Wt=e=>je(ae({},"__esModule",{value:!0}),e);var kn={};Fe(kn,{Features:()=>_.Features,Instrumentation:()=>Me,Polyfills:()=>_.Polyfills,__unstable__loadDesignSystem:()=>sn,compile:()=>an,compileAst:()=>ln,env:()=>se,loadModule:()=>ze,normalizePath:()=>ve,optimize:()=>mn,toSourceMap:()=>vn});module.exports=Wt(kn);var le=T(require("module")),Lt=require("url");var se={};Fe(se,{DEBUG:()=>be});var be=Bt(process.env.DEBUG);function Bt(e){if(typeof e=="boolean")return e;if(e===void 0)return!1;if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1;if(e==="*")return!0;let r=e.split(",").map(t=>t.split(":")[0]);return r.includes("-tailwindcss")?!1:!!r.includes("tailwindcss")}var We=require("module"),Gt={};var Be=(e,r,t)=>{let n=t(e,r);return Yt(r,n)};function Yt(e,r){if(r.url===Gt.url||(0,We.isBuiltin)(r.url)||!e.parentURL)return r;let n=new URL(e.parentURL).searchParams.get("id");if(n===null)return r;let i=new URL(r.url);return i.searchParams.set("id",n),{...r,url:`${i}`}}var W=T(require("enhanced-resolve")),Nt=require("jiti"),ke=T(require("fs")),Le=T(require("fs/promises")),q=T(require("path")),Ie=require("url"),_=require("tailwindcss");var ue=T(require("fs/promises")),Y=T(require("path")),Ht=[/import[\s\S]*?['"](.{3,}?)['"]/gi,/import[\s\S]*from[\s\S]*?['"](.{3,}?)['"]/gi,/export[\s\S]*from[\s\S]*?['"](.{3,}?)['"]/gi,/require\(['"`](.+)['"`]\)/gi],qt=[".js",".cjs",".mjs"],Zt=["",".js",".cjs",".mjs",".ts",".cts",".mts",".jsx",".tsx"],Qt=["",".ts",".cts",".mts",".tsx",".js",".cjs",".mjs",".jsx"];async function Jt(e,r){for(let t of r){let n=`${e}${t}`;if((await ue.default.stat(n).catch(()=>null))?.isFile())return n}for(let t of r){let n=`${e}/index${t}`;if(await ue.default.access(n).then(()=>!0,()=>!1))return n}return null}async function Ye(e,r,t,n){let i=qt.includes(n)?Zt:Qt,l=await Jt(Y.default.resolve(t,r),i);if(l===null||e.has(l))return;e.add(l),t=Y.default.dirname(l),n=Y.default.extname(l);let o=await ue.default.readFile(l,"utf-8"),s=[];for(let a of Ht)for(let u of o.matchAll(a))u[1].startsWith(".")&&s.push(Ye(e,u[1],t,n));await Promise.all(s)}async function Ge(e){let r=new Set;return await Ye(r,e,Y.default.dirname(e),Y.default.extname(e)),Array.from(r)}var _e=T(require("path"));function G(e){return{kind:"word",value:e}}function Xt(e,r){return{kind:"function",value:e,nodes:r}}function er(e){return{kind:"separator",value:e}}function A(e){let r="";for(let t of e)switch(t.kind){case"word":case"separator":{r+=t.value;break}case"function":r+=t.value+"("+A(t.nodes)+")"}return r}var He=92,tr=41,qe=58,Ze=44,rr=34,Qe=61,Je=62,Xe=60,et=10,nr=40,ir=39,or=47,tt=32,rt=9;function y(e){e=e.replaceAll(`\r +`,` +`);let r=[],t=[],n=null,i="",l;for(let o=0;o0){let u=G(i);n?n.nodes.push(u):r.push(u),i=""}let a=G(e[o]);n?n.nodes.push(a):r.push(a);break}case qe:case Ze:case Qe:case Je:case Xe:case et:case tt:case rt:{if(i.length>0){let c=G(i);n?n.nodes.push(c):r.push(c),i=""}let a=o,u=o+1;for(;u0){let u=G(i);a?.nodes.push(u),i=""}t.length>0?n=t[t.length-1]:n=null;break}default:i+=String.fromCharCode(s)}}return i.length>0&&r.push(G(i)),r}var h=class extends Map{constructor(t){super();this.factory=t}factory;get(t){let n=super.get(t);return n===void 0&&(n=this.factory(t,this),this.set(t,n)),n}};var $n=new Uint8Array(256);var ce=new Uint8Array(256);function w(e,r){let t=0,n=[],i=0,l=e.length,o=r.charCodeAt(0);for(let s=0;s0&&a===ce[t-1]&&t--;break}}return n.push(e.slice(i)),n}var ye=(o=>(o[o.Continue=0]="Continue",o[o.Skip=1]="Skip",o[o.Stop=2]="Stop",o[o.Replace=3]="Replace",o[o.ReplaceSkip=4]="ReplaceSkip",o[o.ReplaceStop=5]="ReplaceStop",o))(ye||{}),v={Continue:{kind:0},Skip:{kind:1},Stop:{kind:2},Replace:e=>({kind:3,nodes:Array.isArray(e)?e:[e]}),ReplaceSkip:e=>({kind:4,nodes:Array.isArray(e)?e:[e]}),ReplaceStop:e=>({kind:5,nodes:Array.isArray(e)?e:[e]})};function g(e,r){typeof r=="function"?nt(e,r):nt(e,r.enter,r.exit)}function nt(e,r=()=>v.Continue,t=()=>v.Continue){let n={value:[e,0,null],prev:null},i={parent:null,depth:0,index:0,siblings:e,path(){let l=[],o=n;for(;o;){let s=o.value[2];s&&l.push(s),o=o.prev}return l.reverse(),l}};for(;n!==null;){let l=n.value,o=l[0],s=l[1],a=l[2];if(s>=o.length){n=n.prev,i.depth-=1;continue}if(i.parent=a,i.siblings=o,s>=0){i.index=s;let f=o[s],d=r(f,i)??v.Continue;switch(d.kind){case 0:{f.nodes&&f.nodes.length>0&&(i.depth+=1,n={value:[f.nodes,0,f],prev:n}),l[1]=~s;continue}case 2:return;case 1:{l[1]=~s;continue}case 3:{o.splice(s,1,...d.nodes);continue}case 5:{o.splice(s,1,...d.nodes);return}case 4:{o.splice(s,1,...d.nodes),l[1]+=d.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${ye[d.kind]??`Unknown(${d.kind})`}\` in enter.`)}}let u=~s;i.index=u;let p=o[u],c=t(p,i)??v.Continue;switch(c.kind){case 0:l[1]=u+1;continue;case 2:return;case 3:{o.splice(u,1,...c.nodes),l[1]=u+c.nodes.length;continue}case 5:{o.splice(u,1,...c.nodes);return}case 4:{o.splice(u,1,...c.nodes),l[1]=u+c.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${ye[c.kind]??`Unknown(${c.kind})`}\` in exit.`)}}}var Un=new h(e=>{let r=y(e),t=new Set,n=new Set(["~",">","+","-","*","/"]);return g(r,(i,l)=>{if(i.kind==="word"&&n.has(i.value)){let o=l.index;if(o===-1)return;let s=l.siblings[o-1];if(s?.kind!=="separator"||s.value!==" ")return;let a=l.siblings[o+1];if(a?.kind!=="separator"||a.value!==" ")return;let u=l.siblings[o-2];if(u&&n.has(u.value))return;let p=l.siblings[o+2];if(p&&n.has(p.value))return;t.add(s),t.add(a)}else if(i.kind==="separator"&&i.value.length>0&&i.value.trim()==="")(l.siblings[0]===i||l.siblings[l.siblings.length-1]===i)&&t.add(i);else if(i.kind==="separator"&&i.value.trim()===",")i.value=",";else if(i.kind==="function"&&i.value.startsWith("--")){let o=l.index;if(o<=0)return;let s=l.siblings[o-1];if(s?.kind==="separator"&&s.value===",")return;let a=l.siblings[o-2];return a&&!n.has(a.value)?void 0:v.ReplaceSkip({kind:"function",value:"",nodes:[i]})}}),t.size>0&&g(r,i=>{if(t.has(i))return t.delete(i),v.ReplaceSkip([])}),xe(r),A(r)});var Ln=new h(e=>{let r=y(e);return r.length===3&&r[0].kind==="word"&&r[0].value==="&"&&r[1].kind==="separator"&&r[1].value===":"&&r[2].kind==="function"&&r[2].value==="is"?A(r[2].nodes):e});function xe(e){for(let r of e)switch(r.kind){case"function":{if(r.value==="url"||r.value.endsWith("_url")){r.value=Z(r.value);break}if(r.value==="var"||r.value.endsWith("_var")||r.value==="theme"||r.value.endsWith("_theme")){r.value=Z(r.value);for(let t=0;t{let r=y(e);return r.length===1&&r[0].kind==="function"&&r[0].value==="var"});function ar(e){throw new Error(`Unexpected value: ${e}`)}function Z(e){return e.replaceAll("_",String.raw`\_`).replaceAll(" ","_")}var sr=/^(?[-+]?(?:\d*\.)?\d+)(?[a-z]+|%)?$/i,H=new h(e=>{let r=sr.exec(e);if(!r)return null;let t=r.groups?.value;if(t===void 0)return null;let n=Number(t);if(Number.isNaN(n))return null;let i=r.groups?.unit;return i===void 0?[n,null]:[n,i]});var D=/[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?/,Qn=new RegExp(`^${D.source}$`);var Jn=new RegExp(`^${D.source}%$`);var Xn=new RegExp(`^${D.source}\\s*/\\s*${D.source}$`);var ur=["cm","mm","Q","in","pc","pt","px","em","ex","ch","rem","lh","rlh","vw","vh","vmin","vmax","vb","vi","svw","svh","lvw","lvh","dvw","dvh","cqw","cqh","cqi","cqb","cqmin","cqmax"],ei=new RegExp(`^${D.source}(${ur.join("|")})$`);var cr=["deg","rad","grad","turn"],ti=new RegExp(`^${D.source}(${cr.join("|")})$`);var ri=new RegExp(`^${D.source} +${D.source} +${D.source}$`);function S(e){let r=Number(e);return Number.isInteger(r)&&r>=0&&String(r)===String(e)}function Q(e,r){if(r===null)return e;let t=Number(r);return Number.isNaN(t)||(r=`${t*100}%`),r==="100%"?e:`color-mix(in oklab, ${e} ${r}, transparent)`}var dr={"--alpha":mr,"--spacing":gr,"--theme":hr,theme:vr};function mr(e,r,t,...n){let[i,l]=w(t,"/").map(o=>o.trim());if(!i||!l)throw new Error(`The --alpha(\u2026) function requires a color and an alpha value, e.g.: \`--alpha(${i||"var(--my-color)"} / ${l||"50%"})\``);if(n.length>0)throw new Error(`The --alpha(\u2026) function only accepts one argument, e.g.: \`--alpha(${i||"var(--my-color)"} / ${l||"50%"})\``);return Q(i,l)}function gr(e,r,t,...n){if(!t)throw new Error("The --spacing(\u2026) function requires an argument, but received none.");if(n.length>0)throw new Error(`The --spacing(\u2026) function only accepts a single argument, but received ${n.length+1}.`);let i=e.theme.resolve(null,["--spacing"]);if(!i)throw new Error("The --spacing(\u2026) function requires that the `--spacing` theme variable exists, but it was not found.");let l=H.get(t);if(l){if(l[0]===0)return"0";if(l[0]===1)return i}return`calc(${i} * ${t})`}function hr(e,r,t,...n){if(!t.startsWith("--"))throw new Error("The --theme(\u2026) function can only be used with CSS variables from your theme.");let i=!1;t.endsWith(" inline")&&(i=!0,t=t.slice(0,-7)),r.kind==="at-rule"&&(i=!0);let l=e.resolveThemeValue(t,i);if(!l){if(n.length>0)return n.join(", ");throw new Error(`Could not resolve value for theme function: \`theme(${t})\`. Consider checking if the variable name is correct or provide a fallback value to silence this error.`)}if(n.length===0)return l;let o=n.join(", ");if(o==="initial")return l;if(l==="initial")return o;if(l.startsWith("var(")||l.startsWith("theme(")||l.startsWith("--theme(")){let s=y(l);return wr(s,o),A(s)}return l}function vr(e,r,t,...n){t=kr(t);let i=e.resolveThemeValue(t);if(!i&&n.length>0)return n.join(", ");if(!i)throw new Error(`Could not resolve value for theme function: \`theme(${t})\`. Consider checking if the path is correct or provide a fallback value to silence this error.`);return i}var Ei=new RegExp(Object.keys(dr).map(e=>`${e}\\(`).join("|"));function kr(e){if(e[0]!=="'"&&e[0]!=='"')return e;let r="",t=e[0];for(let n=1;n{if(t.kind==="function"&&!(t.value!=="var"&&t.value!=="theme"&&t.value!=="--theme"))if(t.nodes.length===1)t.nodes.push({kind:"word",value:`, ${r}`});else{let n=t.nodes[t.nodes.length-1];n.kind==="word"&&n.value==="initial"&&(n.value=r)}})}function M(e,r="top",t="right",n="bottom",i="left"){return at(`${e}-${r}`,`${e}-${t}`,`${e}-${n}`,`${e}-${i}`)}function at(e="top",r="right",t="bottom",n="left"){return{1:[[e,0],[r,0],[t,0],[n,0]],2:[[e,0],[r,1],[t,0],[n,1]],3:[[e,0],[r,1],[t,2],[n,1]],4:[[e,0],[r,1],[t,2],[n,3]]}}function $(e,r){return{1:[[e,0],[r,0]],2:[[e,0],[r,1]]}}var Bi={inset:at(),margin:M("margin"),padding:M("padding"),"scroll-margin":M("scroll-margin"),"scroll-padding":M("scroll-padding"),"border-width":M("border","top-width","right-width","bottom-width","left-width"),"border-style":M("border","top-style","right-style","bottom-style","left-style"),"border-color":M("border","top-color","right-color","bottom-color","left-color"),gap:$("row-gap","column-gap"),overflow:$("overflow-x","overflow-y"),"overscroll-behavior":$("overscroll-behavior-x","overscroll-behavior-y")},Yi={"inset-block":$("top","bottom"),"inset-inline":$("left","right"),"margin-block":$("margin-top","margin-bottom"),"margin-inline":$("margin-left","margin-right"),"padding-block":$("padding-top","padding-bottom"),"padding-inline":$("padding-left","padding-right"),"scroll-margin-block":$("scroll-margin-top","scroll-margin-bottom"),"scroll-margin-inline":$("scroll-margin-left","scroll-margin-right"),"scroll-padding-block":$("scroll-padding-top","scroll-padding-bottom"),"scroll-padding-inline":$("scroll-padding-left","scroll-padding-right")};var Cr=1536,So=Cr/16;function $e(e){let r=[0];for(let i=0;i0;){let a=(o|0)>>1,u=l+a;r[u]<=i?(l=u+1,o=o-a-1):o=a}l-=1;let s=i-r[l];return{line:l+1,column:s}}function n({line:i,column:l}){i-=1,i=Math.min(Math.max(i,0),r.length-1);let o=r[i],s=r[i+1]??o;return Math.min(Math.max(o+l,0),s)}return{find:t,findOffset:n}}var ee=92,pe=47,de=42,dt=34,mt=39,Pr=58,me=59,N=10,ge=13,te=32,re=9,gt=123,Ve=125,Ne=40,ht=41,Or=91,_r=93,vt=45,Ee=64,Dr=33,R=class e extends Error{loc;constructor(r,t){if(t){let n=t[0],i=$e(n.code).find(t[1]);r=`${n.file}:${i.line}:${i.column+1}: ${r}`}super(r),this.name="CssSyntaxError",this.loc=t,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function ie(e,r){let t=r?.from?{file:r.from,code:e}:null;e[0]==="\uFEFF"&&(e=" "+e.slice(1));let n=[],i=[],l=[],o=null,s=null,a="",u="",p=0,c;for(let f=0;f0&&e[b]===m[m.length-1]&&(m=m.slice(0,-1));let z=Te(a,k);if(!z)throw new R("Invalid custom property, expected a value",t?[t,C,f]:null);t&&(z.src=[t,C,f],z.dst=[t,C,f]),o?o.nodes.push(z):n.push(z),a=""}else if(d===me&&a.charCodeAt(0)===Ee)s=ne(a),t&&(s.src=[t,p,f],s.dst=[t,p,f]),o?o.nodes.push(s):n.push(s),a="",s=null;else if(d===me&&u[u.length-1]!==")"){let m=Te(a);if(!m){if(a.length===0)continue;throw new R(`Invalid declaration: \`${a.trim()}\``,t?[t,p,f]:null)}t&&(m.src=[t,p,f],m.dst=[t,p,f]),o?o.nodes.push(m):n.push(m),a=""}else if(d===gt&&u[u.length-1]!==")")u+="}",s=I(a.trim()),t&&(s.src=[t,p,f],s.dst=[t,p,f]),o&&o.nodes.push(s),l.push(o),o=s,a="",s=null;else if(d===Ve&&u[u.length-1]!==")"){if(u==="")throw new R("Missing opening {",t?[t,f,f]:null);if(u=u.slice(0,-1),a.length>0)if(a.charCodeAt(0)===Ee)s=ne(a),t&&(s.src=[t,p,f],s.dst=[t,p,f]),o?o.nodes.push(s):n.push(s),a="",s=null;else{let C=a.indexOf(":");if(o){let k=Te(a,C);if(!k)throw new R(`Invalid declaration: \`${a.trim()}\``,t?[t,p,f]:null);t&&(k.src=[t,p,f],k.dst=[t,p,f]),o.nodes.push(k)}}let m=l.pop()??null;m===null&&o&&n.push(o),o=m,a="",s=null}else if(d===Ne)u+=")",a+="(";else if(d===ht){if(u[u.length-1]!==")")throw new R("Missing opening (",t?[t,f,f]:null);u=u.slice(0,-1),a+=")"}else{if(a.length===0&&(d===te||d===N||d===re))continue;a===""&&(p=f),a+=String.fromCharCode(d)}}}if(a.charCodeAt(0)===Ee){let f=ne(a);t&&(f.src=[t,p,e.length],f.dst=[t,p,e.length]),n.push(f)}if(u.length>0&&o){if(o.kind==="rule")throw new R(`Missing closing } at ${o.selector}`,o.src?[o.src[0],o.src[1],o.src[1]]:null);if(o.kind==="at-rule")throw new R(`Missing closing } at ${o.name} ${o.params}`,o.src?[o.src[0],o.src[1],o.src[1]]:null)}return i.length>0?i.concat(n):n}function ne(e,r=[]){let t=e,n="";for(let i=5;i{if(S(e.value))return e.value}),x=j(e=>{if(S(e.value))return`${e.value}%`}),U=j(e=>{if(S(e.value))return`${e.value}px`}),bt=j(e=>{if(S(e.value))return`${e.value}ms`}),he=j(e=>{if(S(e.value))return`${e.value}deg`}),Kr=j(e=>{if(e.fraction===null)return;let[r,t]=w(e.fraction,"/");if(!(!S(r)||!S(t)))return e.fraction}),yt=j(e=>{if(S(Number(e.value)))return`repeat(${e.value}, minmax(0, 1fr))`}),Mr={accentColor:({theme:e})=>e("colors"),animation:{none:"none",spin:"spin 1s linear infinite",ping:"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",bounce:"bounce 1s infinite"},aria:{busy:'busy="true"',checked:'checked="true"',disabled:'disabled="true"',expanded:'expanded="true"',hidden:'hidden="true"',pressed:'pressed="true"',readonly:'readonly="true"',required:'required="true"',selected:'selected="true"'},aspectRatio:{auto:"auto",square:"1 / 1",video:"16 / 9",...Kr},backdropBlur:({theme:e})=>e("blur"),backdropBrightness:({theme:e})=>({...e("brightness"),...x}),backdropContrast:({theme:e})=>({...e("contrast"),...x}),backdropGrayscale:({theme:e})=>({...e("grayscale"),...x}),backdropHueRotate:({theme:e})=>({...e("hueRotate"),...he}),backdropInvert:({theme:e})=>({...e("invert"),...x}),backdropOpacity:({theme:e})=>({...e("opacity"),...x}),backdropSaturate:({theme:e})=>({...e("saturate"),...x}),backdropSepia:({theme:e})=>({...e("sepia"),...x}),backgroundColor:({theme:e})=>e("colors"),backgroundImage:{none:"none","gradient-to-t":"linear-gradient(to top, var(--tw-gradient-stops))","gradient-to-tr":"linear-gradient(to top right, var(--tw-gradient-stops))","gradient-to-r":"linear-gradient(to right, var(--tw-gradient-stops))","gradient-to-br":"linear-gradient(to bottom right, var(--tw-gradient-stops))","gradient-to-b":"linear-gradient(to bottom, var(--tw-gradient-stops))","gradient-to-bl":"linear-gradient(to bottom left, var(--tw-gradient-stops))","gradient-to-l":"linear-gradient(to left, var(--tw-gradient-stops))","gradient-to-tl":"linear-gradient(to top left, var(--tw-gradient-stops))"},backgroundOpacity:({theme:e})=>e("opacity"),backgroundPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},backgroundSize:{auto:"auto",cover:"cover",contain:"contain"},blur:{0:"0",none:"",sm:"4px",DEFAULT:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},borderColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),borderOpacity:({theme:e})=>e("opacity"),borderRadius:{none:"0px",sm:"0.125rem",DEFAULT:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},borderSpacing:({theme:e})=>e("spacing"),borderWidth:{DEFAULT:"1px",0:"0px",2:"2px",4:"4px",8:"8px",...U},boxShadow:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",DEFAULT:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)",inner:"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",none:"none"},boxShadowColor:({theme:e})=>e("colors"),brightness:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",200:"2",...x},caretColor:({theme:e})=>e("colors"),colors:()=>({...Oe}),columns:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12","3xs":"16rem","2xs":"18rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",...P},container:{},content:{none:"none"},contrast:{0:"0",50:".5",75:".75",100:"1",125:"1.25",150:"1.5",200:"2",...x},cursor:{auto:"auto",default:"default",pointer:"pointer",wait:"wait",text:"text",move:"move",help:"help","not-allowed":"not-allowed",none:"none","context-menu":"context-menu",progress:"progress",cell:"cell",crosshair:"crosshair","vertical-text":"vertical-text",alias:"alias",copy:"copy","no-drop":"no-drop",grab:"grab",grabbing:"grabbing","all-scroll":"all-scroll","col-resize":"col-resize","row-resize":"row-resize","n-resize":"n-resize","e-resize":"e-resize","s-resize":"s-resize","w-resize":"w-resize","ne-resize":"ne-resize","nw-resize":"nw-resize","se-resize":"se-resize","sw-resize":"sw-resize","ew-resize":"ew-resize","ns-resize":"ns-resize","nesw-resize":"nesw-resize","nwse-resize":"nwse-resize","zoom-in":"zoom-in","zoom-out":"zoom-out"},divideColor:({theme:e})=>e("borderColor"),divideOpacity:({theme:e})=>e("borderOpacity"),divideWidth:({theme:e})=>({...e("borderWidth"),...U}),dropShadow:{sm:"0 1px 1px rgb(0 0 0 / 0.05)",DEFAULT:["0 1px 2px rgb(0 0 0 / 0.1)","0 1px 1px rgb(0 0 0 / 0.06)"],md:["0 4px 3px rgb(0 0 0 / 0.07)","0 2px 2px rgb(0 0 0 / 0.06)"],lg:["0 10px 8px rgb(0 0 0 / 0.04)","0 4px 3px rgb(0 0 0 / 0.1)"],xl:["0 20px 13px rgb(0 0 0 / 0.03)","0 8px 5px rgb(0 0 0 / 0.08)"],"2xl":"0 25px 25px rgb(0 0 0 / 0.15)",none:"0 0 #0000"},fill:({theme:e})=>e("colors"),flex:{1:"1 1 0%",auto:"1 1 auto",initial:"0 1 auto",none:"none"},flexBasis:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",...e("spacing")}),flexGrow:{0:"0",DEFAULT:"1",...P},flexShrink:{0:"0",DEFAULT:"1",...P},fontFamily:{sans:["ui-sans-serif","system-ui","sans-serif",'"Apple Color Emoji"','"Segoe UI Emoji"','"Segoe UI Symbol"','"Noto Color Emoji"'],serif:["ui-serif","Georgia","Cambria",'"Times New Roman"',"Times","serif"],mono:["ui-monospace","SFMono-Regular","Menlo","Monaco","Consolas",'"Liberation Mono"','"Courier New"',"monospace"]},fontSize:{xs:["0.75rem",{lineHeight:"1rem"}],sm:["0.875rem",{lineHeight:"1.25rem"}],base:["1rem",{lineHeight:"1.5rem"}],lg:["1.125rem",{lineHeight:"1.75rem"}],xl:["1.25rem",{lineHeight:"1.75rem"}],"2xl":["1.5rem",{lineHeight:"2rem"}],"3xl":["1.875rem",{lineHeight:"2.25rem"}],"4xl":["2.25rem",{lineHeight:"2.5rem"}],"5xl":["3rem",{lineHeight:"1"}],"6xl":["3.75rem",{lineHeight:"1"}],"7xl":["4.5rem",{lineHeight:"1"}],"8xl":["6rem",{lineHeight:"1"}],"9xl":["8rem",{lineHeight:"1"}]},fontWeight:{thin:"100",extralight:"200",light:"300",normal:"400",medium:"500",semibold:"600",bold:"700",extrabold:"800",black:"900"},gap:({theme:e})=>e("spacing"),gradientColorStops:({theme:e})=>e("colors"),gradientColorStopPositions:{"0%":"0%","5%":"5%","10%":"10%","15%":"15%","20%":"20%","25%":"25%","30%":"30%","35%":"35%","40%":"40%","45%":"45%","50%":"50%","55%":"55%","60%":"60%","65%":"65%","70%":"70%","75%":"75%","80%":"80%","85%":"85%","90%":"90%","95%":"95%","100%":"100%",...x},grayscale:{0:"0",DEFAULT:"100%",...x},gridAutoColumns:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridAutoRows:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridColumn:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridColumnEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...P},gridColumnStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...P},gridRow:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridRowEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...P},gridRowStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...P},gridTemplateColumns:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...yt},gridTemplateRows:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...yt},height:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),hueRotate:{0:"0deg",15:"15deg",30:"30deg",60:"60deg",90:"90deg",180:"180deg",...he},inset:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),invert:{0:"0",DEFAULT:"100%",...x},keyframes:{spin:{to:{transform:"rotate(360deg)"}},ping:{"75%, 100%":{transform:"scale(2)",opacity:"0"}},pulse:{"50%":{opacity:".5"}},bounce:{"0%, 100%":{transform:"translateY(-25%)",animationTimingFunction:"cubic-bezier(0.8,0,1,1)"},"50%":{transform:"none",animationTimingFunction:"cubic-bezier(0,0,0.2,1)"}}},letterSpacing:{tighter:"-0.05em",tight:"-0.025em",normal:"0em",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeight:{none:"1",tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625",loose:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},listStyleType:{none:"none",disc:"disc",decimal:"decimal"},listStyleImage:{none:"none"},margin:({theme:e})=>({auto:"auto",...e("spacing")}),lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",...P},maxHeight:({theme:e})=>({none:"none",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),maxWidth:({theme:e})=>({none:"none",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",prose:"65ch",...e("spacing")}),minHeight:({theme:e})=>({full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),minWidth:({theme:e})=>({full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),objectPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},opacity:{0:"0",5:"0.05",10:"0.1",15:"0.15",20:"0.2",25:"0.25",30:"0.3",35:"0.35",40:"0.4",45:"0.45",50:"0.5",55:"0.55",60:"0.6",65:"0.65",70:"0.7",75:"0.75",80:"0.8",85:"0.85",90:"0.9",95:"0.95",100:"1",...x},order:{first:"-9999",last:"9999",none:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",...P},outlineColor:({theme:e})=>e("colors"),outlineOffset:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},outlineWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},padding:({theme:e})=>e("spacing"),placeholderColor:({theme:e})=>e("colors"),placeholderOpacity:({theme:e})=>e("opacity"),ringColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),ringOffsetColor:({theme:e})=>e("colors"),ringOffsetWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},ringOpacity:({theme:e})=>({DEFAULT:"0.5",...e("opacity")}),ringWidth:{DEFAULT:"3px",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},rotate:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",45:"45deg",90:"90deg",180:"180deg",...he},saturate:{0:"0",50:".5",100:"1",150:"1.5",200:"2",...x},scale:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",...x},screens:{sm:"40rem",md:"48rem",lg:"64rem",xl:"80rem","2xl":"96rem"},scrollMargin:({theme:e})=>e("spacing"),scrollPadding:({theme:e})=>e("spacing"),sepia:{0:"0",DEFAULT:"100%",...x},skew:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",...he},space:({theme:e})=>e("spacing"),spacing:{px:"1px",0:"0px",.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},stroke:({theme:e})=>({none:"none",...e("colors")}),strokeWidth:{0:"0",1:"1",2:"2",...P},supports:{},data:{},textColor:({theme:e})=>e("colors"),textDecorationColor:({theme:e})=>e("colors"),textDecorationThickness:{auto:"auto","from-font":"from-font",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},textIndent:({theme:e})=>e("spacing"),textOpacity:({theme:e})=>e("opacity"),textUnderlineOffset:{auto:"auto",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},transformOrigin:{center:"center",top:"top","top-right":"top right",right:"right","bottom-right":"bottom right",bottom:"bottom","bottom-left":"bottom left",left:"left","top-left":"top left"},transitionDelay:{0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...bt},transitionDuration:{DEFAULT:"150ms",0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...bt},transitionProperty:{none:"none",all:"all",DEFAULT:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter",colors:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke",opacity:"opacity",shadow:"box-shadow",transform:"transform"},transitionTimingFunction:{DEFAULT:"cubic-bezier(0.4, 0, 0.2, 1)",linear:"linear",in:"cubic-bezier(0.4, 0, 1, 1)",out:"cubic-bezier(0, 0, 0.2, 1)","in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},translate:({theme:e})=>({"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),size:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),width:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",screen:"100vw",svw:"100svw",lvw:"100lvw",dvw:"100dvw",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),willChange:{auto:"auto",scroll:"scroll-position",contents:"contents",transform:"transform"},zIndex:{auto:"auto",0:"0",10:"10",20:"20",30:"30",40:"40",50:"50",...P}};var jr=64;function K(e,r=[]){return{kind:"rule",selector:e,nodes:r}}function E(e,r="",t=[]){return{kind:"at-rule",name:e,params:r,nodes:t}}function I(e,r=[]){return e.charCodeAt(0)===jr?ne(e,r):K(e,r)}function O(e,r,t=!1){return{kind:"declaration",property:e,value:r,important:t}}function Pe(e){return{kind:"comment",value:e}}function F(e,r){let t=0,n={file:null,code:""};function i(o,s=0){let a="",u=" ".repeat(s);if(o.kind==="declaration"){if(a+=`${u}${o.property}: ${o.value}${o.important?" !important":""}; +`,r){t+=u.length;let p=t;t+=o.property.length,t+=2,t+=o.value?.length??0,o.important&&(t+=11);let c=t;t+=2,o.dst=[n,p,c]}}else if(o.kind==="rule"){if(a+=`${u}${o.selector} { +`,r){t+=u.length;let p=t;t+=o.selector.length,t+=1;let c=t;o.dst=[n,p,c],t+=2}for(let p of o.nodes)a+=i(p,s+1);a+=`${u}} +`,r&&(t+=u.length,t+=2)}else if(o.kind==="at-rule"){if(o.nodes.length===0){let p=`${u}${o.name} ${o.params}; +`;if(r){t+=u.length;let c=t;t+=o.name.length,t+=1,t+=o.params.length;let f=t;t+=2,o.dst=[n,c,f]}return p}if(a+=`${u}${o.name}${o.params?` ${o.params} `:" "}{ +`,r){t+=u.length;let p=t;t+=o.name.length,o.params&&(t+=1,t+=o.params.length),t+=1;let c=t;o.dst=[n,p,c],t+=2}for(let p of o.nodes)a+=i(p,s+1);a+=`${u}} +`,r&&(t+=u.length,t+=2)}else if(o.kind==="comment"){if(a+=`${u}/*${o.value}*/ +`,r){t+=u.length;let p=t;t+=2+o.value.length+2;let c=t;o.dst=[n,p,c],t+=1}}else if(o.kind==="context"||o.kind==="at-root")return"";return a}let l="";for(let o of e)l+=i(o,0);return n.code=l,l}function Wr(e,r){if(typeof e!="string")throw new TypeError("expected path to be a string");if(e==="\\"||e==="/")return"/";var t=e.length;if(t<=1)return e;var n="";if(t>4&&e[3]==="\\"){var i=e[2];(i==="?"||i===".")&&e.slice(0,2)==="\\\\"&&(e=e.slice(2),n="//")}var l=e.split(/[/\\]+/);return r!==!1&&l[l.length-1]===""&&l.pop(),n+l.join("/")}function ve(e){let r=Wr(e);return e.startsWith("\\\\")&&r.startsWith("/")&&!r.startsWith("//")?`/${r}`:r}var De=/(?[\w-]+\([^)]*\)|"[^"]*"|'[^']*'|[^,]\S*[^,])\s*(?:\s(?\w[^,]+))?(?:,|$)/g,Zr=/(?Yr.test(e),Xr=e=>Gr.test(e);async function At({css:e,base:r,root:t}){if(!e.includes("url(")&&!e.includes("image-set("))return e;let n=ie(e),i=[];function l(o){if(o[0]==="/")return o;let s=_e.posix.join(ve(r),o),a=_e.posix.relative(ve(t),s);return a.startsWith(".")||(a="./"+a),a}return g(n,o=>{if(o.kind!=="declaration"||!o.value)return;let s=De.test(o.value),a=xt.test(o.value);if(s||a){let u=a?en:Ct;i.push(u(o.value,l).then(p=>{o.value=p}))}}),i.length&&await Promise.all(i),F(n)}function Ct(e,r){return $t(e,De,async t=>{let[n,i]=t;return await St(i.trim(),n,r)})}async function en(e,r){return await $t(e,xt,async t=>{let[,n]=t;return await rn(n,async({url:l})=>De.test(l)?await Ct(l,r):Br.test(l)?l:await St(l,l,r))})}async function St(e,r,t,n="url"){let i="",l=e[0];if((l==='"'||l==="'")&&(i=l,e=e.slice(1,-1)),tn(e))return r;let o=await t(e);return i===""&&o!==encodeURI(o)&&(i='"'),i==="'"&&o.includes("'")&&(i='"'),i==='"'&&o.includes('"')&&(o=o.replace(Zr,'\\"')),`${n}(${i}${o}${i})`}function tn(e,r){return Xr(e)||Jr(e)||!e[0].match(/[.a-zA-Z0-9_]/)||Hr.test(e)}function rn(e,r){return Promise.all(nn(e).map(async({url:t,descriptor:n})=>({url:await r({url:t,descriptor:n}),descriptor:n}))).then(on)}function nn(e){let r=e.trim().replace(Qr," ").replace(/\r?\n/,"").replace(/,\s+/,", ").replaceAll(/\s+/g," ").matchAll(qr);return Array.from(r,({groups:t})=>({url:t?.url?.trim()??"",descriptor:t?.descriptor?.trim()??""})).filter(({url:t})=>!!t)}function on(e){return e.map(({url:r,descriptor:t})=>r+(t?` ${t}`:"")).join(", ")}async function $t(e,r,t){let n,i=e,l="";for(;n=r.exec(i);)l+=i.slice(0,n.index),l+=await t(n),i=i.slice(n.index+n[0].length);return l+=i,l}var dn={};function Rt({base:e,from:r,polyfills:t,onDependency:n,shouldRewriteUrls:i,customCssResolver:l,customJsResolver:o}){return{base:e,polyfills:t,from:r,async loadModule(s,a){return ze(s,a,n,o)},async loadStylesheet(s,a){let u=await Ot(s,a,n,l);return i&&(u.content=await At({css:u.content,root:e,base:u.base})),u}}}async function Pt(e){if(e.root&&e.root!=="none"){let r=/[*{]/,t=[];for(let i of e.root.pattern.split("/")){if(r.test(i))break;t.push(i)}if(!await Le.default.stat(q.default.resolve(e.root.base,t.join("/"))).then(i=>i.isDirectory()).catch(()=>!1))throw new Error(`The \`source(${e.root.pattern})\` does not exist or is not a directory.`)}}async function ln(e,r){let t=await(0,_.compileAst)(e,Rt(r));return await Pt(t),t}async function an(e,r){let t=await(0,_.compile)(e,Rt(r));return await Pt(t),t}async function sn(e,{base:r}){return(0,_.__unstable__loadDesignSystem)(e,{base:r,async loadModule(t,n){return ze(t,n,()=>{})},async loadStylesheet(t,n){return Ot(t,n,()=>{})}})}async function ze(e,r,t,n){if(e[0]!=="."){let s=await Tt(e,r,n);if(!s)throw new Error(`Could not resolve '${e}' from '${r}'`);let a=await Et((0,Ie.pathToFileURL)(s).href);return{path:s,base:q.default.dirname(s),module:a.default??a}}let i=await Tt(e,r,n);if(!i)throw new Error(`Could not resolve '${e}' from '${r}'`);let[l,o]=await Promise.all([Et((0,Ie.pathToFileURL)(i).href+"?id="+Date.now()),Ge(i)]);for(let s of o)t(s);return{path:i,base:q.default.dirname(i),module:l.default??l}}async function Ot(e,r,t,n){let i=await cn(e,r,n);if(!i)throw new Error(`Could not resolve '${e}' from '${r}'`);t(i);let l=await Le.default.readFile(i,"utf-8");return{path:i,base:q.default.dirname(i),content:l}}var Vt=null;async function Et(e){if(typeof globalThis.__tw_load=="function"){let r=await globalThis.__tw_load(e);if(r)return r}try{return await import(e)}catch{return Vt??=(0,Nt.createJiti)(dn.url,{moduleCache:!1,fsCache:!1}),await Vt.import(e)}}var Ke=["node_modules",...process.env.NODE_PATH?[...process.env.NODE_PATH.split(q.default.delimiter)]:[]],un=W.default.ResolverFactory.createResolver({fileSystem:new W.default.CachedInputFileSystem(ke.default,4e3),useSyncFileSystemCalls:!0,extensions:[".css"],mainFields:["style"],conditionNames:["style"],modules:Ke});async function cn(e,r,t){if(typeof globalThis.__tw_resolve=="function"){let n=globalThis.__tw_resolve(e,r);if(n)return Promise.resolve(n)}if(t){let n=await t(e,r);if(n)return n}return Ue(un,e,r)}var fn=W.default.ResolverFactory.createResolver({fileSystem:new W.default.CachedInputFileSystem(ke.default,4e3),useSyncFileSystemCalls:!0,extensions:[".js",".json",".node",".ts"],conditionNames:["node","import"],modules:Ke}),pn=W.default.ResolverFactory.createResolver({fileSystem:new W.default.CachedInputFileSystem(ke.default,4e3),useSyncFileSystemCalls:!0,extensions:[".js",".json",".node",".ts"],conditionNames:["node","require"],modules:Ke});async function Tt(e,r,t){if(typeof globalThis.__tw_resolve=="function"){let n=globalThis.__tw_resolve(e,r);if(n)return Promise.resolve(n)}if(t){let n=await t(e,r);if(n)return n}return Ue(fn,e,r).catch(()=>Ue(pn,e,r))}function Ue(e,r,t){return new Promise((n,i)=>e.resolve({},t,r,{},(l,o)=>{if(l)return i(l);n(o)}))}Symbol.dispose??=Symbol("Symbol.dispose");Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");var Me=class{constructor(r=be,t=n=>{process.stderr.write(`${n} +`)}){this.shouldReport=r;this.defaultFlush=t}shouldReport;defaultFlush;#r=new h(()=>({value:0}));#t=new h(()=>({value:0n}));#e=[];hit(r){this.#r.get(r).value++}start(r){let t=this.#e.map(i=>i.label).join("//"),n=`${t}${t.length===0?"":"//"}${r}`;this.#r.get(n).value++,this.#t.get(n),this.#e.push({id:n,label:r,namespace:t,value:process.hrtime.bigint()})}end(r){let t=process.hrtime.bigint();if(this.#e[this.#e.length-1].label!==r)throw new Error(`Mismatched timer label: \`${r}\`, expected \`${this.#e[this.#e.length-1].label}\``);let n=this.#e.pop(),i=t-n.value;this.#t.get(n.id).value+=i}track(r){this.start(r);let t=!1;return{[Symbol.dispose]:()=>{t||(this.end(r),t=!0)},[Symbol.asyncDispose]:()=>{t||(this.end(r),t=!0)}}}span(r,t){this.start(r);let n=!1;try{let i=t();return n=i&&typeof i.then=="function",n?i.finally(()=>this.end(r)):i}finally{n||this.end(r)}}reset(){this.#r.clear(),this.#t.clear(),this.#e.splice(0)}report(r=this.defaultFlush){let t=[],n=!1;for(let o=this.#e.length-1;o>=0;o--)this.end(this.#e[o].label);for(let[o,{value:s}]of this.#r.entries()){if(this.#t.has(o))continue;t.length===0&&(n=!0,t.push("Hits:"));let a=o.split("//").length;t.push(`${" ".repeat(a)}${o} ${we(_t(`\xD7 ${s}`))}`)}this.#t.size>0&&n&&t.push(` +Timers:`);let i=-1/0,l=new Map;for(let[o,{value:s}]of this.#t){let a=`${(Number(s)/1e6).toFixed(2)}ms`;l.set(o,a),i=Math.max(i,a.length)}for(let o of this.#t.keys()){let s=o.split("//").length;t.push(`${we(`[${l.get(o).padStart(i," ")}]`)}${" ".repeat(s-1)}${s===1?" ":we(" \u21B3 ")}${o.split("//").pop()} ${this.#r.get(o).value===1?"":we(_t(`\xD7 ${this.#r.get(o).value}`))}`.trimEnd())}r(` +${t.join(` +`)} +`),this.reset()}[Symbol.dispose](){this.shouldReport&&this.report()}};function we(e){return`\x1B[2m${e}\x1B[22m`}function _t(e){return`\x1B[34m${e}\x1B[39m`}var Dt=T(require("@jridgewell/remapping")),L=require("lightningcss"),It=T(require("magic-string"));function mn(e,{file:r="input.css",minify:t=!1,map:n}={}){function i(a,u){return(0,L.transform)({filename:r,code:a,minify:t,sourceMap:typeof u<"u",inputSourceMap:u,drafts:{customMedia:!0},nonStandard:{deepSelectorCombinator:!0},include:L.Features.Nesting|L.Features.MediaQueries,exclude:L.Features.LogicalProperties|L.Features.DirSelector|L.Features.LightDark,targets:{safari:16<<16|1024,ios_saf:16<<16|1024,firefox:8388608,chrome:7274496},errorRecovery:!0})}let l=i(Buffer.from(e),n);if(n=l.map?.toString(),l.warnings=l.warnings.filter(a=>!/'(deep|slotted|global)' is not recognized as a valid pseudo-/.test(a.message)),l.warnings.length>0){let a=e.split(` +`),u=[`Found ${l.warnings.length} ${l.warnings.length===1?"warning":"warnings"} while optimizing generated CSS:`];for(let[p,c]of l.warnings.entries()){u.push(""),l.warnings.length>1&&u.push(`Issue #${p+1}:`);let f=2,d=Math.max(0,c.loc.line-f-1),m=Math.min(a.length,c.loc.line+f),C=a.slice(d,m).map((k,z)=>d+z+1===c.loc.line?`${oe("\u2502")} ${k}`:oe(`\u2502 ${k}`));C.splice(c.loc.line-d,0,`${oe("\u2506")}${" ".repeat(c.loc.column-1)} ${gn(`${oe("^--")} ${c.message}`)}`,`${oe("\u2506")}`),u.push(...C)}u.push(""),console.warn(u.join(` +`))}l=i(l.code,n),n=l.map?.toString();let o=l.code.toString(),s=new It.default(o);if(s.replaceAll("@media not (","@media not all and ("),n!==void 0&&s.hasChanged()){let a=s.generateMap({source:"original",hires:"boundary"}).toString();n=(0,Dt.default)([a,n],()=>null).toString()}return o=s.toString(),{code:o,map:n}}function oe(e){return`\x1B[2m${e}\x1B[22m`}function gn(e){return`\x1B[33m${e}\x1B[39m`}var Ut=require("source-map-js");function hn(e){let r=new Ut.SourceMapGenerator,t=1,n=new h(i=>({url:i?.url??``,content:i?.content??""}));for(let i of e.mappings){let l=n.get(i.originalPosition?.source??null);r.addMapping({generated:i.generatedPosition,original:i.originalPosition,source:l.url,name:i.name}),r.setSourceContent(l.url,l.content)}return r.toString()}function vn(e){let r=typeof e=="string"?e:hn(e);function t(n){return`/*# sourceMappingURL=${n} */ +`}return{raw:r,get inline(){let n=Buffer.from(r,"utf-8").toString("base64");return t(`data:application/json;base64,${n}`)},comment:t}}process.versions.bun||(le.registerHooks?le.registerHooks({resolve:Be}):le.register?.((0,Lt.pathToFileURL)(require.resolve("@tailwindcss/node/esm-cache-loader"))));0&&(module.exports={Features,Instrumentation,Polyfills,__unstable__loadDesignSystem,compile,compileAst,env,loadModule,normalizePath,optimize,toSourceMap}); diff --git a/client/node_modules/@tailwindcss/node/dist/index.mjs b/client/node_modules/@tailwindcss/node/dist/index.mjs new file mode 100644 index 0000000..73cb885 --- /dev/null +++ b/client/node_modules/@tailwindcss/node/dist/index.mjs @@ -0,0 +1,18 @@ +var Et=Object.defineProperty;var Tt=(e,r)=>{for(var t in r)Et(e,t,{get:r[t],enumerable:!0})};import*as M from"module";import{pathToFileURL as on}from"url";var me={};Tt(me,{DEBUG:()=>de});var de=Nt(process.env.DEBUG);function Nt(e){if(typeof e=="boolean")return e;if(e===void 0)return!1;if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1;if(e==="*")return!0;let r=e.split(",").map(t=>t.split(":")[0]);return r.includes("-tailwindcss")?!1:!!r.includes("tailwindcss")}import{isBuiltin as Rt}from"module";var De=(e,r,t)=>{let n=t(e,r);return Pt(r,n)};function Pt(e,r){if(r.url===import.meta.url||Rt(r.url)||!e.parentURL)return r;let n=new URL(e.parentURL).searchParams.get("id");if(n===null)return r;let i=new URL(r.url);return i.searchParams.set("id",n),{...r,url:`${i}`}}import B from"enhanced-resolve";import{createJiti as Wr}from"jiti";import Oe from"fs";import yt from"fs/promises";import re from"path";import{pathToFileURL as vt}from"url";import{__unstable__loadDesignSystem as Br,compile as Yr,compileAst as Gr,Features as tu,Polyfills as ru}from"tailwindcss";import ge from"fs/promises";import Y from"path";var Ot=[/import[\s\S]*?['"](.{3,}?)['"]/gi,/import[\s\S]*from[\s\S]*?['"](.{3,}?)['"]/gi,/export[\s\S]*from[\s\S]*?['"](.{3,}?)['"]/gi,/require\(['"`](.+)['"`]\)/gi],_t=[".js",".cjs",".mjs"],Dt=["",".js",".cjs",".mjs",".ts",".cts",".mts",".jsx",".tsx"],It=["",".ts",".cts",".mts",".tsx",".js",".cjs",".mjs",".jsx"];async function Ut(e,r){for(let t of r){let n=`${e}${t}`;if((await ge.stat(n).catch(()=>null))?.isFile())return n}for(let t of r){let n=`${e}/index${t}`;if(await ge.access(n).then(()=>!0,()=>!1))return n}return null}async function Ie(e,r,t,n){let i=_t.includes(n)?Dt:It,l=await Ut(Y.resolve(t,r),i);if(l===null||e.has(l))return;e.add(l),t=Y.dirname(l),n=Y.extname(l);let o=await ge.readFile(l,"utf-8"),s=[];for(let a of Ot)for(let u of o.matchAll(a))u[1].startsWith(".")&&s.push(Ie(e,u[1],t,n));await Promise.all(s)}async function Ue(e){let r=new Set;return await Ie(r,e,Y.dirname(e),Y.extname(e)),Array.from(r)}import*as Ne from"path";function j(e){return{kind:"word",value:e}}function Lt(e,r){return{kind:"function",value:e,nodes:r}}function zt(e){return{kind:"separator",value:e}}function A(e){let r="";for(let t of e)switch(t.kind){case"word":case"separator":{r+=t.value;break}case"function":r+=t.value+"("+A(t.nodes)+")"}return r}var Le=92,Kt=41,ze=58,Ke=44,Mt=34,Me=61,Fe=62,je=60,We=10,Ft=40,jt=39,Wt=47,Be=32,Ye=9;function y(e){e=e.replaceAll(`\r +`,` +`);let r=[],t=[],n=null,i="",l;for(let o=0;o0){let u=j(i);n?n.nodes.push(u):r.push(u),i=""}let a=j(e[o]);n?n.nodes.push(a):r.push(a);break}case ze:case Ke:case Me:case Fe:case je:case We:case Be:case Ye:{if(i.length>0){let c=j(i);n?n.nodes.push(c):r.push(c),i=""}let a=o,u=o+1;for(;u0){let u=j(i);a?.nodes.push(u),i=""}t.length>0?n=t[t.length-1]:n=null;break}default:i+=String.fromCharCode(s)}}return i.length>0&&r.push(j(i)),r}var h=class extends Map{constructor(t){super();this.factory=t}factory;get(t){let n=super.get(t);return n===void 0&&(n=this.factory(t,this),this.set(t,n)),n}};var hn=new Uint8Array(256);var oe=new Uint8Array(256);function w(e,r){let t=0,n=[],i=0,l=e.length,o=r.charCodeAt(0);for(let s=0;s0&&a===oe[t-1]&&t--;break}}return n.push(e.slice(i)),n}var he=(o=>(o[o.Continue=0]="Continue",o[o.Skip=1]="Skip",o[o.Stop=2]="Stop",o[o.Replace=3]="Replace",o[o.ReplaceSkip=4]="ReplaceSkip",o[o.ReplaceStop=5]="ReplaceStop",o))(he||{}),v={Continue:{kind:0},Skip:{kind:1},Stop:{kind:2},Replace:e=>({kind:3,nodes:Array.isArray(e)?e:[e]}),ReplaceSkip:e=>({kind:4,nodes:Array.isArray(e)?e:[e]}),ReplaceStop:e=>({kind:5,nodes:Array.isArray(e)?e:[e]})};function g(e,r){typeof r=="function"?Ge(e,r):Ge(e,r.enter,r.exit)}function Ge(e,r=()=>v.Continue,t=()=>v.Continue){let n={value:[e,0,null],prev:null},i={parent:null,depth:0,index:0,siblings:e,path(){let l=[],o=n;for(;o;){let s=o.value[2];s&&l.push(s),o=o.prev}return l.reverse(),l}};for(;n!==null;){let l=n.value,o=l[0],s=l[1],a=l[2];if(s>=o.length){n=n.prev,i.depth-=1;continue}if(i.parent=a,i.siblings=o,s>=0){i.index=s;let f=o[s],d=r(f,i)??v.Continue;switch(d.kind){case 0:{f.nodes&&f.nodes.length>0&&(i.depth+=1,n={value:[f.nodes,0,f],prev:n}),l[1]=~s;continue}case 2:return;case 1:{l[1]=~s;continue}case 3:{o.splice(s,1,...d.nodes);continue}case 5:{o.splice(s,1,...d.nodes);return}case 4:{o.splice(s,1,...d.nodes),l[1]+=d.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${he[d.kind]??`Unknown(${d.kind})`}\` in enter.`)}}let u=~s;i.index=u;let p=o[u],c=t(p,i)??v.Continue;switch(c.kind){case 0:l[1]=u+1;continue;case 2:return;case 3:{o.splice(u,1,...c.nodes),l[1]=u+c.nodes.length;continue}case 5:{o.splice(u,1,...c.nodes);return}case 4:{o.splice(u,1,...c.nodes),l[1]=u+c.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${he[c.kind]??`Unknown(${c.kind})`}\` in exit.`)}}}var Vn=new h(e=>{let r=y(e),t=new Set,n=new Set(["~",">","+","-","*","/"]);return g(r,(i,l)=>{if(i.kind==="word"&&n.has(i.value)){let o=l.index;if(o===-1)return;let s=l.siblings[o-1];if(s?.kind!=="separator"||s.value!==" ")return;let a=l.siblings[o+1];if(a?.kind!=="separator"||a.value!==" ")return;let u=l.siblings[o-2];if(u&&n.has(u.value))return;let p=l.siblings[o+2];if(p&&n.has(p.value))return;t.add(s),t.add(a)}else if(i.kind==="separator"&&i.value.length>0&&i.value.trim()==="")(l.siblings[0]===i||l.siblings[l.siblings.length-1]===i)&&t.add(i);else if(i.kind==="separator"&&i.value.trim()===",")i.value=",";else if(i.kind==="function"&&i.value.startsWith("--")){let o=l.index;if(o<=0)return;let s=l.siblings[o-1];if(s?.kind==="separator"&&s.value===",")return;let a=l.siblings[o-2];return a&&!n.has(a.value)?void 0:v.ReplaceSkip({kind:"function",value:"",nodes:[i]})}}),t.size>0&&g(r,i=>{if(t.has(i))return t.delete(i),v.ReplaceSkip([])}),ve(r),A(r)});var En=new h(e=>{let r=y(e);return r.length===3&&r[0].kind==="word"&&r[0].value==="&"&&r[1].kind==="separator"&&r[1].value===":"&&r[2].kind==="function"&&r[2].value==="is"?A(r[2].nodes):e});function ve(e){for(let r of e)switch(r.kind){case"function":{if(r.value==="url"||r.value.endsWith("_url")){r.value=G(r.value);break}if(r.value==="var"||r.value.endsWith("_var")||r.value==="theme"||r.value.endsWith("_theme")){r.value=G(r.value);for(let t=0;t{let r=y(e);return r.length===1&&r[0].kind==="function"&&r[0].value==="var"});function Yt(e){throw new Error(`Unexpected value: ${e}`)}function G(e){return e.replaceAll("_",String.raw`\_`).replaceAll(" ","_")}var Gt=/^(?[-+]?(?:\d*\.)?\d+)(?[a-z]+|%)?$/i,W=new h(e=>{let r=Gt.exec(e);if(!r)return null;let t=r.groups?.value;if(t===void 0)return null;let n=Number(t);if(Number.isNaN(n))return null;let i=r.groups?.unit;return i===void 0?[n,null]:[n,i]});var O=/[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?/,Mn=new RegExp(`^${O.source}$`);var Fn=new RegExp(`^${O.source}%$`);var jn=new RegExp(`^${O.source}\\s*/\\s*${O.source}$`);var Ht=["cm","mm","Q","in","pc","pt","px","em","ex","ch","rem","lh","rlh","vw","vh","vmin","vmax","vb","vi","svw","svh","lvw","lvh","dvw","dvh","cqw","cqh","cqi","cqb","cqmin","cqmax"],Wn=new RegExp(`^${O.source}(${Ht.join("|")})$`);var qt=["deg","rad","grad","turn"],Bn=new RegExp(`^${O.source}(${qt.join("|")})$`);var Yn=new RegExp(`^${O.source} +${O.source} +${O.source}$`);function S(e){let r=Number(e);return Number.isInteger(r)&&r>=0&&String(r)===String(e)}function H(e,r){if(r===null)return e;let t=Number(r);return Number.isNaN(t)||(r=`${t*100}%`),r==="100%"?e:`color-mix(in oklab, ${e} ${r}, transparent)`}var Jt={"--alpha":Xt,"--spacing":er,"--theme":tr,theme:rr};function Xt(e,r,t,...n){let[i,l]=w(t,"/").map(o=>o.trim());if(!i||!l)throw new Error(`The --alpha(\u2026) function requires a color and an alpha value, e.g.: \`--alpha(${i||"var(--my-color)"} / ${l||"50%"})\``);if(n.length>0)throw new Error(`The --alpha(\u2026) function only accepts one argument, e.g.: \`--alpha(${i||"var(--my-color)"} / ${l||"50%"})\``);return H(i,l)}function er(e,r,t,...n){if(!t)throw new Error("The --spacing(\u2026) function requires an argument, but received none.");if(n.length>0)throw new Error(`The --spacing(\u2026) function only accepts a single argument, but received ${n.length+1}.`);let i=e.theme.resolve(null,["--spacing"]);if(!i)throw new Error("The --spacing(\u2026) function requires that the `--spacing` theme variable exists, but it was not found.");let l=W.get(t);if(l){if(l[0]===0)return"0";if(l[0]===1)return i}return`calc(${i} * ${t})`}function tr(e,r,t,...n){if(!t.startsWith("--"))throw new Error("The --theme(\u2026) function can only be used with CSS variables from your theme.");let i=!1;t.endsWith(" inline")&&(i=!0,t=t.slice(0,-7)),r.kind==="at-rule"&&(i=!0);let l=e.resolveThemeValue(t,i);if(!l){if(n.length>0)return n.join(", ");throw new Error(`Could not resolve value for theme function: \`theme(${t})\`. Consider checking if the variable name is correct or provide a fallback value to silence this error.`)}if(n.length===0)return l;let o=n.join(", ");if(o==="initial")return l;if(l==="initial")return o;if(l.startsWith("var(")||l.startsWith("theme(")||l.startsWith("--theme(")){let s=y(l);return ir(s,o),A(s)}return l}function rr(e,r,t,...n){t=nr(t);let i=e.resolveThemeValue(t);if(!i&&n.length>0)return n.join(", ");if(!i)throw new Error(`Could not resolve value for theme function: \`theme(${t})\`. Consider checking if the path is correct or provide a fallback value to silence this error.`);return i}var ki=new RegExp(Object.keys(Jt).map(e=>`${e}\\(`).join("|"));function nr(e){if(e[0]!=="'"&&e[0]!=='"')return e;let r="",t=e[0];for(let n=1;n{if(t.kind==="function"&&!(t.value!=="var"&&t.value!=="theme"&&t.value!=="--theme"))if(t.nodes.length===1)t.nodes.push({kind:"word",value:`, ${r}`});else{let n=t.nodes[t.nodes.length-1];n.kind==="word"&&n.value==="initial"&&(n.value=r)}})}function L(e,r="top",t="right",n="bottom",i="left"){return Qe(`${e}-${r}`,`${e}-${t}`,`${e}-${n}`,`${e}-${i}`)}function Qe(e="top",r="right",t="bottom",n="left"){return{1:[[e,0],[r,0],[t,0],[n,0]],2:[[e,0],[r,1],[t,0],[n,1]],3:[[e,0],[r,1],[t,2],[n,1]],4:[[e,0],[r,1],[t,2],[n,3]]}}function $(e,r){return{1:[[e,0],[r,0]],2:[[e,0],[r,1]]}}var Di={inset:Qe(),margin:L("margin"),padding:L("padding"),"scroll-margin":L("scroll-margin"),"scroll-padding":L("scroll-padding"),"border-width":L("border","top-width","right-width","bottom-width","left-width"),"border-style":L("border","top-style","right-style","bottom-style","left-style"),"border-color":L("border","top-color","right-color","bottom-color","left-color"),gap:$("row-gap","column-gap"),overflow:$("overflow-x","overflow-y"),"overscroll-behavior":$("overscroll-behavior-x","overscroll-behavior-y")},Ii={"inset-block":$("top","bottom"),"inset-inline":$("left","right"),"margin-block":$("margin-top","margin-bottom"),"margin-inline":$("margin-left","margin-right"),"padding-block":$("padding-top","padding-bottom"),"padding-inline":$("padding-left","padding-right"),"scroll-margin-block":$("scroll-margin-top","scroll-margin-bottom"),"scroll-margin-inline":$("scroll-margin-left","scroll-margin-right"),"scroll-padding-block":$("scroll-padding-top","scroll-padding-bottom"),"scroll-padding-inline":$("scroll-padding-left","scroll-padding-right")};var ur=1536,go=ur/16;function ye(e){let r=[0];for(let i=0;i0;){let a=(o|0)>>1,u=l+a;r[u]<=i?(l=u+1,o=o-a-1):o=a}l-=1;let s=i-r[l];return{line:l+1,column:s}}function n({line:i,column:l}){i-=1,i=Math.min(Math.max(i,0),r.length-1);let o=r[i],s=r[i+1]??o;return Math.min(Math.max(o+l,0),s)}return{find:t,findOffset:n}}var Q=92,ae=47,se=42,nt=34,it=39,vr=58,ue=59,T=10,ce=13,J=32,X=9,ot=123,xe=125,Se=40,lt=41,kr=91,wr=93,at=45,Ae=64,br=33,N=class e extends Error{loc;constructor(r,t){if(t){let n=t[0],i=ye(n.code).find(t[1]);r=`${n.file}:${i.line}:${i.column+1}: ${r}`}super(r),this.name="CssSyntaxError",this.loc=t,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function te(e,r){let t=r?.from?{file:r.from,code:e}:null;e[0]==="\uFEFF"&&(e=" "+e.slice(1));let n=[],i=[],l=[],o=null,s=null,a="",u="",p=0,c;for(let f=0;f0&&e[b]===m[m.length-1]&&(m=m.slice(0,-1));let I=Ce(a,k);if(!I)throw new N("Invalid custom property, expected a value",t?[t,C,f]:null);t&&(I.src=[t,C,f],I.dst=[t,C,f]),o?o.nodes.push(I):n.push(I),a=""}else if(d===ue&&a.charCodeAt(0)===Ae)s=ee(a),t&&(s.src=[t,p,f],s.dst=[t,p,f]),o?o.nodes.push(s):n.push(s),a="",s=null;else if(d===ue&&u[u.length-1]!==")"){let m=Ce(a);if(!m){if(a.length===0)continue;throw new N(`Invalid declaration: \`${a.trim()}\``,t?[t,p,f]:null)}t&&(m.src=[t,p,f],m.dst=[t,p,f]),o?o.nodes.push(m):n.push(m),a=""}else if(d===ot&&u[u.length-1]!==")")u+="}",s=_(a.trim()),t&&(s.src=[t,p,f],s.dst=[t,p,f]),o&&o.nodes.push(s),l.push(o),o=s,a="",s=null;else if(d===xe&&u[u.length-1]!==")"){if(u==="")throw new N("Missing opening {",t?[t,f,f]:null);if(u=u.slice(0,-1),a.length>0)if(a.charCodeAt(0)===Ae)s=ee(a),t&&(s.src=[t,p,f],s.dst=[t,p,f]),o?o.nodes.push(s):n.push(s),a="",s=null;else{let C=a.indexOf(":");if(o){let k=Ce(a,C);if(!k)throw new N(`Invalid declaration: \`${a.trim()}\``,t?[t,p,f]:null);t&&(k.src=[t,p,f],k.dst=[t,p,f]),o.nodes.push(k)}}let m=l.pop()??null;m===null&&o&&n.push(o),o=m,a="",s=null}else if(d===Se)u+=")",a+="(";else if(d===lt){if(u[u.length-1]!==")")throw new N("Missing opening (",t?[t,f,f]:null);u=u.slice(0,-1),a+=")"}else{if(a.length===0&&(d===J||d===T||d===X))continue;a===""&&(p=f),a+=String.fromCharCode(d)}}}if(a.charCodeAt(0)===Ae){let f=ee(a);t&&(f.src=[t,p,e.length],f.dst=[t,p,e.length]),n.push(f)}if(u.length>0&&o){if(o.kind==="rule")throw new N(`Missing closing } at ${o.selector}`,o.src?[o.src[0],o.src[1],o.src[1]]:null);if(o.kind==="at-rule")throw new N(`Missing closing } at ${o.name} ${o.params}`,o.src?[o.src[0],o.src[1],o.src[1]]:null)}return i.length>0?i.concat(n):n}function ee(e,r=[]){let t=e,n="";for(let i=5;i{if(S(e.value))return e.value}),x=K(e=>{if(S(e.value))return`${e.value}%`}),D=K(e=>{if(S(e.value))return`${e.value}px`}),ct=K(e=>{if(S(e.value))return`${e.value}ms`}),fe=K(e=>{if(S(e.value))return`${e.value}deg`}),Sr=K(e=>{if(e.fraction===null)return;let[r,t]=w(e.fraction,"/");if(!(!S(r)||!S(t)))return e.fraction}),ft=K(e=>{if(S(Number(e.value)))return`repeat(${e.value}, minmax(0, 1fr))`}),$r={accentColor:({theme:e})=>e("colors"),animation:{none:"none",spin:"spin 1s linear infinite",ping:"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",bounce:"bounce 1s infinite"},aria:{busy:'busy="true"',checked:'checked="true"',disabled:'disabled="true"',expanded:'expanded="true"',hidden:'hidden="true"',pressed:'pressed="true"',readonly:'readonly="true"',required:'required="true"',selected:'selected="true"'},aspectRatio:{auto:"auto",square:"1 / 1",video:"16 / 9",...Sr},backdropBlur:({theme:e})=>e("blur"),backdropBrightness:({theme:e})=>({...e("brightness"),...x}),backdropContrast:({theme:e})=>({...e("contrast"),...x}),backdropGrayscale:({theme:e})=>({...e("grayscale"),...x}),backdropHueRotate:({theme:e})=>({...e("hueRotate"),...fe}),backdropInvert:({theme:e})=>({...e("invert"),...x}),backdropOpacity:({theme:e})=>({...e("opacity"),...x}),backdropSaturate:({theme:e})=>({...e("saturate"),...x}),backdropSepia:({theme:e})=>({...e("sepia"),...x}),backgroundColor:({theme:e})=>e("colors"),backgroundImage:{none:"none","gradient-to-t":"linear-gradient(to top, var(--tw-gradient-stops))","gradient-to-tr":"linear-gradient(to top right, var(--tw-gradient-stops))","gradient-to-r":"linear-gradient(to right, var(--tw-gradient-stops))","gradient-to-br":"linear-gradient(to bottom right, var(--tw-gradient-stops))","gradient-to-b":"linear-gradient(to bottom, var(--tw-gradient-stops))","gradient-to-bl":"linear-gradient(to bottom left, var(--tw-gradient-stops))","gradient-to-l":"linear-gradient(to left, var(--tw-gradient-stops))","gradient-to-tl":"linear-gradient(to top left, var(--tw-gradient-stops))"},backgroundOpacity:({theme:e})=>e("opacity"),backgroundPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},backgroundSize:{auto:"auto",cover:"cover",contain:"contain"},blur:{0:"0",none:"",sm:"4px",DEFAULT:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},borderColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),borderOpacity:({theme:e})=>e("opacity"),borderRadius:{none:"0px",sm:"0.125rem",DEFAULT:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},borderSpacing:({theme:e})=>e("spacing"),borderWidth:{DEFAULT:"1px",0:"0px",2:"2px",4:"4px",8:"8px",...D},boxShadow:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",DEFAULT:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)",inner:"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",none:"none"},boxShadowColor:({theme:e})=>e("colors"),brightness:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",200:"2",...x},caretColor:({theme:e})=>e("colors"),colors:()=>({...Ee}),columns:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12","3xs":"16rem","2xs":"18rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",...R},container:{},content:{none:"none"},contrast:{0:"0",50:".5",75:".75",100:"1",125:"1.25",150:"1.5",200:"2",...x},cursor:{auto:"auto",default:"default",pointer:"pointer",wait:"wait",text:"text",move:"move",help:"help","not-allowed":"not-allowed",none:"none","context-menu":"context-menu",progress:"progress",cell:"cell",crosshair:"crosshair","vertical-text":"vertical-text",alias:"alias",copy:"copy","no-drop":"no-drop",grab:"grab",grabbing:"grabbing","all-scroll":"all-scroll","col-resize":"col-resize","row-resize":"row-resize","n-resize":"n-resize","e-resize":"e-resize","s-resize":"s-resize","w-resize":"w-resize","ne-resize":"ne-resize","nw-resize":"nw-resize","se-resize":"se-resize","sw-resize":"sw-resize","ew-resize":"ew-resize","ns-resize":"ns-resize","nesw-resize":"nesw-resize","nwse-resize":"nwse-resize","zoom-in":"zoom-in","zoom-out":"zoom-out"},divideColor:({theme:e})=>e("borderColor"),divideOpacity:({theme:e})=>e("borderOpacity"),divideWidth:({theme:e})=>({...e("borderWidth"),...D}),dropShadow:{sm:"0 1px 1px rgb(0 0 0 / 0.05)",DEFAULT:["0 1px 2px rgb(0 0 0 / 0.1)","0 1px 1px rgb(0 0 0 / 0.06)"],md:["0 4px 3px rgb(0 0 0 / 0.07)","0 2px 2px rgb(0 0 0 / 0.06)"],lg:["0 10px 8px rgb(0 0 0 / 0.04)","0 4px 3px rgb(0 0 0 / 0.1)"],xl:["0 20px 13px rgb(0 0 0 / 0.03)","0 8px 5px rgb(0 0 0 / 0.08)"],"2xl":"0 25px 25px rgb(0 0 0 / 0.15)",none:"0 0 #0000"},fill:({theme:e})=>e("colors"),flex:{1:"1 1 0%",auto:"1 1 auto",initial:"0 1 auto",none:"none"},flexBasis:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",...e("spacing")}),flexGrow:{0:"0",DEFAULT:"1",...R},flexShrink:{0:"0",DEFAULT:"1",...R},fontFamily:{sans:["ui-sans-serif","system-ui","sans-serif",'"Apple Color Emoji"','"Segoe UI Emoji"','"Segoe UI Symbol"','"Noto Color Emoji"'],serif:["ui-serif","Georgia","Cambria",'"Times New Roman"',"Times","serif"],mono:["ui-monospace","SFMono-Regular","Menlo","Monaco","Consolas",'"Liberation Mono"','"Courier New"',"monospace"]},fontSize:{xs:["0.75rem",{lineHeight:"1rem"}],sm:["0.875rem",{lineHeight:"1.25rem"}],base:["1rem",{lineHeight:"1.5rem"}],lg:["1.125rem",{lineHeight:"1.75rem"}],xl:["1.25rem",{lineHeight:"1.75rem"}],"2xl":["1.5rem",{lineHeight:"2rem"}],"3xl":["1.875rem",{lineHeight:"2.25rem"}],"4xl":["2.25rem",{lineHeight:"2.5rem"}],"5xl":["3rem",{lineHeight:"1"}],"6xl":["3.75rem",{lineHeight:"1"}],"7xl":["4.5rem",{lineHeight:"1"}],"8xl":["6rem",{lineHeight:"1"}],"9xl":["8rem",{lineHeight:"1"}]},fontWeight:{thin:"100",extralight:"200",light:"300",normal:"400",medium:"500",semibold:"600",bold:"700",extrabold:"800",black:"900"},gap:({theme:e})=>e("spacing"),gradientColorStops:({theme:e})=>e("colors"),gradientColorStopPositions:{"0%":"0%","5%":"5%","10%":"10%","15%":"15%","20%":"20%","25%":"25%","30%":"30%","35%":"35%","40%":"40%","45%":"45%","50%":"50%","55%":"55%","60%":"60%","65%":"65%","70%":"70%","75%":"75%","80%":"80%","85%":"85%","90%":"90%","95%":"95%","100%":"100%",...x},grayscale:{0:"0",DEFAULT:"100%",...x},gridAutoColumns:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridAutoRows:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridColumn:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridColumnEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...R},gridColumnStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...R},gridRow:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridRowEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...R},gridRowStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...R},gridTemplateColumns:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...ft},gridTemplateRows:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...ft},height:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),hueRotate:{0:"0deg",15:"15deg",30:"30deg",60:"60deg",90:"90deg",180:"180deg",...fe},inset:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),invert:{0:"0",DEFAULT:"100%",...x},keyframes:{spin:{to:{transform:"rotate(360deg)"}},ping:{"75%, 100%":{transform:"scale(2)",opacity:"0"}},pulse:{"50%":{opacity:".5"}},bounce:{"0%, 100%":{transform:"translateY(-25%)",animationTimingFunction:"cubic-bezier(0.8,0,1,1)"},"50%":{transform:"none",animationTimingFunction:"cubic-bezier(0,0,0.2,1)"}}},letterSpacing:{tighter:"-0.05em",tight:"-0.025em",normal:"0em",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeight:{none:"1",tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625",loose:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},listStyleType:{none:"none",disc:"disc",decimal:"decimal"},listStyleImage:{none:"none"},margin:({theme:e})=>({auto:"auto",...e("spacing")}),lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",...R},maxHeight:({theme:e})=>({none:"none",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),maxWidth:({theme:e})=>({none:"none",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",prose:"65ch",...e("spacing")}),minHeight:({theme:e})=>({full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),minWidth:({theme:e})=>({full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),objectPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},opacity:{0:"0",5:"0.05",10:"0.1",15:"0.15",20:"0.2",25:"0.25",30:"0.3",35:"0.35",40:"0.4",45:"0.45",50:"0.5",55:"0.55",60:"0.6",65:"0.65",70:"0.7",75:"0.75",80:"0.8",85:"0.85",90:"0.9",95:"0.95",100:"1",...x},order:{first:"-9999",last:"9999",none:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",...R},outlineColor:({theme:e})=>e("colors"),outlineOffset:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...D},outlineWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...D},padding:({theme:e})=>e("spacing"),placeholderColor:({theme:e})=>e("colors"),placeholderOpacity:({theme:e})=>e("opacity"),ringColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),ringOffsetColor:({theme:e})=>e("colors"),ringOffsetWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...D},ringOpacity:({theme:e})=>({DEFAULT:"0.5",...e("opacity")}),ringWidth:{DEFAULT:"3px",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...D},rotate:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",45:"45deg",90:"90deg",180:"180deg",...fe},saturate:{0:"0",50:".5",100:"1",150:"1.5",200:"2",...x},scale:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",...x},screens:{sm:"40rem",md:"48rem",lg:"64rem",xl:"80rem","2xl":"96rem"},scrollMargin:({theme:e})=>e("spacing"),scrollPadding:({theme:e})=>e("spacing"),sepia:{0:"0",DEFAULT:"100%",...x},skew:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",...fe},space:({theme:e})=>e("spacing"),spacing:{px:"1px",0:"0px",.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},stroke:({theme:e})=>({none:"none",...e("colors")}),strokeWidth:{0:"0",1:"1",2:"2",...R},supports:{},data:{},textColor:({theme:e})=>e("colors"),textDecorationColor:({theme:e})=>e("colors"),textDecorationThickness:{auto:"auto","from-font":"from-font",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...D},textIndent:({theme:e})=>e("spacing"),textOpacity:({theme:e})=>e("opacity"),textUnderlineOffset:{auto:"auto",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...D},transformOrigin:{center:"center",top:"top","top-right":"top right",right:"right","bottom-right":"bottom right",bottom:"bottom","bottom-left":"bottom left",left:"left","top-left":"top left"},transitionDelay:{0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...ct},transitionDuration:{DEFAULT:"150ms",0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...ct},transitionProperty:{none:"none",all:"all",DEFAULT:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter",colors:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke",opacity:"opacity",shadow:"box-shadow",transform:"transform"},transitionTimingFunction:{DEFAULT:"cubic-bezier(0.4, 0, 0.2, 1)",linear:"linear",in:"cubic-bezier(0.4, 0, 1, 1)",out:"cubic-bezier(0, 0, 0.2, 1)","in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},translate:({theme:e})=>({"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),size:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),width:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",screen:"100vw",svw:"100svw",lvw:"100lvw",dvw:"100dvw",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),willChange:{auto:"auto",scroll:"scroll-position",contents:"contents",transform:"transform"},zIndex:{auto:"auto",0:"0",10:"10",20:"20",30:"30",40:"40",50:"50",...R}};var Er=64;function U(e,r=[]){return{kind:"rule",selector:e,nodes:r}}function E(e,r="",t=[]){return{kind:"at-rule",name:e,params:r,nodes:t}}function _(e,r=[]){return e.charCodeAt(0)===Er?ee(e,r):U(e,r)}function P(e,r,t=!1){return{kind:"declaration",property:e,value:r,important:t}}function Ve(e){return{kind:"comment",value:e}}function z(e,r){let t=0,n={file:null,code:""};function i(o,s=0){let a="",u=" ".repeat(s);if(o.kind==="declaration"){if(a+=`${u}${o.property}: ${o.value}${o.important?" !important":""}; +`,r){t+=u.length;let p=t;t+=o.property.length,t+=2,t+=o.value?.length??0,o.important&&(t+=11);let c=t;t+=2,o.dst=[n,p,c]}}else if(o.kind==="rule"){if(a+=`${u}${o.selector} { +`,r){t+=u.length;let p=t;t+=o.selector.length,t+=1;let c=t;o.dst=[n,p,c],t+=2}for(let p of o.nodes)a+=i(p,s+1);a+=`${u}} +`,r&&(t+=u.length,t+=2)}else if(o.kind==="at-rule"){if(o.nodes.length===0){let p=`${u}${o.name} ${o.params}; +`;if(r){t+=u.length;let c=t;t+=o.name.length,t+=1,t+=o.params.length;let f=t;t+=2,o.dst=[n,c,f]}return p}if(a+=`${u}${o.name}${o.params?` ${o.params} `:" "}{ +`,r){t+=u.length;let p=t;t+=o.name.length,o.params&&(t+=1,t+=o.params.length),t+=1;let c=t;o.dst=[n,p,c],t+=2}for(let p of o.nodes)a+=i(p,s+1);a+=`${u}} +`,r&&(t+=u.length,t+=2)}else if(o.kind==="comment"){if(a+=`${u}/*${o.value}*/ +`,r){t+=u.length;let p=t;t+=2+o.value.length+2;let c=t;o.dst=[n,p,c],t+=1}}else if(o.kind==="context"||o.kind==="at-root")return"";return a}let l="";for(let o of e)l+=i(o,0);return n.code=l,l}function Tr(e,r){if(typeof e!="string")throw new TypeError("expected path to be a string");if(e==="\\"||e==="/")return"/";var t=e.length;if(t<=1)return e;var n="";if(t>4&&e[3]==="\\"){var i=e[2];(i==="?"||i===".")&&e.slice(0,2)==="\\\\"&&(e=e.slice(2),n="//")}var l=e.split(/[/\\]+/);return r!==!1&&l[l.length-1]===""&&l.pop(),n+l.join("/")}function Te(e){let r=Tr(e);return e.startsWith("\\\\")&&r.startsWith("/")&&!r.startsWith("//")?`/${r}`:r}var Re=/(?[\w-]+\([^)]*\)|"[^"]*"|'[^']*'|[^,]\S*[^,])\s*(?:\s(?\w[^,]+))?(?:,|$)/g,Dr=/(?Rr.test(e),Lr=e=>Pr.test(e);async function dt({css:e,base:r,root:t}){if(!e.includes("url(")&&!e.includes("image-set("))return e;let n=te(e),i=[];function l(o){if(o[0]==="/")return o;let s=Ne.posix.join(Te(r),o),a=Ne.posix.relative(Te(t),s);return a.startsWith(".")||(a="./"+a),a}return g(n,o=>{if(o.kind!=="declaration"||!o.value)return;let s=Re.test(o.value),a=pt.test(o.value);if(s||a){let u=a?zr:mt;i.push(u(o.value,l).then(p=>{o.value=p}))}}),i.length&&await Promise.all(i),z(n)}function mt(e,r){return ht(e,Re,async t=>{let[n,i]=t;return await gt(i.trim(),n,r)})}async function zr(e,r){return await ht(e,pt,async t=>{let[,n]=t;return await Mr(n,async({url:l})=>Re.test(l)?await mt(l,r):Nr.test(l)?l:await gt(l,l,r))})}async function gt(e,r,t,n="url"){let i="",l=e[0];if((l==='"'||l==="'")&&(i=l,e=e.slice(1,-1)),Kr(e))return r;let o=await t(e);return i===""&&o!==encodeURI(o)&&(i='"'),i==="'"&&o.includes("'")&&(i='"'),i==='"'&&o.includes('"')&&(o=o.replace(Dr,'\\"')),`${n}(${i}${o}${i})`}function Kr(e,r){return Lr(e)||Ur(e)||!e[0].match(/[.a-zA-Z0-9_]/)||Or.test(e)}function Mr(e,r){return Promise.all(Fr(e).map(async({url:t,descriptor:n})=>({url:await r({url:t,descriptor:n}),descriptor:n}))).then(jr)}function Fr(e){let r=e.trim().replace(Ir," ").replace(/\r?\n/,"").replace(/,\s+/,", ").replaceAll(/\s+/g," ").matchAll(_r);return Array.from(r,({groups:t})=>({url:t?.url?.trim()??"",descriptor:t?.descriptor?.trim()??""})).filter(({url:t})=>!!t)}function jr(e){return e.map(({url:r,descriptor:t})=>r+(t?` ${t}`:"")).join(", ")}async function ht(e,r,t){let n,i=e,l="";for(;n=r.exec(i);)l+=i.slice(0,n.index),l+=await t(n),i=i.slice(n.index+n[0].length);return l+=i,l}function xt({base:e,from:r,polyfills:t,onDependency:n,shouldRewriteUrls:i,customCssResolver:l,customJsResolver:o}){return{base:e,polyfills:t,from:r,async loadModule(s,a){return Ct(s,a,n,o)},async loadStylesheet(s,a){let u=await St(s,a,n,l);return i&&(u.content=await dt({css:u.content,root:e,base:u.base})),u}}}async function At(e){if(e.root&&e.root!=="none"){let r=/[*{]/,t=[];for(let i of e.root.pattern.split("/")){if(r.test(i))break;t.push(i)}if(!await yt.stat(re.resolve(e.root.base,t.join("/"))).then(i=>i.isDirectory()).catch(()=>!1))throw new Error(`The \`source(${e.root.pattern})\` does not exist or is not a directory.`)}}async function ou(e,r){let t=await Gr(e,xt(r));return await At(t),t}async function lu(e,r){let t=await Yr(e,xt(r));return await At(t),t}async function au(e,{base:r}){return Br(e,{base:r,async loadModule(t,n){return Ct(t,n,()=>{})},async loadStylesheet(t,n){return St(t,n,()=>{})}})}async function Ct(e,r,t,n){if(e[0]!=="."){let s=await bt(e,r,n);if(!s)throw new Error(`Could not resolve '${e}' from '${r}'`);let a=await wt(vt(s).href);return{path:s,base:re.dirname(s),module:a.default??a}}let i=await bt(e,r,n);if(!i)throw new Error(`Could not resolve '${e}' from '${r}'`);let[l,o]=await Promise.all([wt(vt(i).href+"?id="+Date.now()),Ue(i)]);for(let s of o)t(s);return{path:i,base:re.dirname(i),module:l.default??l}}async function St(e,r,t,n){let i=await qr(e,r,n);if(!i)throw new Error(`Could not resolve '${e}' from '${r}'`);t(i);let l=await yt.readFile(i,"utf-8");return{path:i,base:re.dirname(i),content:l}}var kt=null;async function wt(e){if(typeof globalThis.__tw_load=="function"){let r=await globalThis.__tw_load(e);if(r)return r}try{return await import(e)}catch{return kt??=Wr(import.meta.url,{moduleCache:!1,fsCache:!1}),await kt.import(e)}}var _e=["node_modules",...process.env.NODE_PATH?[...process.env.NODE_PATH.split(re.delimiter)]:[]],Hr=B.ResolverFactory.createResolver({fileSystem:new B.CachedInputFileSystem(Oe,4e3),useSyncFileSystemCalls:!0,extensions:[".css"],mainFields:["style"],conditionNames:["style"],modules:_e});async function qr(e,r,t){if(typeof globalThis.__tw_resolve=="function"){let n=globalThis.__tw_resolve(e,r);if(n)return Promise.resolve(n)}if(t){let n=await t(e,r);if(n)return n}return Pe(Hr,e,r)}var Zr=B.ResolverFactory.createResolver({fileSystem:new B.CachedInputFileSystem(Oe,4e3),useSyncFileSystemCalls:!0,extensions:[".js",".json",".node",".ts"],conditionNames:["node","import"],modules:_e}),Qr=B.ResolverFactory.createResolver({fileSystem:new B.CachedInputFileSystem(Oe,4e3),useSyncFileSystemCalls:!0,extensions:[".js",".json",".node",".ts"],conditionNames:["node","require"],modules:_e});async function bt(e,r,t){if(typeof globalThis.__tw_resolve=="function"){let n=globalThis.__tw_resolve(e,r);if(n)return Promise.resolve(n)}if(t){let n=await t(e,r);if(n)return n}return Pe(Zr,e,r).catch(()=>Pe(Qr,e,r))}function Pe(e,r,t){return new Promise((n,i)=>e.resolve({},t,r,{},(l,o)=>{if(l)return i(l);n(o)}))}Symbol.dispose??=Symbol("Symbol.dispose");Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");var $t=class{constructor(r=de,t=n=>{process.stderr.write(`${n} +`)}){this.shouldReport=r;this.defaultFlush=t}shouldReport;defaultFlush;#r=new h(()=>({value:0}));#t=new h(()=>({value:0n}));#e=[];hit(r){this.#r.get(r).value++}start(r){let t=this.#e.map(i=>i.label).join("//"),n=`${t}${t.length===0?"":"//"}${r}`;this.#r.get(n).value++,this.#t.get(n),this.#e.push({id:n,label:r,namespace:t,value:process.hrtime.bigint()})}end(r){let t=process.hrtime.bigint();if(this.#e[this.#e.length-1].label!==r)throw new Error(`Mismatched timer label: \`${r}\`, expected \`${this.#e[this.#e.length-1].label}\``);let n=this.#e.pop(),i=t-n.value;this.#t.get(n.id).value+=i}track(r){this.start(r);let t=!1;return{[Symbol.dispose]:()=>{t||(this.end(r),t=!0)},[Symbol.asyncDispose]:()=>{t||(this.end(r),t=!0)}}}span(r,t){this.start(r);let n=!1;try{let i=t();return n=i&&typeof i.then=="function",n?i.finally(()=>this.end(r)):i}finally{n||this.end(r)}}reset(){this.#r.clear(),this.#t.clear(),this.#e.splice(0)}report(r=this.defaultFlush){let t=[],n=!1;for(let o=this.#e.length-1;o>=0;o--)this.end(this.#e[o].label);for(let[o,{value:s}]of this.#r.entries()){if(this.#t.has(o))continue;t.length===0&&(n=!0,t.push("Hits:"));let a=o.split("//").length;t.push(`${" ".repeat(a)}${o} ${pe(Vt(`\xD7 ${s}`))}`)}this.#t.size>0&&n&&t.push(` +Timers:`);let i=-1/0,l=new Map;for(let[o,{value:s}]of this.#t){let a=`${(Number(s)/1e6).toFixed(2)}ms`;l.set(o,a),i=Math.max(i,a.length)}for(let o of this.#t.keys()){let s=o.split("//").length;t.push(`${pe(`[${l.get(o).padStart(i," ")}]`)}${" ".repeat(s-1)}${s===1?" ":pe(" \u21B3 ")}${o.split("//").pop()} ${this.#r.get(o).value===1?"":pe(Vt(`\xD7 ${this.#r.get(o).value}`))}`.trimEnd())}r(` +${t.join(` +`)} +`),this.reset()}[Symbol.dispose](){this.shouldReport&&this.report()}};function pe(e){return`\x1B[2m${e}\x1B[22m`}function Vt(e){return`\x1B[34m${e}\x1B[39m`}import Jr from"@jridgewell/remapping";import{Features as ne,transform as Xr}from"lightningcss";import en from"magic-string";function mu(e,{file:r="input.css",minify:t=!1,map:n}={}){function i(a,u){return Xr({filename:r,code:a,minify:t,sourceMap:typeof u<"u",inputSourceMap:u,drafts:{customMedia:!0},nonStandard:{deepSelectorCombinator:!0},include:ne.Nesting|ne.MediaQueries,exclude:ne.LogicalProperties|ne.DirSelector|ne.LightDark,targets:{safari:16<<16|1024,ios_saf:16<<16|1024,firefox:8388608,chrome:7274496},errorRecovery:!0})}let l=i(Buffer.from(e),n);if(n=l.map?.toString(),l.warnings=l.warnings.filter(a=>!/'(deep|slotted|global)' is not recognized as a valid pseudo-/.test(a.message)),l.warnings.length>0){let a=e.split(` +`),u=[`Found ${l.warnings.length} ${l.warnings.length===1?"warning":"warnings"} while optimizing generated CSS:`];for(let[p,c]of l.warnings.entries()){u.push(""),l.warnings.length>1&&u.push(`Issue #${p+1}:`);let f=2,d=Math.max(0,c.loc.line-f-1),m=Math.min(a.length,c.loc.line+f),C=a.slice(d,m).map((k,I)=>d+I+1===c.loc.line?`${ie("\u2502")} ${k}`:ie(`\u2502 ${k}`));C.splice(c.loc.line-d,0,`${ie("\u2506")}${" ".repeat(c.loc.column-1)} ${tn(`${ie("^--")} ${c.message}`)}`,`${ie("\u2506")}`),u.push(...C)}u.push(""),console.warn(u.join(` +`))}l=i(l.code,n),n=l.map?.toString();let o=l.code.toString(),s=new en(o);if(s.replaceAll("@media not (","@media not all and ("),n!==void 0&&s.hasChanged()){let a=s.generateMap({source:"original",hires:"boundary"}).toString();n=Jr([a,n],()=>null).toString()}return o=s.toString(),{code:o,map:n}}function ie(e){return`\x1B[2m${e}\x1B[22m`}function tn(e){return`\x1B[33m${e}\x1B[39m`}import{SourceMapGenerator as rn}from"source-map-js";function nn(e){let r=new rn,t=1,n=new h(i=>({url:i?.url??``,content:i?.content??""}));for(let i of e.mappings){let l=n.get(i.originalPosition?.source??null);r.addMapping({generated:i.generatedPosition,original:i.originalPosition,source:l.url,name:i.name}),r.setSourceContent(l.url,l.content)}return r.toString()}function ku(e){let r=typeof e=="string"?e:nn(e);function t(n){return`/*# sourceMappingURL=${n} */ +`}return{raw:r,get inline(){let n=Buffer.from(r,"utf-8").toString("base64");return t(`data:application/json;base64,${n}`)},comment:t}}if(!process.versions.bun)if(M.registerHooks)M.registerHooks({resolve:De});else{let e=M.createRequire(import.meta.url);M.register?.(on(e.resolve("@tailwindcss/node/esm-cache-loader")))}export{tu as Features,$t as Instrumentation,ru as Polyfills,au as __unstable__loadDesignSystem,lu as compile,ou as compileAst,me as env,Ct as loadModule,Te as normalizePath,mu as optimize,ku as toSourceMap}; diff --git a/client/node_modules/@tailwindcss/node/dist/require-cache.d.ts b/client/node_modules/@tailwindcss/node/dist/require-cache.d.ts new file mode 100644 index 0000000..de970b9 --- /dev/null +++ b/client/node_modules/@tailwindcss/node/dist/require-cache.d.ts @@ -0,0 +1,3 @@ +declare function clearRequireCache(files: string[]): void; + +export { clearRequireCache }; diff --git a/client/node_modules/@tailwindcss/node/dist/require-cache.js b/client/node_modules/@tailwindcss/node/dist/require-cache.js new file mode 100644 index 0000000..398995f --- /dev/null +++ b/client/node_modules/@tailwindcss/node/dist/require-cache.js @@ -0,0 +1 @@ +"use strict";var i=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var l=Object.prototype.hasOwnProperty;var n=(r,e)=>{for(var t in e)i(r,t,{get:e[t],enumerable:!0})},u=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of f(e))!l.call(r,c)&&c!==t&&i(r,c,{get:()=>e[c],enumerable:!(o=a(e,c))||o.enumerable});return r};var h=r=>u(i({},"__esModule",{value:!0}),r);var d={};n(d,{clearRequireCache:()=>q});module.exports=h(d);function q(r){for(let e of r)delete require.cache[e]}0&&(module.exports={clearRequireCache}); diff --git a/client/node_modules/@tailwindcss/node/package.json b/client/node_modules/@tailwindcss/node/package.json new file mode 100644 index 0000000..6c442c2 --- /dev/null +++ b/client/node_modules/@tailwindcss/node/package.json @@ -0,0 +1,48 @@ +{ + "name": "@tailwindcss/node", + "version": "4.3.1", + "description": "A utility-first CSS framework for rapidly building custom user interfaces.", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/tailwindlabs/tailwindcss.git", + "directory": "packages/@tailwindcss-node" + }, + "bugs": "https://github.com/tailwindlabs/tailwindcss/issues", + "homepage": "https://tailwindcss.com", + "files": [ + "dist/" + ], + "publishConfig": { + "provenance": true, + "access": "public" + }, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + }, + "./require-cache": { + "types": "./dist/require-cache.d.ts", + "default": "./dist/require-cache.js" + }, + "./esm-cache-loader": { + "types": "./dist/esm-cache.loader.d.mts", + "default": "./dist/esm-cache.loader.mjs" + } + }, + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "5.21.6", + "jiti": "^2.7.0", + "lightningcss": "1.32.0", + "magic-string": "^0.30.21", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.1" + }, + "scripts": { + "build": "tsup-node", + "dev": "pnpm run build -- --watch" + } +} \ No newline at end of file diff --git a/client/node_modules/@tailwindcss/oxide-linux-x64-gnu/LICENSE b/client/node_modules/@tailwindcss/oxide-linux-x64-gnu/LICENSE new file mode 100644 index 0000000..d6a8229 --- /dev/null +++ b/client/node_modules/@tailwindcss/oxide-linux-x64-gnu/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Tailwind Labs, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/client/node_modules/@tailwindcss/oxide-linux-x64-gnu/README.md b/client/node_modules/@tailwindcss/oxide-linux-x64-gnu/README.md new file mode 100644 index 0000000..f129c11 --- /dev/null +++ b/client/node_modules/@tailwindcss/oxide-linux-x64-gnu/README.md @@ -0,0 +1,3 @@ +# `@tailwindcss/oxide-linux-x64-gnu` + +This is the **x86_64-unknown-linux-gnu** binary for `@tailwindcss/oxide` diff --git a/client/node_modules/@tailwindcss/oxide-linux-x64-gnu/package.json b/client/node_modules/@tailwindcss/oxide-linux-x64-gnu/package.json new file mode 100644 index 0000000..67ec47c --- /dev/null +++ b/client/node_modules/@tailwindcss/oxide-linux-x64-gnu/package.json @@ -0,0 +1,30 @@ +{ + "name": "@tailwindcss/oxide-linux-x64-gnu", + "version": "4.3.1", + "repository": { + "type": "git", + "url": "git+https://github.com/tailwindlabs/tailwindcss.git", + "directory": "crates/node/npm/linux-x64-gnu" + }, + "os": [ + "linux" + ], + "cpu": [ + "x64" + ], + "main": "tailwindcss-oxide.linux-x64-gnu.node", + "files": [ + "tailwindcss-oxide.linux-x64-gnu.node" + ], + "publishConfig": { + "provenance": true, + "access": "public" + }, + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "libc": [ + "glibc" + ] +} \ No newline at end of file diff --git a/client/node_modules/@tailwindcss/oxide-linux-x64-gnu/tailwindcss-oxide.linux-x64-gnu.node b/client/node_modules/@tailwindcss/oxide-linux-x64-gnu/tailwindcss-oxide.linux-x64-gnu.node new file mode 100644 index 0000000..986e0d3 Binary files /dev/null and b/client/node_modules/@tailwindcss/oxide-linux-x64-gnu/tailwindcss-oxide.linux-x64-gnu.node differ diff --git a/client/node_modules/@tailwindcss/oxide/LICENSE b/client/node_modules/@tailwindcss/oxide/LICENSE new file mode 100644 index 0000000..d6a8229 --- /dev/null +++ b/client/node_modules/@tailwindcss/oxide/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Tailwind Labs, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/client/node_modules/@tailwindcss/oxide/index.d.ts b/client/node_modules/@tailwindcss/oxide/index.d.ts new file mode 100644 index 0000000..184e089 --- /dev/null +++ b/client/node_modules/@tailwindcss/oxide/index.d.ts @@ -0,0 +1,48 @@ +/* auto-generated by NAPI-RS */ +/* eslint-disable */ +export declare class Scanner { + constructor(opts: ScannerOptions) + scan(): Array + scanFiles(input: Array): Array + getCandidatesWithPositions(input: ChangedContent): Array + get files(): Array + get globs(): Array + get normalizedSources(): Array +} + +export interface CandidateWithPosition { + /** The candidate string */ + candidate: string + /** The position of the candidate inside the content file */ + position: number +} + +export interface ChangedContent { + /** File path to the changed file */ + file?: string + /** Contents of the changed file */ + content?: string + /** File extension */ + extension: string +} + +export interface GlobEntry { + /** Base path of the glob */ + base: string + /** Glob pattern */ + pattern: string +} + +export interface ScannerOptions { + /** Glob sources */ + sources?: Array +} + +export interface SourceEntry { + /** Base path of the glob */ + base: string + /** Glob pattern */ + pattern: string + /** Negated flag */ + negated: boolean +} diff --git a/client/node_modules/@tailwindcss/oxide/index.js b/client/node_modules/@tailwindcss/oxide/index.js new file mode 100644 index 0000000..ef2f522 --- /dev/null +++ b/client/node_modules/@tailwindcss/oxide/index.js @@ -0,0 +1,589 @@ +// prettier-ignore +/* eslint-disable */ +// @ts-nocheck +/* auto-generated by NAPI-RS */ + +const { readFileSync } = require('node:fs') +let nativeBinding = null +const loadErrors = [] + +const isMusl = () => { + let musl = false + if (process.platform === 'linux') { + musl = isMuslFromFilesystem() + if (musl === null) { + musl = isMuslFromReport() + } + if (musl === null) { + musl = isMuslFromChildProcess() + } + } + return musl +} + +const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-') + +const isMuslFromFilesystem = () => { + try { + return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl') + } catch { + return null + } +} + +const isMuslFromReport = () => { + let report = null + if (typeof process.report?.getReport === 'function') { + process.report.excludeNetwork = true + report = process.report.getReport() + } + if (!report) { + return null + } + if (report.header && report.header.glibcVersionRuntime) { + return false + } + if (Array.isArray(report.sharedObjects)) { + if (report.sharedObjects.some(isFileMusl)) { + return true + } + } + return false +} + +const isMuslFromChildProcess = () => { + try { + return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl') + } catch (e) { + // If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false + return false + } +} + +function requireNative() { + if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) { + try { + return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH); + } catch (err) { + loadErrors.push(err) + } + } else if (process.platform === 'android') { + if (process.arch === 'arm64') { + try { + return require('./tailwindcss-oxide.android-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-android-arm64') + const bindingPackageVersion = require('@tailwindcss/oxide-android-arm64/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm') { + try { + return require('./tailwindcss-oxide.android-arm-eabi.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-android-arm-eabi') + const bindingPackageVersion = require('@tailwindcss/oxide-android-arm-eabi/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`)) + } + } else if (process.platform === 'win32') { + if (process.arch === 'x64') { + if (process.config?.variables?.shlib_suffix === 'dll.a' || process.config?.variables?.node_target_type === 'shared_library') { + try { + return require('./tailwindcss-oxide.win32-x64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-win32-x64-gnu') + const bindingPackageVersion = require('@tailwindcss/oxide-win32-x64-gnu/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./tailwindcss-oxide.win32-x64-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-win32-x64-msvc') + const bindingPackageVersion = require('@tailwindcss/oxide-win32-x64-msvc/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'ia32') { + try { + return require('./tailwindcss-oxide.win32-ia32-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-win32-ia32-msvc') + const bindingPackageVersion = require('@tailwindcss/oxide-win32-ia32-msvc/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./tailwindcss-oxide.win32-arm64-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-win32-arm64-msvc') + const bindingPackageVersion = require('@tailwindcss/oxide-win32-arm64-msvc/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`)) + } + } else if (process.platform === 'darwin') { + try { + return require('./tailwindcss-oxide.darwin-universal.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-darwin-universal') + const bindingPackageVersion = require('@tailwindcss/oxide-darwin-universal/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + if (process.arch === 'x64') { + try { + return require('./tailwindcss-oxide.darwin-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-darwin-x64') + const bindingPackageVersion = require('@tailwindcss/oxide-darwin-x64/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./tailwindcss-oxide.darwin-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-darwin-arm64') + const bindingPackageVersion = require('@tailwindcss/oxide-darwin-arm64/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`)) + } + } else if (process.platform === 'freebsd') { + if (process.arch === 'x64') { + try { + return require('./tailwindcss-oxide.freebsd-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-freebsd-x64') + const bindingPackageVersion = require('@tailwindcss/oxide-freebsd-x64/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./tailwindcss-oxide.freebsd-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-freebsd-arm64') + const bindingPackageVersion = require('@tailwindcss/oxide-freebsd-arm64/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`)) + } + } else if (process.platform === 'linux') { + if (process.arch === 'x64') { + if (isMusl()) { + try { + return require('./tailwindcss-oxide.linux-x64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-x64-musl') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-x64-musl/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./tailwindcss-oxide.linux-x64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-x64-gnu') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-x64-gnu/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'arm64') { + if (isMusl()) { + try { + return require('./tailwindcss-oxide.linux-arm64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-arm64-musl') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-arm64-musl/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./tailwindcss-oxide.linux-arm64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-arm64-gnu') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-arm64-gnu/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'arm') { + if (isMusl()) { + try { + return require('./tailwindcss-oxide.linux-arm-musleabihf.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-arm-musleabihf') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-arm-musleabihf/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./tailwindcss-oxide.linux-arm-gnueabihf.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-arm-gnueabihf') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-arm-gnueabihf/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'loong64') { + if (isMusl()) { + try { + return require('./tailwindcss-oxide.linux-loong64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-loong64-musl') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-loong64-musl/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./tailwindcss-oxide.linux-loong64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-loong64-gnu') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-loong64-gnu/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'riscv64') { + if (isMusl()) { + try { + return require('./tailwindcss-oxide.linux-riscv64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-riscv64-musl') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-riscv64-musl/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./tailwindcss-oxide.linux-riscv64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-riscv64-gnu') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-riscv64-gnu/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'ppc64') { + try { + return require('./tailwindcss-oxide.linux-ppc64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-ppc64-gnu') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-ppc64-gnu/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 's390x') { + try { + return require('./tailwindcss-oxide.linux-s390x-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-s390x-gnu') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-s390x-gnu/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`)) + } + } else if (process.platform === 'openharmony') { + if (process.arch === 'arm64') { + try { + return require('./tailwindcss-oxide.openharmony-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-openharmony-arm64') + const bindingPackageVersion = require('@tailwindcss/oxide-openharmony-arm64/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'x64') { + try { + return require('./tailwindcss-oxide.openharmony-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-openharmony-x64') + const bindingPackageVersion = require('@tailwindcss/oxide-openharmony-x64/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm') { + try { + return require('./tailwindcss-oxide.openharmony-arm.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-openharmony-arm') + const bindingPackageVersion = require('@tailwindcss/oxide-openharmony-arm/package.json').version + if (bindingPackageVersion !== '4.3.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`)) + } + } else { + loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`)) + } +} + +nativeBinding = requireNative() + +// NAPI_RS_FORCE_WASI is a tri-state flag: +// unset / any other value → native binding preferred, WASI is only a fallback +// 'true' → force WASI fallback even if native loaded +// 'error' → force WASI and throw if no WASI binding is found +// Treating any non-empty string as truthy (the historical behavior) meant +// NAPI_RS_FORCE_WASI=false, NAPI_RS_FORCE_WASI=0, etc. inadvertently triggered +// the WASI path, causing ENOENT for packages shipped without a .wasi.cjs file. +const forceWasi = + process.env.NAPI_RS_FORCE_WASI === 'true' || process.env.NAPI_RS_FORCE_WASI === 'error' + +if (!nativeBinding || forceWasi) { + let wasiBinding = null + let wasiBindingError = null + try { + wasiBinding = require('./tailwindcss-oxide.wasi.cjs') + nativeBinding = wasiBinding + } catch (err) { + if (forceWasi) { + wasiBindingError = err + } + } + if (!nativeBinding || forceWasi) { + try { + wasiBinding = require('@tailwindcss/oxide-wasm32-wasi') + nativeBinding = wasiBinding + } catch (err) { + if (forceWasi) { + if (!wasiBindingError) { + wasiBindingError = err + } else { + wasiBindingError.cause = err + } + loadErrors.push(err) + } + } + } + if (process.env.NAPI_RS_FORCE_WASI === 'error' && !wasiBinding) { + const error = new Error('WASI binding not found and NAPI_RS_FORCE_WASI is set to error') + error.cause = wasiBindingError + throw error + } +} + +if (!nativeBinding) { + if (loadErrors.length > 0) { + throw new Error( + `Cannot find native binding. ` + + `npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` + + 'Please try `npm i` again after removing both package-lock.json and node_modules directory.', + { + cause: loadErrors.reduce((err, cur) => { + cur.cause = err + return cur + }), + }, + ) + } + throw new Error(`Failed to load native binding`) +} + +module.exports = nativeBinding +module.exports.Scanner = nativeBinding.Scanner diff --git a/client/node_modules/@tailwindcss/oxide/package.json b/client/node_modules/@tailwindcss/oxide/package.json new file mode 100644 index 0000000..6d0b8ed --- /dev/null +++ b/client/node_modules/@tailwindcss/oxide/package.json @@ -0,0 +1,75 @@ +{ + "name": "@tailwindcss/oxide", + "version": "4.3.1", + "repository": { + "type": "git", + "url": "git+https://github.com/tailwindlabs/tailwindcss.git", + "directory": "crates/node" + }, + "main": "index.js", + "types": "index.d.ts", + "napi": { + "binaryName": "tailwindcss-oxide", + "packageName": "@tailwindcss/oxide", + "targets": [ + "armv7-linux-androideabi", + "aarch64-linux-android", + "aarch64-apple-darwin", + "aarch64-unknown-linux-gnu", + "aarch64-unknown-linux-musl", + "armv7-unknown-linux-gnueabihf", + "x86_64-unknown-linux-musl", + "x86_64-unknown-freebsd", + "i686-pc-windows-msvc", + "aarch64-pc-windows-msvc", + "wasm32-wasip1-threads" + ], + "wasm": { + "initialMemory": 16384, + "browser": { + "fs": true + } + } + }, + "license": "MIT", + "devDependencies": { + "@napi-rs/cli": "3.7.0", + "@napi-rs/wasm-runtime": "^1.1.4", + "emnapi": "1.10.0" + }, + "engines": { + "node": ">= 20" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "publishConfig": { + "provenance": true, + "access": "public" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.1", + "@tailwindcss/oxide-freebsd-x64": "4.3.1", + "@tailwindcss/oxide-darwin-arm64": "4.3.1", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.1", + "@tailwindcss/oxide-linux-x64-musl": "4.3.1", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.1", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.1", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.1", + "@tailwindcss/oxide-wasm32-wasi": "4.3.1", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.1", + "@tailwindcss/oxide-darwin-x64": "4.3.1", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.1" + }, + "scripts": { + "build": "pnpm run build:platform && pnpm run build:wasm", + "build:platform": "napi build --platform --release", + "postbuild:platform": "node ./scripts/move-artifacts.mjs", + "build:wasm": "napi build --release --target wasm32-wasip1-threads", + "postbuild:wasm": "node ./scripts/move-artifacts.mjs", + "dev": "cargo watch --quiet --shell 'npm run build'", + "build:debug": "napi build --platform", + "version": "napi version" + } +} \ No newline at end of file diff --git a/client/node_modules/@tailwindcss/postcss/LICENSE b/client/node_modules/@tailwindcss/postcss/LICENSE new file mode 100644 index 0000000..d6a8229 --- /dev/null +++ b/client/node_modules/@tailwindcss/postcss/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Tailwind Labs, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/client/node_modules/@tailwindcss/postcss/README.md b/client/node_modules/@tailwindcss/postcss/README.md new file mode 100644 index 0000000..3facf28 --- /dev/null +++ b/client/node_modules/@tailwindcss/postcss/README.md @@ -0,0 +1,111 @@ +

+ + + + + Tailwind CSS + + +

+ +

+ A utility-first CSS framework for rapidly building custom user interfaces. +

+ +

+ Build Status + Total Downloads + Latest Release + License +

+ +--- + +## Documentation + +For full documentation, visit [tailwindcss.com](https://tailwindcss.com). + +## Community + +For help, discussion about best practices, or feature ideas: + +[Discuss Tailwind CSS on GitHub](https://github.com/tailwindlabs/tailwindcss/discussions) + +## Contributing + +If you're interested in contributing to Tailwind CSS, please read our [contributing docs](https://github.com/tailwindlabs/tailwindcss/blob/main/.github/CONTRIBUTING.md) **before submitting a pull request**. + +--- + +## `@tailwindcss/postcss` plugin API + +### Changing where the plugin searches for source files + +You can use the `base` option (defaults to the current working directory) to change the directory in which the plugin searches for source files: + +```js +import tailwindcss from '@tailwindcss/postcss' + +export default { + plugins: [ + tailwindcss({ + base: path.resolve(__dirname, './path'), + }), + ], +} +``` + +### Enabling or disabling Lightning CSS + +By default, this plugin detects whether or not the CSS is being built for production by checking the `NODE_ENV` environment variable. When building for production Lightning CSS will be enabled otherwise it is disabled. + +If you want to always enable or disable Lightning CSS the `optimize` option may be used: + +```js +import tailwindcss from '@tailwindcss/postcss' + +export default { + plugins: [ + tailwindcss({ + // Enable or disable Lightning CSS + optimize: false, + }), + ], +} +``` + +It's also possible to keep Lightning CSS enabled but disable minification: + +```js +import tailwindcss from '@tailwindcss/postcss' + +export default { + plugins: [ + tailwindcss({ + optimize: { minify: false }, + }), + ], +} +``` + +### Enabling or disabling `url(…)` rewriting + +Our PostCSS plugin can rewrite `url(…)`s for you since it also handles `@import` (no `postcss-import` is needed). This feature is enabled by default. + +In some situations the bundler or framework you're using may provide this feature itself. In this case you can set `transformAssetUrls` to `false` to disable this feature: + +```js +import tailwindcss from '@tailwindcss/postcss' + +export default { + plugins: [ + tailwindcss({ + // Disable `url(…)` rewriting + transformAssetUrls: false, + + // Enable `url(…)` rewriting (the default) + transformAssetUrls: true, + }), + ], +} +``` diff --git a/client/node_modules/@tailwindcss/postcss/dist/index.d.mts b/client/node_modules/@tailwindcss/postcss/dist/index.d.mts new file mode 100644 index 0000000..5d32d11 --- /dev/null +++ b/client/node_modules/@tailwindcss/postcss/dist/index.d.mts @@ -0,0 +1,25 @@ +import { PluginCreator } from 'postcss'; + +type PluginOptions = { + /** + * The base directory to scan for class candidates. + * + * Defaults to the current working directory. + */ + base?: string; + /** + * Optimize and minify the output CSS. + */ + optimize?: boolean | { + minify?: boolean; + }; + /** + * Enable or disable asset URL rewriting. + * + * Defaults to `true`. + */ + transformAssetUrls?: boolean; +}; +declare const _default: PluginCreator; + +export { type PluginOptions, _default as default }; diff --git a/client/node_modules/@tailwindcss/postcss/dist/index.d.ts b/client/node_modules/@tailwindcss/postcss/dist/index.d.ts new file mode 100644 index 0000000..7a0ff00 --- /dev/null +++ b/client/node_modules/@tailwindcss/postcss/dist/index.d.ts @@ -0,0 +1,25 @@ +import { PluginCreator } from 'postcss'; + +type PluginOptions = { + /** + * The base directory to scan for class candidates. + * + * Defaults to the current working directory. + */ + base?: string; + /** + * Optimize and minify the output CSS. + */ + optimize?: boolean | { + minify?: boolean; + }; + /** + * Enable or disable asset URL rewriting. + * + * Defaults to `true`. + */ + transformAssetUrls?: boolean; +}; +declare const _default: PluginCreator; + +export = _default; diff --git a/client/node_modules/@tailwindcss/postcss/dist/index.js b/client/node_modules/@tailwindcss/postcss/dist/index.js new file mode 100644 index 0000000..3baf8bd --- /dev/null +++ b/client/node_modules/@tailwindcss/postcss/dist/index.js @@ -0,0 +1,10 @@ +"use strict";var tt=Object.create;var ke=Object.defineProperty;var rt=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,ot=Object.prototype.hasOwnProperty;var he=(e,r)=>(r=Symbol[e])?r:Symbol.for("Symbol."+e),ve=e=>{throw TypeError(e)};var lt=(e,r,t,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of nt(r))!ot.call(e,o)&&o!==t&&ke(e,o,{get:()=>r[o],enumerable:!(a=rt(r,o))||a.enumerable});return e};var Z=(e,r,t)=>(t=e!=null?tt(it(e)):{},lt(r||!e||!e.__esModule?ke(t,"default",{value:e,enumerable:!0}):t,e));var be=(e,r,t)=>{if(r!=null){typeof r!="object"&&typeof r!="function"&&ve("Object expected");var a,o;t&&(a=r[he("asyncDispose")]),a===void 0&&(a=r[he("dispose")],t&&(o=a)),typeof a!="function"&&ve("Object not disposable"),o&&(a=function(){try{o.call(this)}catch(i){return Promise.reject(i)}}),e.push([t,a,r])}else t&&e.push([t]);return r},we=(e,r,t)=>{var a=typeof SuppressedError=="function"?SuppressedError:function(n,l,u,s){return s=Error(u),s.name="SuppressedError",s.error=n,s.suppressed=l,s},o=n=>r=t?new a(n,r,"An error was suppressed during disposal"):(t=!0,n),i=n=>{for(;n=e.pop();)try{var l=n[1]&&n[1].call(n[2]);if(n[0])return Promise.resolve(l).then(i,u=>(o(u),i()))}catch(u){o(u)}if(t)throw r};return i()};var Ge=Z(require("@alloc/quick-lru")),A=require("@tailwindcss/node"),He=require("@tailwindcss/node/require-cache"),qe=require("@tailwindcss/oxide"),Ze=Z(require("fs")),N=Z(require("path"));function F(e){return{kind:"word",value:e}}function at(e,r){return{kind:"function",value:e,nodes:r}}function st(e){return{kind:"separator",value:e}}function C(e){let r="";for(let t of e)switch(t.kind){case"word":case"separator":{r+=t.value;break}case"function":r+=t.value+"("+C(t.nodes)+")"}return r}var ye=92,ut=41,xe=58,Ae=44,ct=34,Ce=61,Se=62,$e=60,Te=10,ft=40,pt=39,dt=47,Ve=32,Ne=9;function y(e){e=e.replaceAll(`\r +`,` +`);let r=[],t=[],a=null,o="",i;for(let n=0;n0){let s=F(o);a?a.nodes.push(s):r.push(s),o=""}let u=F(e[n]);a?a.nodes.push(u):r.push(u);break}case xe:case Ae:case Ce:case Se:case $e:case Te:case Ve:case Ne:{if(o.length>0){let f=F(o);a?a.nodes.push(f):r.push(f),o=""}let u=n,s=n+1;for(;s0){let s=F(o);u?.nodes.push(s),o=""}t.length>0?a=t[t.length-1]:a=null;break}default:o+=String.fromCharCode(l)}}return o.length>0&&r.push(F(o)),r}var m=class extends Map{constructor(t){super();this.factory=t}factory;get(t){let a=super.get(t);return a===void 0&&(a=this.factory(t,this),this.set(t,a)),a}};var lr=new Uint8Array(256);var Q=new Uint8Array(256);function v(e,r){let t=0,a=[],o=0,i=e.length,n=r.charCodeAt(0);for(let l=0;l0&&u===Q[t-1]&&t--;break}}return a.push(e.slice(o)),a}var ne=(n=>(n[n.Continue=0]="Continue",n[n.Skip=1]="Skip",n[n.Stop=2]="Stop",n[n.Replace=3]="Replace",n[n.ReplaceSkip=4]="ReplaceSkip",n[n.ReplaceStop=5]="ReplaceStop",n))(ne||{}),d={Continue:{kind:0},Skip:{kind:1},Stop:{kind:2},Replace:e=>({kind:3,nodes:Array.isArray(e)?e:[e]}),ReplaceSkip:e=>({kind:4,nodes:Array.isArray(e)?e:[e]}),ReplaceStop:e=>({kind:5,nodes:Array.isArray(e)?e:[e]})};function g(e,r){typeof r=="function"?Ee(e,r):Ee(e,r.enter,r.exit)}function Ee(e,r=()=>d.Continue,t=()=>d.Continue){let a={value:[e,0,null],prev:null},o={parent:null,depth:0,index:0,siblings:e,path(){let i=[],n=a;for(;n;){let l=n.value[2];l&&i.push(l),n=n.prev}return i.reverse(),i}};for(;a!==null;){let i=a.value,n=i[0],l=i[1],u=i[2];if(l>=n.length){a=a.prev,o.depth-=1;continue}if(o.parent=u,o.siblings=n,l>=0){o.index=l;let k=n[l],E=r(k,o)??d.Continue;switch(E.kind){case 0:{k.nodes&&k.nodes.length>0&&(o.depth+=1,a={value:[k.nodes,0,k],prev:a}),i[1]=~l;continue}case 2:return;case 1:{i[1]=~l;continue}case 3:{n.splice(l,1,...E.nodes);continue}case 5:{n.splice(l,1,...E.nodes);return}case 4:{n.splice(l,1,...E.nodes),i[1]+=E.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${ne[E.kind]??`Unknown(${E.kind})`}\` in enter.`)}}let s=~l;o.index=s;let c=n[s],f=t(c,o)??d.Continue;switch(f.kind){case 0:i[1]=s+1;continue;case 2:return;case 3:{n.splice(s,1,...f.nodes),i[1]=s+f.nodes.length;continue}case 5:{n.splice(s,1,...f.nodes);return}case 4:{n.splice(s,1,...f.nodes),i[1]=s+f.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${ne[f.kind]??`Unknown(${f.kind})`}\` in exit.`)}}}var vr=new m(e=>{let r=y(e),t=new Set,a=new Set(["~",">","+","-","*","/"]);return g(r,(o,i)=>{if(o.kind==="word"&&a.has(o.value)){let n=i.index;if(n===-1)return;let l=i.siblings[n-1];if(l?.kind!=="separator"||l.value!==" ")return;let u=i.siblings[n+1];if(u?.kind!=="separator"||u.value!==" ")return;let s=i.siblings[n-2];if(s&&a.has(s.value))return;let c=i.siblings[n+2];if(c&&a.has(c.value))return;t.add(l),t.add(u)}else if(o.kind==="separator"&&o.value.length>0&&o.value.trim()==="")(i.siblings[0]===o||i.siblings[i.siblings.length-1]===o)&&t.add(o);else if(o.kind==="separator"&&o.value.trim()===",")o.value=",";else if(o.kind==="function"&&o.value.startsWith("--")){let n=i.index;if(n<=0)return;let l=i.siblings[n-1];if(l?.kind==="separator"&&l.value===",")return;let u=i.siblings[n-2];return u&&!a.has(u.value)?void 0:d.ReplaceSkip({kind:"function",value:"",nodes:[o]})}}),t.size>0&&g(r,o=>{if(t.has(o))return t.delete(o),d.ReplaceSkip([])}),ie(r),C(r)});var kr=new m(e=>{let r=y(e);return r.length===3&&r[0].kind==="word"&&r[0].value==="&"&&r[1].kind==="separator"&&r[1].value===":"&&r[2].kind==="function"&&r[2].value==="is"?C(r[2].nodes):e});function ie(e){for(let r of e)switch(r.kind){case"function":{if(r.value==="url"||r.value.endsWith("_url")){r.value=W(r.value);break}if(r.value==="var"||r.value.endsWith("_var")||r.value==="theme"||r.value.endsWith("_theme")){r.value=W(r.value);for(let t=0;t{let r=y(e);return r.length===1&&r[0].kind==="function"&&r[0].value==="var"});function gt(e){throw new Error(`Unexpected value: ${e}`)}function W(e){return e.replaceAll("_",String.raw`\_`).replaceAll(" ","_")}var ht=/^(?[-+]?(?:\d*\.)?\d+)(?[a-z]+|%)?$/i,j=new m(e=>{let r=ht.exec(e);if(!r)return null;let t=r.groups?.value;if(t===void 0)return null;let a=Number(t);if(Number.isNaN(a))return null;let o=r.groups?.unit;return o===void 0?[a,null]:[a,o]});var _=/[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?/,Rr=new RegExp(`^${_.source}$`);var Pr=new RegExp(`^${_.source}%$`);var Or=new RegExp(`^${_.source}\\s*/\\s*${_.source}$`);var vt=["cm","mm","Q","in","pc","pt","px","em","ex","ch","rem","lh","rlh","vw","vh","vmin","vmax","vb","vi","svw","svh","lvw","lvh","dvw","dvh","cqw","cqh","cqi","cqb","cqmin","cqmax"],_r=new RegExp(`^${_.source}(${vt.join("|")})$`);var kt=["deg","rad","grad","turn"],Ir=new RegExp(`^${_.source}(${kt.join("|")})$`);var Dr=new RegExp(`^${_.source} +${_.source} +${_.source}$`);function $(e){let r=Number(e);return Number.isInteger(r)&&r>=0&&String(r)===String(e)}function B(e,r){if(r===null)return e;let t=Number(r);return Number.isNaN(t)||(r=`${t*100}%`),r==="100%"?e:`color-mix(in oklab, ${e} ${r}, transparent)`}var yt={"--alpha":xt,"--spacing":At,"--theme":Ct,theme:St};function xt(e,r,t,...a){let[o,i]=v(t,"/").map(n=>n.trim());if(!o||!i)throw new Error(`The --alpha(\u2026) function requires a color and an alpha value, e.g.: \`--alpha(${o||"var(--my-color)"} / ${i||"50%"})\``);if(a.length>0)throw new Error(`The --alpha(\u2026) function only accepts one argument, e.g.: \`--alpha(${o||"var(--my-color)"} / ${i||"50%"})\``);return B(o,i)}function At(e,r,t,...a){if(!t)throw new Error("The --spacing(\u2026) function requires an argument, but received none.");if(a.length>0)throw new Error(`The --spacing(\u2026) function only accepts a single argument, but received ${a.length+1}.`);let o=e.theme.resolve(null,["--spacing"]);if(!o)throw new Error("The --spacing(\u2026) function requires that the `--spacing` theme variable exists, but it was not found.");let i=j.get(t);if(i){if(i[0]===0)return"0";if(i[0]===1)return o}return`calc(${o} * ${t})`}function Ct(e,r,t,...a){if(!t.startsWith("--"))throw new Error("The --theme(\u2026) function can only be used with CSS variables from your theme.");let o=!1;t.endsWith(" inline")&&(o=!0,t=t.slice(0,-7)),r.kind==="at-rule"&&(o=!0);let i=e.resolveThemeValue(t,o);if(!i){if(a.length>0)return a.join(", ");throw new Error(`Could not resolve value for theme function: \`theme(${t})\`. Consider checking if the variable name is correct or provide a fallback value to silence this error.`)}if(a.length===0)return i;let n=a.join(", ");if(n==="initial")return i;if(i==="initial")return n;if(i.startsWith("var(")||i.startsWith("theme(")||i.startsWith("--theme(")){let l=y(i);return Tt(l,n),C(l)}return i}function St(e,r,t,...a){t=$t(t);let o=e.resolveThemeValue(t);if(!o&&a.length>0)return a.join(", ");if(!o)throw new Error(`Could not resolve value for theme function: \`theme(${t})\`. Consider checking if the path is correct or provide a fallback value to silence this error.`);return o}var un=new RegExp(Object.keys(yt).map(e=>`${e}\\(`).join("|"));function $t(e){if(e[0]!=="'"&&e[0]!=='"')return e;let r="",t=e[0];for(let a=1;a{if(t.kind==="function"&&!(t.value!=="var"&&t.value!=="theme"&&t.value!=="--theme"))if(t.nodes.length===1)t.nodes.push({kind:"word",value:`, ${r}`});else{let a=t.nodes[t.nodes.length-1];a.kind==="word"&&a.value==="initial"&&(a.value=r)}})}function z(e,r="top",t="right",a="bottom",o="left"){return _e(`${e}-${r}`,`${e}-${t}`,`${e}-${a}`,`${e}-${o}`)}function _e(e="top",r="right",t="bottom",a="left"){return{1:[[e,0],[r,0],[t,0],[a,0]],2:[[e,0],[r,1],[t,0],[a,1]],3:[[e,0],[r,1],[t,2],[a,1]],4:[[e,0],[r,1],[t,2],[a,3]]}}function T(e,r){return{1:[[e,0],[r,0]],2:[[e,0],[r,1]]}}var $n={inset:_e(),margin:z("margin"),padding:z("padding"),"scroll-margin":z("scroll-margin"),"scroll-padding":z("scroll-padding"),"border-width":z("border","top-width","right-width","bottom-width","left-width"),"border-style":z("border","top-style","right-style","bottom-style","left-style"),"border-color":z("border","top-color","right-color","bottom-color","left-color"),gap:T("row-gap","column-gap"),overflow:T("overflow-x","overflow-y"),"overscroll-behavior":T("overscroll-behavior-x","overscroll-behavior-y")},Tn={"inset-block":T("top","bottom"),"inset-inline":T("left","right"),"margin-block":T("margin-top","margin-bottom"),"margin-inline":T("margin-left","margin-right"),"padding-block":T("padding-top","padding-bottom"),"padding-inline":T("padding-left","padding-right"),"scroll-margin-block":T("scroll-margin-top","scroll-margin-bottom"),"scroll-margin-inline":T("scroll-margin-left","scroll-margin-right"),"scroll-padding-block":T("scroll-padding-top","scroll-padding-bottom"),"scroll-padding-inline":T("scroll-padding-left","scroll-padding-right")};var Pt=1536,oi=Pt/16;function X(e){let r=[0];for(let o=0;o0;){let u=(n|0)>>1,s=i+u;r[s]<=o?(i=s+1,n=n-u-1):n=u}i-=1;let l=o-r[i];return{line:i+1,column:l}}function a({line:o,column:i}){o-=1,o=Math.min(Math.max(o,0),r.length-1);let n=r[o],l=r[o+1]??n;return Math.min(Math.max(n+i,0),l)}return{find:t,findOffset:a}}var Kt=32,Mt=9;var Ft=40;function Ke(e,r=[]){let t=e,a="";for(let o=5;o{if($(e.value))return e.value}),x=M(e=>{if($(e.value))return`${e.value}%`}),U=M(e=>{if($(e.value))return`${e.value}px`}),je=M(e=>{if($(e.value))return`${e.value}ms`}),te=M(e=>{if($(e.value))return`${e.value}deg`}),Gt=M(e=>{if(e.fraction===null)return;let[r,t]=v(e.fraction,"/");if(!(!$(r)||!$(t)))return e.fraction}),We=M(e=>{if($(Number(e.value)))return`repeat(${e.value}, minmax(0, 1fr))`}),Ht={accentColor:({theme:e})=>e("colors"),animation:{none:"none",spin:"spin 1s linear infinite",ping:"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",bounce:"bounce 1s infinite"},aria:{busy:'busy="true"',checked:'checked="true"',disabled:'disabled="true"',expanded:'expanded="true"',hidden:'hidden="true"',pressed:'pressed="true"',readonly:'readonly="true"',required:'required="true"',selected:'selected="true"'},aspectRatio:{auto:"auto",square:"1 / 1",video:"16 / 9",...Gt},backdropBlur:({theme:e})=>e("blur"),backdropBrightness:({theme:e})=>({...e("brightness"),...x}),backdropContrast:({theme:e})=>({...e("contrast"),...x}),backdropGrayscale:({theme:e})=>({...e("grayscale"),...x}),backdropHueRotate:({theme:e})=>({...e("hueRotate"),...te}),backdropInvert:({theme:e})=>({...e("invert"),...x}),backdropOpacity:({theme:e})=>({...e("opacity"),...x}),backdropSaturate:({theme:e})=>({...e("saturate"),...x}),backdropSepia:({theme:e})=>({...e("sepia"),...x}),backgroundColor:({theme:e})=>e("colors"),backgroundImage:{none:"none","gradient-to-t":"linear-gradient(to top, var(--tw-gradient-stops))","gradient-to-tr":"linear-gradient(to top right, var(--tw-gradient-stops))","gradient-to-r":"linear-gradient(to right, var(--tw-gradient-stops))","gradient-to-br":"linear-gradient(to bottom right, var(--tw-gradient-stops))","gradient-to-b":"linear-gradient(to bottom, var(--tw-gradient-stops))","gradient-to-bl":"linear-gradient(to bottom left, var(--tw-gradient-stops))","gradient-to-l":"linear-gradient(to left, var(--tw-gradient-stops))","gradient-to-tl":"linear-gradient(to top left, var(--tw-gradient-stops))"},backgroundOpacity:({theme:e})=>e("opacity"),backgroundPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},backgroundSize:{auto:"auto",cover:"cover",contain:"contain"},blur:{0:"0",none:"",sm:"4px",DEFAULT:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},borderColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),borderOpacity:({theme:e})=>e("opacity"),borderRadius:{none:"0px",sm:"0.125rem",DEFAULT:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},borderSpacing:({theme:e})=>e("spacing"),borderWidth:{DEFAULT:"1px",0:"0px",2:"2px",4:"4px",8:"8px",...U},boxShadow:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",DEFAULT:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)",inner:"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",none:"none"},boxShadowColor:({theme:e})=>e("colors"),brightness:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",200:"2",...x},caretColor:({theme:e})=>e("colors"),colors:()=>({...ue}),columns:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12","3xs":"16rem","2xs":"18rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",...P},container:{},content:{none:"none"},contrast:{0:"0",50:".5",75:".75",100:"1",125:"1.25",150:"1.5",200:"2",...x},cursor:{auto:"auto",default:"default",pointer:"pointer",wait:"wait",text:"text",move:"move",help:"help","not-allowed":"not-allowed",none:"none","context-menu":"context-menu",progress:"progress",cell:"cell",crosshair:"crosshair","vertical-text":"vertical-text",alias:"alias",copy:"copy","no-drop":"no-drop",grab:"grab",grabbing:"grabbing","all-scroll":"all-scroll","col-resize":"col-resize","row-resize":"row-resize","n-resize":"n-resize","e-resize":"e-resize","s-resize":"s-resize","w-resize":"w-resize","ne-resize":"ne-resize","nw-resize":"nw-resize","se-resize":"se-resize","sw-resize":"sw-resize","ew-resize":"ew-resize","ns-resize":"ns-resize","nesw-resize":"nesw-resize","nwse-resize":"nwse-resize","zoom-in":"zoom-in","zoom-out":"zoom-out"},divideColor:({theme:e})=>e("borderColor"),divideOpacity:({theme:e})=>e("borderOpacity"),divideWidth:({theme:e})=>({...e("borderWidth"),...U}),dropShadow:{sm:"0 1px 1px rgb(0 0 0 / 0.05)",DEFAULT:["0 1px 2px rgb(0 0 0 / 0.1)","0 1px 1px rgb(0 0 0 / 0.06)"],md:["0 4px 3px rgb(0 0 0 / 0.07)","0 2px 2px rgb(0 0 0 / 0.06)"],lg:["0 10px 8px rgb(0 0 0 / 0.04)","0 4px 3px rgb(0 0 0 / 0.1)"],xl:["0 20px 13px rgb(0 0 0 / 0.03)","0 8px 5px rgb(0 0 0 / 0.08)"],"2xl":"0 25px 25px rgb(0 0 0 / 0.15)",none:"0 0 #0000"},fill:({theme:e})=>e("colors"),flex:{1:"1 1 0%",auto:"1 1 auto",initial:"0 1 auto",none:"none"},flexBasis:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",...e("spacing")}),flexGrow:{0:"0",DEFAULT:"1",...P},flexShrink:{0:"0",DEFAULT:"1",...P},fontFamily:{sans:["ui-sans-serif","system-ui","sans-serif",'"Apple Color Emoji"','"Segoe UI Emoji"','"Segoe UI Symbol"','"Noto Color Emoji"'],serif:["ui-serif","Georgia","Cambria",'"Times New Roman"',"Times","serif"],mono:["ui-monospace","SFMono-Regular","Menlo","Monaco","Consolas",'"Liberation Mono"','"Courier New"',"monospace"]},fontSize:{xs:["0.75rem",{lineHeight:"1rem"}],sm:["0.875rem",{lineHeight:"1.25rem"}],base:["1rem",{lineHeight:"1.5rem"}],lg:["1.125rem",{lineHeight:"1.75rem"}],xl:["1.25rem",{lineHeight:"1.75rem"}],"2xl":["1.5rem",{lineHeight:"2rem"}],"3xl":["1.875rem",{lineHeight:"2.25rem"}],"4xl":["2.25rem",{lineHeight:"2.5rem"}],"5xl":["3rem",{lineHeight:"1"}],"6xl":["3.75rem",{lineHeight:"1"}],"7xl":["4.5rem",{lineHeight:"1"}],"8xl":["6rem",{lineHeight:"1"}],"9xl":["8rem",{lineHeight:"1"}]},fontWeight:{thin:"100",extralight:"200",light:"300",normal:"400",medium:"500",semibold:"600",bold:"700",extrabold:"800",black:"900"},gap:({theme:e})=>e("spacing"),gradientColorStops:({theme:e})=>e("colors"),gradientColorStopPositions:{"0%":"0%","5%":"5%","10%":"10%","15%":"15%","20%":"20%","25%":"25%","30%":"30%","35%":"35%","40%":"40%","45%":"45%","50%":"50%","55%":"55%","60%":"60%","65%":"65%","70%":"70%","75%":"75%","80%":"80%","85%":"85%","90%":"90%","95%":"95%","100%":"100%",...x},grayscale:{0:"0",DEFAULT:"100%",...x},gridAutoColumns:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridAutoRows:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridColumn:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridColumnEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...P},gridColumnStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...P},gridRow:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridRowEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...P},gridRowStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...P},gridTemplateColumns:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...We},gridTemplateRows:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...We},height:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),hueRotate:{0:"0deg",15:"15deg",30:"30deg",60:"60deg",90:"90deg",180:"180deg",...te},inset:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),invert:{0:"0",DEFAULT:"100%",...x},keyframes:{spin:{to:{transform:"rotate(360deg)"}},ping:{"75%, 100%":{transform:"scale(2)",opacity:"0"}},pulse:{"50%":{opacity:".5"}},bounce:{"0%, 100%":{transform:"translateY(-25%)",animationTimingFunction:"cubic-bezier(0.8,0,1,1)"},"50%":{transform:"none",animationTimingFunction:"cubic-bezier(0,0,0.2,1)"}}},letterSpacing:{tighter:"-0.05em",tight:"-0.025em",normal:"0em",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeight:{none:"1",tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625",loose:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},listStyleType:{none:"none",disc:"disc",decimal:"decimal"},listStyleImage:{none:"none"},margin:({theme:e})=>({auto:"auto",...e("spacing")}),lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",...P},maxHeight:({theme:e})=>({none:"none",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),maxWidth:({theme:e})=>({none:"none",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",prose:"65ch",...e("spacing")}),minHeight:({theme:e})=>({full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),minWidth:({theme:e})=>({full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),objectPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},opacity:{0:"0",5:"0.05",10:"0.1",15:"0.15",20:"0.2",25:"0.25",30:"0.3",35:"0.35",40:"0.4",45:"0.45",50:"0.5",55:"0.55",60:"0.6",65:"0.65",70:"0.7",75:"0.75",80:"0.8",85:"0.85",90:"0.9",95:"0.95",100:"1",...x},order:{first:"-9999",last:"9999",none:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",...P},outlineColor:({theme:e})=>e("colors"),outlineOffset:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},outlineWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},padding:({theme:e})=>e("spacing"),placeholderColor:({theme:e})=>e("colors"),placeholderOpacity:({theme:e})=>e("opacity"),ringColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),ringOffsetColor:({theme:e})=>e("colors"),ringOffsetWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},ringOpacity:({theme:e})=>({DEFAULT:"0.5",...e("opacity")}),ringWidth:{DEFAULT:"3px",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},rotate:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",45:"45deg",90:"90deg",180:"180deg",...te},saturate:{0:"0",50:".5",100:"1",150:"1.5",200:"2",...x},scale:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",...x},screens:{sm:"40rem",md:"48rem",lg:"64rem",xl:"80rem","2xl":"96rem"},scrollMargin:({theme:e})=>e("spacing"),scrollPadding:({theme:e})=>e("spacing"),sepia:{0:"0",DEFAULT:"100%",...x},skew:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",...te},space:({theme:e})=>e("spacing"),spacing:{px:"1px",0:"0px",.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},stroke:({theme:e})=>({none:"none",...e("colors")}),strokeWidth:{0:"0",1:"1",2:"2",...P},supports:{},data:{},textColor:({theme:e})=>e("colors"),textDecorationColor:({theme:e})=>e("colors"),textDecorationThickness:{auto:"auto","from-font":"from-font",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},textIndent:({theme:e})=>e("spacing"),textOpacity:({theme:e})=>e("opacity"),textUnderlineOffset:{auto:"auto",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},transformOrigin:{center:"center",top:"top","top-right":"top right",right:"right","bottom-right":"bottom right",bottom:"bottom","bottom-left":"bottom left",left:"left","top-left":"top left"},transitionDelay:{0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...je},transitionDuration:{DEFAULT:"150ms",0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...je},transitionProperty:{none:"none",all:"all",DEFAULT:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter",colors:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke",opacity:"opacity",shadow:"box-shadow",transform:"transform"},transitionTimingFunction:{DEFAULT:"cubic-bezier(0.4, 0, 0.2, 1)",linear:"linear",in:"cubic-bezier(0.4, 0, 1, 1)",out:"cubic-bezier(0, 0, 0.2, 1)","in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},translate:({theme:e})=>({"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),size:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),width:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",screen:"100vw",svw:"100svw",lvw:"100lvw",dvw:"100dvw",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),willChange:{auto:"auto",scroll:"scroll-position",contents:"contents",transform:"transform"},zIndex:{auto:"auto",0:"0",10:"10",20:"20",30:"30",40:"40",50:"50",...P}};var Zt=64;function L(e,r=[]){return{kind:"rule",selector:e,nodes:r}}function S(e,r="",t=[]){return{kind:"at-rule",name:e,params:r,nodes:t}}function I(e,r=[]){return e.charCodeAt(0)===Zt?Ke(e,r):L(e,r)}function R(e,r,t=!1){return{kind:"declaration",property:e,value:r,important:t}}function ee(e){return{kind:"comment",value:e}}function K(e,r){let t=0,a={file:null,code:""};function o(n,l=0){let u="",s=" ".repeat(l);if(n.kind==="declaration"){if(u+=`${s}${n.property}: ${n.value}${n.important?" !important":""}; +`,r){t+=s.length;let c=t;t+=n.property.length,t+=2,t+=n.value?.length??0,n.important&&(t+=11);let f=t;t+=2,n.dst=[a,c,f]}}else if(n.kind==="rule"){if(u+=`${s}${n.selector} { +`,r){t+=s.length;let c=t;t+=n.selector.length,t+=1;let f=t;n.dst=[a,c,f],t+=2}for(let c of n.nodes)u+=o(c,l+1);u+=`${s}} +`,r&&(t+=s.length,t+=2)}else if(n.kind==="at-rule"){if(n.nodes.length===0){let c=`${s}${n.name} ${n.params}; +`;if(r){t+=s.length;let f=t;t+=n.name.length,t+=1,t+=n.params.length;let k=t;t+=2,n.dst=[a,f,k]}return c}if(u+=`${s}${n.name}${n.params?` ${n.params} `:" "}{ +`,r){t+=s.length;let c=t;t+=n.name.length,n.params&&(t+=1,t+=n.params.length),t+=1;let f=t;n.dst=[a,c,f],t+=2}for(let c of n.nodes)u+=o(c,l+1);u+=`${s}} +`,r&&(t+=s.length,t+=2)}else if(n.kind==="comment"){if(u+=`${s}/*${n.value}*/ +`,r){t+=s.length;let c=t;t+=2+n.value.length+2;let f=t;n.dst=[a,c,f],t+=1}}else if(n.kind==="context"||n.kind==="at-root")return"";return u}let i="";for(let n of e)i+=o(n,0);return a.code=i,i}var Qt=33;function Be(e,r,t){let a=new m(s=>new e.Input(s.code,{map:t?.input.map,from:s.file??void 0})),o=new m(s=>X(s.code)),i=e.root();i.source=t;function n(s){if(!s||!s[0])return;let c=o.get(s[0]),f=c.find(s[1]),k=c.find(s[2]);return{input:a.get(s[0]),start:{line:f.line,column:f.column+1,offset:s[1]},end:{line:k.line,column:k.column+1,offset:s[2]}}}function l(s,c){let f=n(c);f?s.source=f:delete s.source}function u(s,c){if(s.kind==="declaration"){let f=e.decl({prop:s.property,value:s.value??"",important:s.important});l(f,s.src),c.append(f)}else if(s.kind==="rule"){let f=e.rule({selector:s.selector});l(f,s.src),f.raws.semicolon=!0,c.append(f);for(let k of s.nodes)u(k,f)}else if(s.kind==="at-rule"){let f=e.atRule({name:s.name.slice(1),params:s.params});l(f,s.src),f.raws.semicolon=!0,c.append(f);for(let k of s.nodes)u(k,f)}else if(s.kind==="comment"){let f=e.comment({text:s.value});f.raws.left="",f.raws.right="",l(f,s.src),c.append(f)}else s.kind==="at-root"||s.kind}for(let s of r)u(s,i);return i}function Ye(e){let r=new m(i=>({file:i.file??i.id??null,code:i.css}));function t(i){let n=i.source;if(!n)return;let l=n.input;if(l&&n.start!==void 0&&n.end!==void 0)return[r.get(l),n.start.offset,n.end.offset]}function a(i,n){if(i.type==="decl"){let l=R(i.prop,i.value,i.important);l.src=t(i),n.push(l)}else if(i.type==="rule"){let l=I(i.selector);l.src=t(i),i.each(u=>a(u,l.nodes)),n.push(l)}else if(i.type==="atrule"){let l=S(`@${i.name}`,i.params);l.src=t(i),i.each(u=>a(u,l.nodes)),n.push(l)}else if(i.type==="comment"){if(i.text.charCodeAt(0)!==Qt)return;let l=ee(i.text);l.src=t(i),n.push(l)}}let o=[];return e.each(i=>a(i,o)),o}var pe=require("@tailwindcss/node"),H=Z(require("path")),ce="'",fe='"';function de(){let e=new WeakSet;function r(t){let a=t.root().source?.input.file;if(!a)return;let o=t.source?.input.file;if(!o||e.has(t))return;let i=t.params[0],n=i[0]===fe&&i[i.length-1]===fe?fe:i[0]===ce&&i[i.length-1]===ce?ce:null;if(!n)return;let l=t.params.slice(1,-1),u="";if(l.startsWith("!")&&(l=l.slice(1),u="!"),!l.startsWith("./")&&!l.startsWith("../"))return;let s=H.default.posix.join((0,pe.normalizePath)(H.default.dirname(o)),l),c=H.default.posix.dirname((0,pe.normalizePath)(a)),f=H.default.posix.relative(c,s);f.startsWith(".")||(f="./"+f),t.params=n+u+f+n,e.add(t)}return{postcssPlugin:"tailwindcss-postcss-fix-relative-paths",Once(t){t.walkAtRules(/source|plugin|config/,r)}}}var p=A.env.DEBUG,me=new Ge.default({maxSize:50});function Jt(e,r,t){let a=`${r}:${t.base??""}:${JSON.stringify(t.optimize)}`;if(me.has(a))return me.get(a);let o={mtimes:new Map,compiler:null,scanner:null,tailwindCssAst:[],cachedPostCssAst:e.root(),optimizedPostCssAst:e.root(),fullRebuildPaths:[]};return me.set(a,o),o}function Xt(e={}){let r=e.base??process.cwd(),t=e.optimize??process.env.NODE_ENV==="production",a=e.transformAssetUrls??!0;return{postcssPlugin:"@tailwindcss/postcss",plugins:[de(),{postcssPlugin:"tailwindcss",async Once(o,{result:i,postcss:n}){var ge=[];try{let l=be(ge,new A.Instrumentation);let u=i.opts.from??"";let s=u.endsWith(".module.css");p&&l.start(`[@tailwindcss/postcss] ${(0,N.relative)(r,u)}`);{p&&l.start("Quick bail check");let w=!0;if(o.walkAtRules(h=>{if(h.name==="import"||h.name==="reference"||h.name==="theme"||h.name==="variant"||h.name==="config"||h.name==="plugin"||h.name==="apply"||h.name==="tailwind")return w=!1,!1}),w)return;p&&l.end("Quick bail check")}let c=Jt(n,u,e);let f=u?N.default.dirname(N.default.resolve(u)):r;let k=c.compiler===null;async function E(){p&&l.start("Setup compiler"),c.fullRebuildPaths.length>0&&!k&&(0,He.clearRequireCache)(c.fullRebuildPaths),c.fullRebuildPaths=[],p&&l.start("PostCSS AST -> Tailwind CSS AST");let w=Ye(o);p&&l.end("PostCSS AST -> Tailwind CSS AST"),p&&l.start("Create compiler");let h=await(0,A.compileAst)(w,{from:i.opts.from,base:f,shouldRewriteUrls:a,onDependency:re=>c.fullRebuildPaths.push(re),polyfills:s?A.Polyfills.All^A.Polyfills.AtProperty:A.Polyfills.All});return p&&l.end("Create compiler"),p&&l.end("Setup compiler"),h}try{if(c.compiler??=E(),(await c.compiler).features===A.Features.None)return;let w="incremental";p&&l.start("Register full rebuild paths");{for(let b of c.fullRebuildPaths)i.messages.push({type:"dependency",plugin:"@tailwindcss/postcss",file:N.default.resolve(b),parent:i.opts.from});let D=i.messages.flatMap(b=>b.type!=="dependency"?[]:b.file);D.push(u);for(let b of D){let O=Ze.default.statSync(b,{throwIfNoEntry:!1})?.mtimeMs??null;if(O===null){b===u&&(w="full");continue}c.mtimes.get(b)!==O&&(w="full",c.mtimes.set(b,O))}}p&&l.end("Register full rebuild paths"),w==="full"&&!k&&(c.compiler=E());let h=await c.compiler;if(c.scanner===null||w==="full"){p&&l.start("Setup scanner");let D=(h.root==="none"?[]:h.root===null?[{base:r,pattern:"**/*",negated:!1}]:[{...h.root,negated:!1}]).concat(h.sources);c.scanner=new qe.Scanner({sources:D}),p&&l.end("Setup scanner")}p&&l.start("Scan for candidates");let re=h.features&A.Features.Utilities?c.scanner.scan():[];if(p&&l.end("Scan for candidates"),h.features&A.Features.Utilities){p&&l.start("Register dependency messages");let D=N.default.resolve(r,u);for(let b of c.scanner.files){let O=N.default.resolve(b);O!==D&&i.messages.push({type:"dependency",plugin:"@tailwindcss/postcss",file:O,parent:i.opts.from})}for(let{base:b,pattern:O}of c.scanner.globs)O==="*"&&r===b||(O===""?i.messages.push({type:"dependency",plugin:"@tailwindcss/postcss",file:N.default.resolve(b),parent:i.opts.from}):i.messages.push({type:"dir-dependency",plugin:"@tailwindcss/postcss",dir:N.default.resolve(b),glob:O,parent:i.opts.from}));p&&l.end("Register dependency messages")}p&&l.start("Build utilities");let q=h.build(re);if(p&&l.end("Build utilities"),c.tailwindCssAst!==q)if(t){p&&l.start("Optimization"),p&&l.start("AST -> CSS");let D=K(q);p&&l.end("AST -> CSS"),p&&l.start("Lightning CSS");let b=(0,A.optimize)(D,{minify:typeof t=="object"?t.minify:!0});p&&l.end("Lightning CSS"),p&&l.start("CSS -> PostCSS AST"),c.optimizedPostCssAst=n.parse(b.code,i.opts),p&&l.end("CSS -> PostCSS AST"),p&&l.end("Optimization")}else p&&l.start("Transform Tailwind CSS AST into PostCSS AST"),c.cachedPostCssAst=Be(n,q,o.source),p&&l.end("Transform Tailwind CSS AST into PostCSS AST");c.tailwindCssAst=q,p&&l.start("Update PostCSS AST"),o.removeAll(),o.append(t?c.optimizedPostCssAst.clone().nodes:c.cachedPostCssAst.clone().nodes),o.raws.indent=" ",p&&l.end("Update PostCSS AST"),p&&l.end(`[@tailwindcss/postcss] ${(0,N.relative)(r,u)}`)}catch(w){c.compiler=null;for(let h of c.fullRebuildPaths)i.messages.push({type:"dependency",plugin:"@tailwindcss/postcss",file:N.default.resolve(h),parent:i.opts.from});throw console.error(w),w&&typeof w=="object"&&"message"in w?o.error(`${w.message}`):o.error(`${w}`)}}catch(Je){var Xe=Je,et=!0}finally{we(ge,Xe,et)}}}]}}var Qe=Object.assign(Xt,{postcss:!0});module.exports=Qe; diff --git a/client/node_modules/@tailwindcss/postcss/dist/index.mjs b/client/node_modules/@tailwindcss/postcss/dist/index.mjs new file mode 100644 index 0000000..ebc2dc9 --- /dev/null +++ b/client/node_modules/@tailwindcss/postcss/dist/index.mjs @@ -0,0 +1,10 @@ +var ge=(e,r)=>(r=Symbol[e])?r:Symbol.for("Symbol."+e),he=e=>{throw TypeError(e)};var ve=(e,r,t)=>{if(r!=null){typeof r!="object"&&typeof r!="function"&&he("Object expected");var a,o;t&&(a=r[ge("asyncDispose")]),a===void 0&&(a=r[ge("dispose")],t&&(o=a)),typeof a!="function"&&he("Object not disposable"),o&&(a=function(){try{o.call(this)}catch(i){return Promise.reject(i)}}),e.push([t,a,r])}else t&&e.push([t]);return r},ke=(e,r,t)=>{var a=typeof SuppressedError=="function"?SuppressedError:function(n,l,u,s){return s=Error(u),s.name="SuppressedError",s.error=n,s.suppressed=l,s},o=n=>r=t?new a(n,r,"An error was suppressed during disposal"):(t=!0,n),i=n=>{for(;n=e.pop();)try{var l=n[1]&&n[1].call(n[2]);if(n[0])return Promise.resolve(l).then(i,u=>(o(u),i()))}catch(u){o(u)}if(t)throw r};return i()};import Mt from"@alloc/quick-lru";import{compileAst as Ft,env as jt,Features as fe,Instrumentation as Wt,optimize as Bt,Polyfills as pe}from"@tailwindcss/node";import{clearRequireCache as Yt}from"@tailwindcss/node/require-cache";import{Scanner as Gt}from"@tailwindcss/oxide";import Ht from"fs";import D,{relative as Ye}from"path";function M(e){return{kind:"word",value:e}}function Ze(e,r){return{kind:"function",value:e,nodes:r}}function Qe(e){return{kind:"separator",value:e}}function A(e){let r="";for(let t of e)switch(t.kind){case"word":case"separator":{r+=t.value;break}case"function":r+=t.value+"("+A(t.nodes)+")"}return r}var be=92,Je=41,we=58,ye=44,Xe=34,xe=61,Ae=62,Ce=60,Se=10,et=40,tt=39,rt=47,$e=32,Te=9;function y(e){e=e.replaceAll(`\r +`,` +`);let r=[],t=[],a=null,o="",i;for(let n=0;n0){let s=M(o);a?a.nodes.push(s):r.push(s),o=""}let u=M(e[n]);a?a.nodes.push(u):r.push(u);break}case we:case ye:case xe:case Ae:case Ce:case Se:case $e:case Te:{if(o.length>0){let f=M(o);a?a.nodes.push(f):r.push(f),o=""}let u=n,s=n+1;for(;s0){let s=M(o);u?.nodes.push(s),o=""}t.length>0?a=t[t.length-1]:a=null;break}default:o+=String.fromCharCode(l)}}return o.length>0&&r.push(M(o)),r}var m=class extends Map{constructor(t){super();this.factory=t}factory;get(t){let a=super.get(t);return a===void 0&&(a=this.factory(t,this),this.set(t,a)),a}};var nr=new Uint8Array(256);var H=new Uint8Array(256);function v(e,r){let t=0,a=[],o=0,i=e.length,n=r.charCodeAt(0);for(let l=0;l0&&u===H[t-1]&&t--;break}}return a.push(e.slice(o)),a}var te=(n=>(n[n.Continue=0]="Continue",n[n.Skip=1]="Skip",n[n.Stop=2]="Stop",n[n.Replace=3]="Replace",n[n.ReplaceSkip=4]="ReplaceSkip",n[n.ReplaceStop=5]="ReplaceStop",n))(te||{}),d={Continue:{kind:0},Skip:{kind:1},Stop:{kind:2},Replace:e=>({kind:3,nodes:Array.isArray(e)?e:[e]}),ReplaceSkip:e=>({kind:4,nodes:Array.isArray(e)?e:[e]}),ReplaceStop:e=>({kind:5,nodes:Array.isArray(e)?e:[e]})};function g(e,r){typeof r=="function"?Ve(e,r):Ve(e,r.enter,r.exit)}function Ve(e,r=()=>d.Continue,t=()=>d.Continue){let a={value:[e,0,null],prev:null},o={parent:null,depth:0,index:0,siblings:e,path(){let i=[],n=a;for(;n;){let l=n.value[2];l&&i.push(l),n=n.prev}return i.reverse(),i}};for(;a!==null;){let i=a.value,n=i[0],l=i[1],u=i[2];if(l>=n.length){a=a.prev,o.depth-=1;continue}if(o.parent=u,o.siblings=n,l>=0){o.index=l;let k=n[l],V=r(k,o)??d.Continue;switch(V.kind){case 0:{k.nodes&&k.nodes.length>0&&(o.depth+=1,a={value:[k.nodes,0,k],prev:a}),i[1]=~l;continue}case 2:return;case 1:{i[1]=~l;continue}case 3:{n.splice(l,1,...V.nodes);continue}case 5:{n.splice(l,1,...V.nodes);return}case 4:{n.splice(l,1,...V.nodes),i[1]+=V.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${te[V.kind]??`Unknown(${V.kind})`}\` in enter.`)}}let s=~l;o.index=s;let c=n[s],f=t(c,o)??d.Continue;switch(f.kind){case 0:i[1]=s+1;continue;case 2:return;case 3:{n.splice(s,1,...f.nodes),i[1]=s+f.nodes.length;continue}case 5:{n.splice(s,1,...f.nodes);return}case 4:{n.splice(s,1,...f.nodes),i[1]=s+f.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${te[f.kind]??`Unknown(${f.kind})`}\` in exit.`)}}}var mr=new m(e=>{let r=y(e),t=new Set,a=new Set(["~",">","+","-","*","/"]);return g(r,(o,i)=>{if(o.kind==="word"&&a.has(o.value)){let n=i.index;if(n===-1)return;let l=i.siblings[n-1];if(l?.kind!=="separator"||l.value!==" ")return;let u=i.siblings[n+1];if(u?.kind!=="separator"||u.value!==" ")return;let s=i.siblings[n-2];if(s&&a.has(s.value))return;let c=i.siblings[n+2];if(c&&a.has(c.value))return;t.add(l),t.add(u)}else if(o.kind==="separator"&&o.value.length>0&&o.value.trim()==="")(i.siblings[0]===o||i.siblings[i.siblings.length-1]===o)&&t.add(o);else if(o.kind==="separator"&&o.value.trim()===",")o.value=",";else if(o.kind==="function"&&o.value.startsWith("--")){let n=i.index;if(n<=0)return;let l=i.siblings[n-1];if(l?.kind==="separator"&&l.value===",")return;let u=i.siblings[n-2];return u&&!a.has(u.value)?void 0:d.ReplaceSkip({kind:"function",value:"",nodes:[o]})}}),t.size>0&&g(r,o=>{if(t.has(o))return t.delete(o),d.ReplaceSkip([])}),re(r),A(r)});var gr=new m(e=>{let r=y(e);return r.length===3&&r[0].kind==="word"&&r[0].value==="&"&&r[1].kind==="separator"&&r[1].value===":"&&r[2].kind==="function"&&r[2].value==="is"?A(r[2].nodes):e});function re(e){for(let r of e)switch(r.kind){case"function":{if(r.value==="url"||r.value.endsWith("_url")){r.value=j(r.value);break}if(r.value==="var"||r.value.endsWith("_var")||r.value==="theme"||r.value.endsWith("_theme")){r.value=j(r.value);for(let t=0;t{let r=y(e);return r.length===1&&r[0].kind==="function"&&r[0].value==="var"});function it(e){throw new Error(`Unexpected value: ${e}`)}function j(e){return e.replaceAll("_",String.raw`\_`).replaceAll(" ","_")}var ot=/^(?[-+]?(?:\d*\.)?\d+)(?[a-z]+|%)?$/i,F=new m(e=>{let r=ot.exec(e);if(!r)return null;let t=r.groups?.value;if(t===void 0)return null;let a=Number(t);if(Number.isNaN(a))return null;let o=r.groups?.unit;return o===void 0?[a,null]:[a,o]});var P=/[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?/,Vr=new RegExp(`^${P.source}$`);var Nr=new RegExp(`^${P.source}%$`);var Er=new RegExp(`^${P.source}\\s*/\\s*${P.source}$`);var lt=["cm","mm","Q","in","pc","pt","px","em","ex","ch","rem","lh","rlh","vw","vh","vmin","vmax","vb","vi","svw","svh","lvw","lvh","dvw","dvh","cqw","cqh","cqi","cqb","cqmin","cqmax"],Rr=new RegExp(`^${P.source}(${lt.join("|")})$`);var at=["deg","rad","grad","turn"],Pr=new RegExp(`^${P.source}(${at.join("|")})$`);var Or=new RegExp(`^${P.source} +${P.source} +${P.source}$`);function S(e){let r=Number(e);return Number.isInteger(r)&&r>=0&&String(r)===String(e)}function W(e,r){if(r===null)return e;let t=Number(r);return Number.isNaN(t)||(r=`${t*100}%`),r==="100%"?e:`color-mix(in oklab, ${e} ${r}, transparent)`}var ct={"--alpha":ft,"--spacing":pt,"--theme":dt,theme:mt};function ft(e,r,t,...a){let[o,i]=v(t,"/").map(n=>n.trim());if(!o||!i)throw new Error(`The --alpha(\u2026) function requires a color and an alpha value, e.g.: \`--alpha(${o||"var(--my-color)"} / ${i||"50%"})\``);if(a.length>0)throw new Error(`The --alpha(\u2026) function only accepts one argument, e.g.: \`--alpha(${o||"var(--my-color)"} / ${i||"50%"})\``);return W(o,i)}function pt(e,r,t,...a){if(!t)throw new Error("The --spacing(\u2026) function requires an argument, but received none.");if(a.length>0)throw new Error(`The --spacing(\u2026) function only accepts a single argument, but received ${a.length+1}.`);let o=e.theme.resolve(null,["--spacing"]);if(!o)throw new Error("The --spacing(\u2026) function requires that the `--spacing` theme variable exists, but it was not found.");let i=F.get(t);if(i){if(i[0]===0)return"0";if(i[0]===1)return o}return`calc(${o} * ${t})`}function dt(e,r,t,...a){if(!t.startsWith("--"))throw new Error("The --theme(\u2026) function can only be used with CSS variables from your theme.");let o=!1;t.endsWith(" inline")&&(o=!0,t=t.slice(0,-7)),r.kind==="at-rule"&&(o=!0);let i=e.resolveThemeValue(t,o);if(!i){if(a.length>0)return a.join(", ");throw new Error(`Could not resolve value for theme function: \`theme(${t})\`. Consider checking if the variable name is correct or provide a fallback value to silence this error.`)}if(a.length===0)return i;let n=a.join(", ");if(n==="initial")return i;if(i==="initial")return n;if(i.startsWith("var(")||i.startsWith("theme(")||i.startsWith("--theme(")){let l=y(i);return ht(l,n),A(l)}return i}function mt(e,r,t,...a){t=gt(t);let o=e.resolveThemeValue(t);if(!o&&a.length>0)return a.join(", ");if(!o)throw new Error(`Could not resolve value for theme function: \`theme(${t})\`. Consider checking if the path is correct or provide a fallback value to silence this error.`);return o}var ln=new RegExp(Object.keys(ct).map(e=>`${e}\\(`).join("|"));function gt(e){if(e[0]!=="'"&&e[0]!=='"')return e;let r="",t=e[0];for(let a=1;a{if(t.kind==="function"&&!(t.value!=="var"&&t.value!=="theme"&&t.value!=="--theme"))if(t.nodes.length===1)t.nodes.push({kind:"word",value:`, ${r}`});else{let a=t.nodes[t.nodes.length-1];a.kind==="word"&&a.value==="initial"&&(a.value=r)}})}function L(e,r="top",t="right",a="bottom",o="left"){return Pe(`${e}-${r}`,`${e}-${t}`,`${e}-${a}`,`${e}-${o}`)}function Pe(e="top",r="right",t="bottom",a="left"){return{1:[[e,0],[r,0],[t,0],[a,0]],2:[[e,0],[r,1],[t,0],[a,1]],3:[[e,0],[r,1],[t,2],[a,1]],4:[[e,0],[r,1],[t,2],[a,3]]}}function $(e,r){return{1:[[e,0],[r,0]],2:[[e,0],[r,1]]}}var An={inset:Pe(),margin:L("margin"),padding:L("padding"),"scroll-margin":L("scroll-margin"),"scroll-padding":L("scroll-padding"),"border-width":L("border","top-width","right-width","bottom-width","left-width"),"border-style":L("border","top-style","right-style","bottom-style","left-style"),"border-color":L("border","top-color","right-color","bottom-color","left-color"),gap:$("row-gap","column-gap"),overflow:$("overflow-x","overflow-y"),"overscroll-behavior":$("overscroll-behavior-x","overscroll-behavior-y")},Cn={"inset-block":$("top","bottom"),"inset-inline":$("left","right"),"margin-block":$("margin-top","margin-bottom"),"margin-inline":$("margin-left","margin-right"),"padding-block":$("padding-top","padding-bottom"),"padding-inline":$("padding-left","padding-right"),"scroll-margin-block":$("scroll-margin-top","scroll-margin-bottom"),"scroll-margin-inline":$("scroll-margin-left","scroll-margin-right"),"scroll-padding-block":$("scroll-padding-top","scroll-padding-bottom"),"scroll-padding-inline":$("scroll-padding-left","scroll-padding-right")};var yt=1536,ri=yt/16;function Z(e){let r=[0];for(let o=0;o0;){let u=(n|0)>>1,s=i+u;r[s]<=o?(i=s+1,n=n-u-1):n=u}i-=1;let l=o-r[i];return{line:i+1,column:l}}function a({line:o,column:i}){o-=1,o=Math.min(Math.max(o,0),r.length-1);let n=r[o],l=r[o+1]??n;return Math.min(Math.max(n+i,0),l)}return{find:t,findOffset:a}}var Nt=32,Et=9;var Rt=40;function Le(e,r=[]){let t=e,a="";for(let o=5;o{if(S(e.value))return e.value}),x=K(e=>{if(S(e.value))return`${e.value}%`}),I=K(e=>{if(S(e.value))return`${e.value}px`}),Me=K(e=>{if(S(e.value))return`${e.value}ms`}),J=K(e=>{if(S(e.value))return`${e.value}deg`}),Dt=K(e=>{if(e.fraction===null)return;let[r,t]=v(e.fraction,"/");if(!(!S(r)||!S(t)))return e.fraction}),Fe=K(e=>{if(S(Number(e.value)))return`repeat(${e.value}, minmax(0, 1fr))`}),Ut={accentColor:({theme:e})=>e("colors"),animation:{none:"none",spin:"spin 1s linear infinite",ping:"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",bounce:"bounce 1s infinite"},aria:{busy:'busy="true"',checked:'checked="true"',disabled:'disabled="true"',expanded:'expanded="true"',hidden:'hidden="true"',pressed:'pressed="true"',readonly:'readonly="true"',required:'required="true"',selected:'selected="true"'},aspectRatio:{auto:"auto",square:"1 / 1",video:"16 / 9",...Dt},backdropBlur:({theme:e})=>e("blur"),backdropBrightness:({theme:e})=>({...e("brightness"),...x}),backdropContrast:({theme:e})=>({...e("contrast"),...x}),backdropGrayscale:({theme:e})=>({...e("grayscale"),...x}),backdropHueRotate:({theme:e})=>({...e("hueRotate"),...J}),backdropInvert:({theme:e})=>({...e("invert"),...x}),backdropOpacity:({theme:e})=>({...e("opacity"),...x}),backdropSaturate:({theme:e})=>({...e("saturate"),...x}),backdropSepia:({theme:e})=>({...e("sepia"),...x}),backgroundColor:({theme:e})=>e("colors"),backgroundImage:{none:"none","gradient-to-t":"linear-gradient(to top, var(--tw-gradient-stops))","gradient-to-tr":"linear-gradient(to top right, var(--tw-gradient-stops))","gradient-to-r":"linear-gradient(to right, var(--tw-gradient-stops))","gradient-to-br":"linear-gradient(to bottom right, var(--tw-gradient-stops))","gradient-to-b":"linear-gradient(to bottom, var(--tw-gradient-stops))","gradient-to-bl":"linear-gradient(to bottom left, var(--tw-gradient-stops))","gradient-to-l":"linear-gradient(to left, var(--tw-gradient-stops))","gradient-to-tl":"linear-gradient(to top left, var(--tw-gradient-stops))"},backgroundOpacity:({theme:e})=>e("opacity"),backgroundPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},backgroundSize:{auto:"auto",cover:"cover",contain:"contain"},blur:{0:"0",none:"",sm:"4px",DEFAULT:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},borderColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),borderOpacity:({theme:e})=>e("opacity"),borderRadius:{none:"0px",sm:"0.125rem",DEFAULT:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},borderSpacing:({theme:e})=>e("spacing"),borderWidth:{DEFAULT:"1px",0:"0px",2:"2px",4:"4px",8:"8px",...I},boxShadow:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",DEFAULT:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)",inner:"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",none:"none"},boxShadowColor:({theme:e})=>e("colors"),brightness:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",200:"2",...x},caretColor:({theme:e})=>e("colors"),colors:()=>({...ae}),columns:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12","3xs":"16rem","2xs":"18rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",...E},container:{},content:{none:"none"},contrast:{0:"0",50:".5",75:".75",100:"1",125:"1.25",150:"1.5",200:"2",...x},cursor:{auto:"auto",default:"default",pointer:"pointer",wait:"wait",text:"text",move:"move",help:"help","not-allowed":"not-allowed",none:"none","context-menu":"context-menu",progress:"progress",cell:"cell",crosshair:"crosshair","vertical-text":"vertical-text",alias:"alias",copy:"copy","no-drop":"no-drop",grab:"grab",grabbing:"grabbing","all-scroll":"all-scroll","col-resize":"col-resize","row-resize":"row-resize","n-resize":"n-resize","e-resize":"e-resize","s-resize":"s-resize","w-resize":"w-resize","ne-resize":"ne-resize","nw-resize":"nw-resize","se-resize":"se-resize","sw-resize":"sw-resize","ew-resize":"ew-resize","ns-resize":"ns-resize","nesw-resize":"nesw-resize","nwse-resize":"nwse-resize","zoom-in":"zoom-in","zoom-out":"zoom-out"},divideColor:({theme:e})=>e("borderColor"),divideOpacity:({theme:e})=>e("borderOpacity"),divideWidth:({theme:e})=>({...e("borderWidth"),...I}),dropShadow:{sm:"0 1px 1px rgb(0 0 0 / 0.05)",DEFAULT:["0 1px 2px rgb(0 0 0 / 0.1)","0 1px 1px rgb(0 0 0 / 0.06)"],md:["0 4px 3px rgb(0 0 0 / 0.07)","0 2px 2px rgb(0 0 0 / 0.06)"],lg:["0 10px 8px rgb(0 0 0 / 0.04)","0 4px 3px rgb(0 0 0 / 0.1)"],xl:["0 20px 13px rgb(0 0 0 / 0.03)","0 8px 5px rgb(0 0 0 / 0.08)"],"2xl":"0 25px 25px rgb(0 0 0 / 0.15)",none:"0 0 #0000"},fill:({theme:e})=>e("colors"),flex:{1:"1 1 0%",auto:"1 1 auto",initial:"0 1 auto",none:"none"},flexBasis:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",...e("spacing")}),flexGrow:{0:"0",DEFAULT:"1",...E},flexShrink:{0:"0",DEFAULT:"1",...E},fontFamily:{sans:["ui-sans-serif","system-ui","sans-serif",'"Apple Color Emoji"','"Segoe UI Emoji"','"Segoe UI Symbol"','"Noto Color Emoji"'],serif:["ui-serif","Georgia","Cambria",'"Times New Roman"',"Times","serif"],mono:["ui-monospace","SFMono-Regular","Menlo","Monaco","Consolas",'"Liberation Mono"','"Courier New"',"monospace"]},fontSize:{xs:["0.75rem",{lineHeight:"1rem"}],sm:["0.875rem",{lineHeight:"1.25rem"}],base:["1rem",{lineHeight:"1.5rem"}],lg:["1.125rem",{lineHeight:"1.75rem"}],xl:["1.25rem",{lineHeight:"1.75rem"}],"2xl":["1.5rem",{lineHeight:"2rem"}],"3xl":["1.875rem",{lineHeight:"2.25rem"}],"4xl":["2.25rem",{lineHeight:"2.5rem"}],"5xl":["3rem",{lineHeight:"1"}],"6xl":["3.75rem",{lineHeight:"1"}],"7xl":["4.5rem",{lineHeight:"1"}],"8xl":["6rem",{lineHeight:"1"}],"9xl":["8rem",{lineHeight:"1"}]},fontWeight:{thin:"100",extralight:"200",light:"300",normal:"400",medium:"500",semibold:"600",bold:"700",extrabold:"800",black:"900"},gap:({theme:e})=>e("spacing"),gradientColorStops:({theme:e})=>e("colors"),gradientColorStopPositions:{"0%":"0%","5%":"5%","10%":"10%","15%":"15%","20%":"20%","25%":"25%","30%":"30%","35%":"35%","40%":"40%","45%":"45%","50%":"50%","55%":"55%","60%":"60%","65%":"65%","70%":"70%","75%":"75%","80%":"80%","85%":"85%","90%":"90%","95%":"95%","100%":"100%",...x},grayscale:{0:"0",DEFAULT:"100%",...x},gridAutoColumns:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridAutoRows:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridColumn:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridColumnEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...E},gridColumnStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...E},gridRow:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridRowEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...E},gridRowStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...E},gridTemplateColumns:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...Fe},gridTemplateRows:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...Fe},height:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),hueRotate:{0:"0deg",15:"15deg",30:"30deg",60:"60deg",90:"90deg",180:"180deg",...J},inset:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),invert:{0:"0",DEFAULT:"100%",...x},keyframes:{spin:{to:{transform:"rotate(360deg)"}},ping:{"75%, 100%":{transform:"scale(2)",opacity:"0"}},pulse:{"50%":{opacity:".5"}},bounce:{"0%, 100%":{transform:"translateY(-25%)",animationTimingFunction:"cubic-bezier(0.8,0,1,1)"},"50%":{transform:"none",animationTimingFunction:"cubic-bezier(0,0,0.2,1)"}}},letterSpacing:{tighter:"-0.05em",tight:"-0.025em",normal:"0em",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeight:{none:"1",tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625",loose:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},listStyleType:{none:"none",disc:"disc",decimal:"decimal"},listStyleImage:{none:"none"},margin:({theme:e})=>({auto:"auto",...e("spacing")}),lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",...E},maxHeight:({theme:e})=>({none:"none",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),maxWidth:({theme:e})=>({none:"none",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",prose:"65ch",...e("spacing")}),minHeight:({theme:e})=>({full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),minWidth:({theme:e})=>({full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),objectPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},opacity:{0:"0",5:"0.05",10:"0.1",15:"0.15",20:"0.2",25:"0.25",30:"0.3",35:"0.35",40:"0.4",45:"0.45",50:"0.5",55:"0.55",60:"0.6",65:"0.65",70:"0.7",75:"0.75",80:"0.8",85:"0.85",90:"0.9",95:"0.95",100:"1",...x},order:{first:"-9999",last:"9999",none:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",...E},outlineColor:({theme:e})=>e("colors"),outlineOffset:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...I},outlineWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...I},padding:({theme:e})=>e("spacing"),placeholderColor:({theme:e})=>e("colors"),placeholderOpacity:({theme:e})=>e("opacity"),ringColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),ringOffsetColor:({theme:e})=>e("colors"),ringOffsetWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...I},ringOpacity:({theme:e})=>({DEFAULT:"0.5",...e("opacity")}),ringWidth:{DEFAULT:"3px",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...I},rotate:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",45:"45deg",90:"90deg",180:"180deg",...J},saturate:{0:"0",50:".5",100:"1",150:"1.5",200:"2",...x},scale:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",...x},screens:{sm:"40rem",md:"48rem",lg:"64rem",xl:"80rem","2xl":"96rem"},scrollMargin:({theme:e})=>e("spacing"),scrollPadding:({theme:e})=>e("spacing"),sepia:{0:"0",DEFAULT:"100%",...x},skew:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",...J},space:({theme:e})=>e("spacing"),spacing:{px:"1px",0:"0px",.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},stroke:({theme:e})=>({none:"none",...e("colors")}),strokeWidth:{0:"0",1:"1",2:"2",...E},supports:{},data:{},textColor:({theme:e})=>e("colors"),textDecorationColor:({theme:e})=>e("colors"),textDecorationThickness:{auto:"auto","from-font":"from-font",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...I},textIndent:({theme:e})=>e("spacing"),textOpacity:({theme:e})=>e("opacity"),textUnderlineOffset:{auto:"auto",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...I},transformOrigin:{center:"center",top:"top","top-right":"top right",right:"right","bottom-right":"bottom right",bottom:"bottom","bottom-left":"bottom left",left:"left","top-left":"top left"},transitionDelay:{0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...Me},transitionDuration:{DEFAULT:"150ms",0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...Me},transitionProperty:{none:"none",all:"all",DEFAULT:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter",colors:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke",opacity:"opacity",shadow:"box-shadow",transform:"transform"},transitionTimingFunction:{DEFAULT:"cubic-bezier(0.4, 0, 0.2, 1)",linear:"linear",in:"cubic-bezier(0.4, 0, 1, 1)",out:"cubic-bezier(0, 0, 0.2, 1)","in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},translate:({theme:e})=>({"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),size:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),width:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",screen:"100vw",svw:"100svw",lvw:"100lvw",dvw:"100dvw",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),willChange:{auto:"auto",scroll:"scroll-position",contents:"contents",transform:"transform"},zIndex:{auto:"auto",0:"0",10:"10",20:"20",30:"30",40:"40",50:"50",...E}};var zt=64;function U(e,r=[]){return{kind:"rule",selector:e,nodes:r}}function C(e,r="",t=[]){return{kind:"at-rule",name:e,params:r,nodes:t}}function O(e,r=[]){return e.charCodeAt(0)===zt?Le(e,r):U(e,r)}function N(e,r,t=!1){return{kind:"declaration",property:e,value:r,important:t}}function Q(e){return{kind:"comment",value:e}}function z(e,r){let t=0,a={file:null,code:""};function o(n,l=0){let u="",s=" ".repeat(l);if(n.kind==="declaration"){if(u+=`${s}${n.property}: ${n.value}${n.important?" !important":""}; +`,r){t+=s.length;let c=t;t+=n.property.length,t+=2,t+=n.value?.length??0,n.important&&(t+=11);let f=t;t+=2,n.dst=[a,c,f]}}else if(n.kind==="rule"){if(u+=`${s}${n.selector} { +`,r){t+=s.length;let c=t;t+=n.selector.length,t+=1;let f=t;n.dst=[a,c,f],t+=2}for(let c of n.nodes)u+=o(c,l+1);u+=`${s}} +`,r&&(t+=s.length,t+=2)}else if(n.kind==="at-rule"){if(n.nodes.length===0){let c=`${s}${n.name} ${n.params}; +`;if(r){t+=s.length;let f=t;t+=n.name.length,t+=1,t+=n.params.length;let k=t;t+=2,n.dst=[a,f,k]}return c}if(u+=`${s}${n.name}${n.params?` ${n.params} `:" "}{ +`,r){t+=s.length;let c=t;t+=n.name.length,n.params&&(t+=1,t+=n.params.length),t+=1;let f=t;n.dst=[a,c,f],t+=2}for(let c of n.nodes)u+=o(c,l+1);u+=`${s}} +`,r&&(t+=s.length,t+=2)}else if(n.kind==="comment"){if(u+=`${s}/*${n.value}*/ +`,r){t+=s.length;let c=t;t+=2+n.value.length+2;let f=t;n.dst=[a,c,f],t+=1}}else if(n.kind==="context"||n.kind==="at-root")return"";return u}let i="";for(let n of e)i+=o(n,0);return a.code=i,i}var Kt=33;function je(e,r,t){let a=new m(s=>new e.Input(s.code,{map:t?.input.map,from:s.file??void 0})),o=new m(s=>Z(s.code)),i=e.root();i.source=t;function n(s){if(!s||!s[0])return;let c=o.get(s[0]),f=c.find(s[1]),k=c.find(s[2]);return{input:a.get(s[0]),start:{line:f.line,column:f.column+1,offset:s[1]},end:{line:k.line,column:k.column+1,offset:s[2]}}}function l(s,c){let f=n(c);f?s.source=f:delete s.source}function u(s,c){if(s.kind==="declaration"){let f=e.decl({prop:s.property,value:s.value??"",important:s.important});l(f,s.src),c.append(f)}else if(s.kind==="rule"){let f=e.rule({selector:s.selector});l(f,s.src),f.raws.semicolon=!0,c.append(f);for(let k of s.nodes)u(k,f)}else if(s.kind==="at-rule"){let f=e.atRule({name:s.name.slice(1),params:s.params});l(f,s.src),f.raws.semicolon=!0,c.append(f);for(let k of s.nodes)u(k,f)}else if(s.kind==="comment"){let f=e.comment({text:s.value});f.raws.left="",f.raws.right="",l(f,s.src),c.append(f)}else s.kind==="at-root"||s.kind}for(let s of r)u(s,i);return i}function We(e){let r=new m(i=>({file:i.file??i.id??null,code:i.css}));function t(i){let n=i.source;if(!n)return;let l=n.input;if(l&&n.start!==void 0&&n.end!==void 0)return[r.get(l),n.start.offset,n.end.offset]}function a(i,n){if(i.type==="decl"){let l=N(i.prop,i.value,i.important);l.src=t(i),n.push(l)}else if(i.type==="rule"){let l=O(i.selector);l.src=t(i),i.each(u=>a(u,l.nodes)),n.push(l)}else if(i.type==="atrule"){let l=C(`@${i.name}`,i.params);l.src=t(i),i.each(u=>a(u,l.nodes)),n.push(l)}else if(i.type==="comment"){if(i.text.charCodeAt(0)!==Kt)return;let l=Q(i.text);l.src=t(i),n.push(l)}}let o=[];return e.each(i=>a(i,o)),o}import{normalizePath as Be}from"@tailwindcss/node";import X from"path";var se="'",ue='"';function ce(){let e=new WeakSet;function r(t){let a=t.root().source?.input.file;if(!a)return;let o=t.source?.input.file;if(!o||e.has(t))return;let i=t.params[0],n=i[0]===ue&&i[i.length-1]===ue?ue:i[0]===se&&i[i.length-1]===se?se:null;if(!n)return;let l=t.params.slice(1,-1),u="";if(l.startsWith("!")&&(l=l.slice(1),u="!"),!l.startsWith("./")&&!l.startsWith("../"))return;let s=X.posix.join(Be(X.dirname(o)),l),c=X.posix.dirname(Be(a)),f=X.posix.relative(c,s);f.startsWith(".")||(f="./"+f),t.params=n+u+f+n,e.add(t)}return{postcssPlugin:"tailwindcss-postcss-fix-relative-paths",Once(t){t.walkAtRules(/source|plugin|config/,r)}}}var p=jt.DEBUG,de=new Mt({maxSize:50});function qt(e,r,t){let a=`${r}:${t.base??""}:${JSON.stringify(t.optimize)}`;if(de.has(a))return de.get(a);let o={mtimes:new Map,compiler:null,scanner:null,tailwindCssAst:[],cachedPostCssAst:e.root(),optimizedPostCssAst:e.root(),fullRebuildPaths:[]};return de.set(a,o),o}function Zt(e={}){let r=e.base??process.cwd(),t=e.optimize??process.env.NODE_ENV==="production",a=e.transformAssetUrls??!0;return{postcssPlugin:"@tailwindcss/postcss",plugins:[ce(),{postcssPlugin:"tailwindcss",async Once(o,{result:i,postcss:n}){var me=[];try{let l=ve(me,new Wt);let u=i.opts.from??"";let s=u.endsWith(".module.css");p&&l.start(`[@tailwindcss/postcss] ${Ye(r,u)}`);{p&&l.start("Quick bail check");let w=!0;if(o.walkAtRules(h=>{if(h.name==="import"||h.name==="reference"||h.name==="theme"||h.name==="variant"||h.name==="config"||h.name==="plugin"||h.name==="apply"||h.name==="tailwind")return w=!1,!1}),w)return;p&&l.end("Quick bail check")}let c=qt(n,u,e);let f=u?D.dirname(D.resolve(u)):r;let k=c.compiler===null;async function V(){p&&l.start("Setup compiler"),c.fullRebuildPaths.length>0&&!k&&Yt(c.fullRebuildPaths),c.fullRebuildPaths=[],p&&l.start("PostCSS AST -> Tailwind CSS AST");let w=We(o);p&&l.end("PostCSS AST -> Tailwind CSS AST"),p&&l.start("Create compiler");let h=await Ft(w,{from:i.opts.from,base:f,shouldRewriteUrls:a,onDependency:ee=>c.fullRebuildPaths.push(ee),polyfills:s?pe.All^pe.AtProperty:pe.All});return p&&l.end("Create compiler"),p&&l.end("Setup compiler"),h}try{if(c.compiler??=V(),(await c.compiler).features===fe.None)return;let w="incremental";p&&l.start("Register full rebuild paths");{for(let b of c.fullRebuildPaths)i.messages.push({type:"dependency",plugin:"@tailwindcss/postcss",file:D.resolve(b),parent:i.opts.from});let _=i.messages.flatMap(b=>b.type!=="dependency"?[]:b.file);_.push(u);for(let b of _){let R=Ht.statSync(b,{throwIfNoEntry:!1})?.mtimeMs??null;if(R===null){b===u&&(w="full");continue}c.mtimes.get(b)!==R&&(w="full",c.mtimes.set(b,R))}}p&&l.end("Register full rebuild paths"),w==="full"&&!k&&(c.compiler=V());let h=await c.compiler;if(c.scanner===null||w==="full"){p&&l.start("Setup scanner");let _=(h.root==="none"?[]:h.root===null?[{base:r,pattern:"**/*",negated:!1}]:[{...h.root,negated:!1}]).concat(h.sources);c.scanner=new Gt({sources:_}),p&&l.end("Setup scanner")}p&&l.start("Scan for candidates");let ee=h.features&fe.Utilities?c.scanner.scan():[];if(p&&l.end("Scan for candidates"),h.features&fe.Utilities){p&&l.start("Register dependency messages");let _=D.resolve(r,u);for(let b of c.scanner.files){let R=D.resolve(b);R!==_&&i.messages.push({type:"dependency",plugin:"@tailwindcss/postcss",file:R,parent:i.opts.from})}for(let{base:b,pattern:R}of c.scanner.globs)R==="*"&&r===b||(R===""?i.messages.push({type:"dependency",plugin:"@tailwindcss/postcss",file:D.resolve(b),parent:i.opts.from}):i.messages.push({type:"dir-dependency",plugin:"@tailwindcss/postcss",dir:D.resolve(b),glob:R,parent:i.opts.from}));p&&l.end("Register dependency messages")}p&&l.start("Build utilities");let G=h.build(ee);if(p&&l.end("Build utilities"),c.tailwindCssAst!==G)if(t){p&&l.start("Optimization"),p&&l.start("AST -> CSS");let _=z(G);p&&l.end("AST -> CSS"),p&&l.start("Lightning CSS");let b=Bt(_,{minify:typeof t=="object"?t.minify:!0});p&&l.end("Lightning CSS"),p&&l.start("CSS -> PostCSS AST"),c.optimizedPostCssAst=n.parse(b.code,i.opts),p&&l.end("CSS -> PostCSS AST"),p&&l.end("Optimization")}else p&&l.start("Transform Tailwind CSS AST into PostCSS AST"),c.cachedPostCssAst=je(n,G,o.source),p&&l.end("Transform Tailwind CSS AST into PostCSS AST");c.tailwindCssAst=G,p&&l.start("Update PostCSS AST"),o.removeAll(),o.append(t?c.optimizedPostCssAst.clone().nodes:c.cachedPostCssAst.clone().nodes),o.raws.indent=" ",p&&l.end("Update PostCSS AST"),p&&l.end(`[@tailwindcss/postcss] ${Ye(r,u)}`)}catch(w){c.compiler=null;for(let h of c.fullRebuildPaths)i.messages.push({type:"dependency",plugin:"@tailwindcss/postcss",file:D.resolve(h),parent:i.opts.from});throw console.error(w),w&&typeof w=="object"&&"message"in w?o.error(`${w.message}`):o.error(`${w}`)}}catch(Ge){var He=Ge,qe=!0}finally{ke(me,He,qe)}}}]}}var Ya=Object.assign(Zt,{postcss:!0});export{Ya as default}; diff --git a/client/node_modules/@tailwindcss/postcss/package.json b/client/node_modules/@tailwindcss/postcss/package.json new file mode 100644 index 0000000..5c6d327 --- /dev/null +++ b/client/node_modules/@tailwindcss/postcss/package.json @@ -0,0 +1,51 @@ +{ + "name": "@tailwindcss/postcss", + "version": "4.3.1", + "description": "PostCSS plugin for Tailwind CSS, a utility-first CSS framework for rapidly building custom user interfaces", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/tailwindlabs/tailwindcss.git", + "directory": "packages/@tailwindcss-postcss" + }, + "bugs": "https://github.com/tailwindlabs/tailwindcss/issues", + "homepage": "https://tailwindcss.com", + "files": [ + "dist/" + ], + "publishConfig": { + "provenance": true, + "access": "public" + }, + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + } + }, + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "postcss": "8.5.15", + "@tailwindcss/node": "4.3.1", + "@tailwindcss/oxide": "4.3.1", + "tailwindcss": "4.3.1" + }, + "devDependencies": { + "@types/node": "22.19.19", + "@types/postcss-import": "14.0.3", + "dedent": "1.7.2", + "postcss-import": "^16.1.1", + "internal-example-plugin": "0.0.0" + }, + "scripts": { + "lint": "tsc --noEmit", + "build": "tsup-node", + "dev": "pnpm run build -- --watch" + } +} \ No newline at end of file diff --git a/client/node_modules/autoprefixer/LICENSE b/client/node_modules/autoprefixer/LICENSE new file mode 100644 index 0000000..c2314d5 --- /dev/null +++ b/client/node_modules/autoprefixer/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright 2013 Andrey Sitnik + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/client/node_modules/autoprefixer/README.md b/client/node_modules/autoprefixer/README.md new file mode 100644 index 0000000..92ef036 --- /dev/null +++ b/client/node_modules/autoprefixer/README.md @@ -0,0 +1,56 @@ +# Autoprefixer [![Cult Of Martians][cult-img]][cult] + + + +[PostCSS] plugin to parse CSS and add vendor prefixes to CSS rules using values +from [Can I Use]. It is recommended by Google and used in Twitter and Alibaba. + +Write your CSS rules without vendor prefixes (in fact, forget about them +entirely): + +```css +::placeholder { + color: gray; +} + +.image { + width: stretch; +} +``` + +Autoprefixer will use the data based on current browser popularity and property +support to apply prefixes for you. You can try the [interactive demo] +of Autoprefixer. + +```css +::-moz-placeholder { + color: gray; +} +::placeholder { + color: gray; +} + +.image { + width: -webkit-fill-available; + width: -moz-available; + width: stretch; +} +``` + +Twitter account for news and releases: [@autoprefixer]. + + +Sponsored by Evil Martians + + +[interactive demo]: https://autoprefixer.github.io/ +[@autoprefixer]: https://twitter.com/autoprefixer +[Can I Use]: https://caniuse.com/ +[cult-img]: https://cultofmartians.com/assets/badges/badge.svg +[PostCSS]: https://github.com/postcss/postcss +[cult]: https://cultofmartians.com/tasks/autoprefixer-grid.html + +## Docs +Read full docs **[here](https://github.com/postcss/autoprefixer#readme)**. diff --git a/client/node_modules/autoprefixer/bin/autoprefixer b/client/node_modules/autoprefixer/bin/autoprefixer new file mode 100755 index 0000000..785830e --- /dev/null +++ b/client/node_modules/autoprefixer/bin/autoprefixer @@ -0,0 +1,22 @@ +#!/usr/bin/env node + +let mode = process.argv[2] +if (mode === '--info') { + process.stdout.write(require('../')().info() + '\n') +} else if (mode === '--version') { + process.stdout.write( + 'autoprefixer ' + require('../package.json').version + '\n' + ) +} else { + process.stdout.write( + 'autoprefix\n' + + '\n' + + 'Options:\n' + + ' --info Show target browsers and used prefixes\n' + + ' --version Show version number\n' + + ' --help Show help\n' + + '\n' + + 'Usage:\n' + + ' autoprefixer --info\n' + ) +} diff --git a/client/node_modules/autoprefixer/data/prefixes.js b/client/node_modules/autoprefixer/data/prefixes.js new file mode 100644 index 0000000..073a78c --- /dev/null +++ b/client/node_modules/autoprefixer/data/prefixes.js @@ -0,0 +1,1141 @@ +let unpack = require('caniuse-lite/dist/unpacker/feature') + +function browsersSort(a, b) { + a = a.split(' ') + b = b.split(' ') + if (a[0] > b[0]) { + return 1 + } else if (a[0] < b[0]) { + return -1 + } else { + return Math.sign(parseFloat(a[1]) - parseFloat(b[1])) + } +} + +// Convert Can I Use data +function f(data, opts, callback) { + data = unpack(data) + + if (!callback) { + ;[callback, opts] = [opts, {}] + } + + let match = opts.match || /\sx($|\s)/ + let need = [] + + for (let browser in data.stats) { + let versions = data.stats[browser] + for (let version in versions) { + let support = versions[version] + if (support.match(match)) { + need.push(browser + ' ' + version) + } + } + } + + callback(need.sort(browsersSort)) +} + +// Add data for all properties +let result = {} + +function prefix(names, data) { + for (let name of names) { + result[name] = Object.assign({}, data) + } +} + +function add(names, data) { + for (let name of names) { + result[name].browsers = result[name].browsers + .concat(data.browsers) + .sort(browsersSort) + } +} + +module.exports = result + +// Border Radius +let prefixBorderRadius = require('caniuse-lite/data/features/border-radius') + +f(prefixBorderRadius, browsers => + prefix( + [ + 'border-radius', + 'border-top-left-radius', + 'border-top-right-radius', + 'border-bottom-right-radius', + 'border-bottom-left-radius' + ], + { + browsers, + feature: 'border-radius', + mistakes: ['-khtml-', '-ms-', '-o-'] + } + ) +) + +// Box Shadow +let prefixBoxshadow = require('caniuse-lite/data/features/css-boxshadow') + +f(prefixBoxshadow, browsers => + prefix(['box-shadow'], { + browsers, + feature: 'css-boxshadow', + mistakes: ['-khtml-'] + }) +) + +// Animation +let prefixAnimation = require('caniuse-lite/data/features/css-animation') + +f(prefixAnimation, browsers => + prefix( + [ + 'animation', + 'animation-name', + 'animation-duration', + 'animation-delay', + 'animation-direction', + 'animation-fill-mode', + 'animation-iteration-count', + 'animation-play-state', + 'animation-timing-function', + '@keyframes' + ], + { + browsers, + feature: 'css-animation', + mistakes: ['-khtml-', '-ms-'] + } + ) +) + +// Transition +let prefixTransition = require('caniuse-lite/data/features/css-transitions') + +f(prefixTransition, browsers => + prefix( + [ + 'transition', + 'transition-property', + 'transition-duration', + 'transition-delay', + 'transition-timing-function' + ], + { + browsers, + feature: 'css-transitions', + mistakes: ['-khtml-', '-ms-'] + } + ) +) + +// Transform 2D +let prefixTransform2d = require('caniuse-lite/data/features/transforms2d') + +f(prefixTransform2d, browsers => + prefix(['transform', 'transform-origin'], { + browsers, + feature: 'transforms2d' + }) +) + +// Transform 3D +let prefixTransforms3d = require('caniuse-lite/data/features/transforms3d') + +f(prefixTransforms3d, browsers => { + prefix(['perspective', 'perspective-origin'], { + browsers, + feature: 'transforms3d' + }) + return prefix(['transform-style'], { + browsers, + feature: 'transforms3d', + mistakes: ['-ms-', '-o-'] + }) +}) + +f(prefixTransforms3d, { match: /y\sx|y\s#2/ }, browsers => + prefix(['backface-visibility'], { + browsers, + feature: 'transforms3d', + mistakes: ['-ms-', '-o-'] + }) +) + +// Gradients +let prefixGradients = require('caniuse-lite/data/features/css-gradients') + +f(prefixGradients, { match: /y\sx/ }, browsers => + prefix( + [ + 'linear-gradient', + 'repeating-linear-gradient', + 'radial-gradient', + 'repeating-radial-gradient' + ], + { + browsers, + feature: 'css-gradients', + mistakes: ['-ms-'], + props: [ + 'background', + 'background-image', + 'border-image', + 'mask', + 'list-style', + 'list-style-image', + 'content', + 'mask-image' + ] + } + ) +) + +f(prefixGradients, { match: /a\sx/ }, browsers => { + browsers = browsers.map(i => { + if (/firefox|op/.test(i)) { + return i + } else { + return `${i} old` + } + }) + return add( + [ + 'linear-gradient', + 'repeating-linear-gradient', + 'radial-gradient', + 'repeating-radial-gradient' + ], + { + browsers, + feature: 'css-gradients' + } + ) +}) + +// Box sizing +let prefixBoxsizing = require('caniuse-lite/data/features/css3-boxsizing') + +f(prefixBoxsizing, browsers => + prefix(['box-sizing'], { + browsers, + feature: 'css3-boxsizing' + }) +) + +// Filter Effects +let prefixFilters = require('caniuse-lite/data/features/css-filters') + +f(prefixFilters, browsers => + prefix(['filter'], { + browsers, + feature: 'css-filters' + }) +) + +// filter() function +let prefixFilterFunction = require('caniuse-lite/data/features/css-filter-function') + +f(prefixFilterFunction, browsers => + prefix(['filter-function'], { + browsers, + feature: 'css-filter-function', + props: [ + 'background', + 'background-image', + 'border-image', + 'mask', + 'list-style', + 'list-style-image', + 'content', + 'mask-image' + ] + }) +) + +// Backdrop-filter +let prefixBackdropFilter = require('caniuse-lite/data/features/css-backdrop-filter') + +f(prefixBackdropFilter, { match: /y\sx|y\s#2/ }, browsers => + prefix(['backdrop-filter'], { + browsers, + feature: 'css-backdrop-filter' + }) +) + +// element() function +let prefixElementFunction = require('caniuse-lite/data/features/css-element-function') + +f(prefixElementFunction, browsers => + prefix(['element'], { + browsers, + feature: 'css-element-function', + props: [ + 'background', + 'background-image', + 'border-image', + 'mask', + 'list-style', + 'list-style-image', + 'content', + 'mask-image' + ] + }) +) + +// Multicolumns +let prefixMulticolumns = require('caniuse-lite/data/features/multicolumn') + +f(prefixMulticolumns, browsers => { + prefix( + [ + 'columns', + 'column-width', + 'column-gap', + 'column-rule', + 'column-rule-color', + 'column-rule-width', + 'column-count', + 'column-rule-style', + 'column-span', + 'column-fill' + ], + { + browsers, + feature: 'multicolumn' + } + ) + + let noff = browsers.filter(i => !/firefox/.test(i)) + prefix(['break-before', 'break-after', 'break-inside'], { + browsers: noff, + feature: 'multicolumn' + }) +}) + +// User select +let prefixUserSelect = require('caniuse-lite/data/features/user-select-none') + +f(prefixUserSelect, browsers => + prefix(['user-select'], { + browsers, + feature: 'user-select-none', + mistakes: ['-khtml-'] + }) +) + +// Flexible Box Layout +let prefixFlexbox = require('caniuse-lite/data/features/flexbox') + +f(prefixFlexbox, { match: /a\sx/ }, browsers => { + browsers = browsers.map(i => { + if (/ie|firefox/.test(i)) { + return i + } else { + return `${i} 2009` + } + }) + prefix(['display-flex', 'inline-flex'], { + browsers, + feature: 'flexbox', + props: ['display'] + }) + prefix(['flex', 'flex-grow', 'flex-shrink', 'flex-basis'], { + browsers, + feature: 'flexbox' + }) + prefix( + [ + 'flex-direction', + 'flex-wrap', + 'flex-flow', + 'justify-content', + 'order', + 'align-items', + 'align-self', + 'align-content' + ], + { + browsers, + feature: 'flexbox' + } + ) +}) + +f(prefixFlexbox, { match: /y\sx/ }, browsers => { + add(['display-flex', 'inline-flex'], { + browsers, + feature: 'flexbox' + }) + add(['flex', 'flex-grow', 'flex-shrink', 'flex-basis'], { + browsers, + feature: 'flexbox' + }) + add( + [ + 'flex-direction', + 'flex-wrap', + 'flex-flow', + 'justify-content', + 'order', + 'align-items', + 'align-self', + 'align-content' + ], + { + browsers, + feature: 'flexbox' + } + ) +}) + +// calc() unit +let prefixCalc = require('caniuse-lite/data/features/calc') + +f(prefixCalc, browsers => + prefix(['calc'], { + browsers, + feature: 'calc', + props: ['*'] + }) +) + +// Background options +let prefixBackgroundOptions = require('caniuse-lite/data/features/background-img-opts') + +f(prefixBackgroundOptions, browsers => + prefix(['background-origin', 'background-size'], { + browsers, + feature: 'background-img-opts' + }) +) + +// background-clip: text +let prefixBackgroundClipText = require('caniuse-lite/data/features/background-clip-text') + +f(prefixBackgroundClipText, browsers => + prefix(['background-clip'], { + browsers, + feature: 'background-clip-text' + }) +) + +// Font feature settings +let prefixFontFeature = require('caniuse-lite/data/features/font-feature') + +f(prefixFontFeature, browsers => + prefix( + [ + 'font-feature-settings', + 'font-variant-ligatures', + 'font-language-override' + ], + { + browsers, + feature: 'font-feature' + } + ) +) + +// CSS font-kerning property +let prefixFontKerning = require('caniuse-lite/data/features/font-kerning') + +f(prefixFontKerning, browsers => + prefix(['font-kerning'], { + browsers, + feature: 'font-kerning' + }) +) + +// Border image +let prefixBorderImage = require('caniuse-lite/data/features/border-image') + +f(prefixBorderImage, browsers => + prefix(['border-image'], { + browsers, + feature: 'border-image' + }) +) + +// Selection selector +let prefixSelection = require('caniuse-lite/data/features/css-selection') + +f(prefixSelection, browsers => + prefix(['::selection'], { + browsers, + feature: 'css-selection', + selector: true + }) +) + +// Placeholder selector +let prefixPlaceholder = require('caniuse-lite/data/features/css-placeholder') + +f(prefixPlaceholder, browsers => { + prefix(['::placeholder'], { + browsers: browsers.concat(['ie 10 old', 'ie 11 old', 'firefox 18 old']), + feature: 'css-placeholder', + selector: true + }) +}) + +// Placeholder-shown selector +let prefixPlaceholderShown = require('caniuse-lite/data/features/css-placeholder-shown') + +f(prefixPlaceholderShown, browsers => { + prefix([':placeholder-shown'], { + browsers, + feature: 'css-placeholder-shown', + selector: true + }) +}) + +// Hyphenation +let prefixHyphens = require('caniuse-lite/data/features/css-hyphens') + +f(prefixHyphens, browsers => + prefix(['hyphens'], { + browsers, + feature: 'css-hyphens' + }) +) + +// Fullscreen selector +let prefixFullscreen = require('caniuse-lite/data/features/fullscreen') + +f(prefixFullscreen, browsers => + prefix([':fullscreen'], { + browsers, + feature: 'fullscreen', + selector: true + }) +) + +// ::backdrop pseudo-element +// https://caniuse.com/mdn-css_selectors_backdrop +let prefixBackdrop = require('caniuse-lite/data/features/mdn-css-backdrop-pseudo-element') + +f(prefixBackdrop, browsers => + prefix(['::backdrop'], { + browsers, + feature: 'backdrop', + selector: true + }) +) + +// File selector button +let prefixFileSelectorButton = require('caniuse-lite/data/features/css-file-selector-button') + +f(prefixFileSelectorButton, browsers => + prefix(['::file-selector-button'], { + browsers, + feature: 'file-selector-button', + selector: true + }) +) + +// :autofill +let prefixAutofill = require('caniuse-lite/data/features/css-autofill') + +f(prefixAutofill, browsers => + prefix([':autofill'], { + browsers, + feature: 'css-autofill', + selector: true + }) +) + +// Tab size +let prefixTabsize = require('caniuse-lite/data/features/css3-tabsize') + +f(prefixTabsize, browsers => + prefix(['tab-size'], { + browsers, + feature: 'css3-tabsize' + }) +) + +// Intrinsic & extrinsic sizing +let prefixIntrinsic = require('caniuse-lite/data/features/intrinsic-width') + +let sizeProps = [ + 'width', + 'min-width', + 'max-width', + 'height', + 'min-height', + 'max-height', + 'inline-size', + 'min-inline-size', + 'max-inline-size', + 'block-size', + 'min-block-size', + 'max-block-size', + 'grid', + 'grid-template', + 'grid-template-rows', + 'grid-template-columns', + 'grid-auto-columns', + 'grid-auto-rows' +] + +f(prefixIntrinsic, browsers => + prefix(['max-content', 'min-content'], { + browsers, + feature: 'intrinsic-width', + props: sizeProps + }) +) + +f(prefixIntrinsic, { match: /x|\s#4/ }, browsers => + prefix(['fill', 'fill-available'], { + browsers, + feature: 'intrinsic-width', + props: sizeProps + }) +) + +f(prefixIntrinsic, { match: /x|\s#5/ }, browsers => { + let ffFix = browsers.filter(i => { + let [name, version] = i.split(' ') + if (name === 'firefox' || name === 'and_ff') { + return parseInt(version) < 94 + } else { + return true + } + }) + return prefix(['fit-content'], { + browsers: ffFix, + feature: 'intrinsic-width', + props: sizeProps + }) +}) + +// Stretch value + +let prefixStretch = require('caniuse-lite/data/features/css-width-stretch') + +f(prefixStretch, browsers => { + f(prefixIntrinsic, { match: /x|\s#2/ }, firefox => { + browsers = browsers.concat(firefox) + }) + return prefix(['stretch'], { + browsers, + feature: 'css-width-stretch', + props: sizeProps + }) +}) + +// Zoom cursors +let prefixCursorsNew = require('caniuse-lite/data/features/css3-cursors-newer') + +f(prefixCursorsNew, browsers => + prefix(['zoom-in', 'zoom-out'], { + browsers, + feature: 'css3-cursors-newer', + props: ['cursor'] + }) +) + +// Grab cursors +let prefixCursorsGrab = require('caniuse-lite/data/features/css3-cursors-grab') + +f(prefixCursorsGrab, browsers => + prefix(['grab', 'grabbing'], { + browsers, + feature: 'css3-cursors-grab', + props: ['cursor'] + }) +) + +// Sticky position +let prefixSticky = require('caniuse-lite/data/features/css-sticky') + +f(prefixSticky, browsers => + prefix(['sticky'], { + browsers, + feature: 'css-sticky', + props: ['position'] + }) +) + +// Pointer Events +let prefixPointer = require('caniuse-lite/data/features/pointer') + +f(prefixPointer, browsers => + prefix(['touch-action'], { + browsers, + feature: 'pointer' + }) +) + +// Text decoration +let prefixDecoration = require('caniuse-lite/data/features/text-decoration') + +f(prefixDecoration, { match: /x.*#[235]/ }, browsers => + prefix(['text-decoration-skip', 'text-decoration-skip-ink'], { + browsers, + feature: 'text-decoration' + }) +) + +let prefixDecorationShorthand = require('caniuse-lite/data/features/mdn-text-decoration-shorthand') + +f(prefixDecorationShorthand, browsers => + prefix(['text-decoration'], { + browsers, + feature: 'text-decoration' + }) +) + +let prefixDecorationColor = require('caniuse-lite/data/features/mdn-text-decoration-color') + +f(prefixDecorationColor, browsers => + prefix(['text-decoration-color'], { + browsers, + feature: 'text-decoration' + }) +) + +let prefixDecorationLine = require('caniuse-lite/data/features/mdn-text-decoration-line') + +f(prefixDecorationLine, browsers => + prefix(['text-decoration-line'], { + browsers, + feature: 'text-decoration' + }) +) + +let prefixDecorationStyle = require('caniuse-lite/data/features/mdn-text-decoration-style') + +f(prefixDecorationStyle, browsers => + prefix(['text-decoration-style'], { + browsers, + feature: 'text-decoration' + }) +) + +// Text Size Adjust +let prefixTextSizeAdjust = require('caniuse-lite/data/features/text-size-adjust') + +f(prefixTextSizeAdjust, browsers => + prefix(['text-size-adjust'], { + browsers, + feature: 'text-size-adjust' + }) +) + +// CSS Masks +let prefixCssMasks = require('caniuse-lite/data/features/css-masks') + +f(prefixCssMasks, browsers => { + prefix( + [ + 'mask-clip', + 'mask-composite', + 'mask-image', + 'mask-origin', + 'mask-repeat', + 'mask-border-repeat', + 'mask-border-source' + ], + { + browsers, + feature: 'css-masks' + } + ) + prefix( + [ + 'mask', + 'mask-position', + 'mask-position-x', + 'mask-position-y', + 'mask-size', + 'mask-border', + 'mask-border-outset', + 'mask-border-width', + 'mask-border-slice' + ], + { + browsers, + feature: 'css-masks' + } + ) +}) + +// CSS clip-path property +let prefixClipPath = require('caniuse-lite/data/features/css-clip-path') + +f(prefixClipPath, browsers => + prefix(['clip-path'], { + browsers, + feature: 'css-clip-path' + }) +) + +// Fragmented Borders and Backgrounds +let prefixBoxdecoration = require('caniuse-lite/data/features/css-boxdecorationbreak') + +f(prefixBoxdecoration, browsers => + prefix(['box-decoration-break'], { + browsers, + feature: 'css-boxdecorationbreak' + }) +) + +// CSS3 object-fit/object-position +let prefixObjectFit = require('caniuse-lite/data/features/object-fit') + +f(prefixObjectFit, browsers => + prefix(['object-fit', 'object-position'], { + browsers, + feature: 'object-fit' + }) +) + +// CSS Shapes +let prefixShapes = require('caniuse-lite/data/features/css-shapes') + +f(prefixShapes, browsers => + prefix(['shape-margin', 'shape-outside', 'shape-image-threshold'], { + browsers, + feature: 'css-shapes' + }) +) + +// CSS3 text-overflow +let prefixTextOverflow = require('caniuse-lite/data/features/text-overflow') + +f(prefixTextOverflow, browsers => + prefix(['text-overflow'], { + browsers, + feature: 'text-overflow' + }) +) + +// Viewport at-rule +let prefixDeviceadaptation = require('caniuse-lite/data/features/css-deviceadaptation') + +f(prefixDeviceadaptation, browsers => + prefix(['@viewport'], { + browsers, + feature: 'css-deviceadaptation' + }) +) + +// Resolution Media Queries +let prefixResolut = require('caniuse-lite/data/features/css-media-resolution') + +f(prefixResolut, { match: /( x($| )|a #2)/ }, browsers => + prefix(['@resolution'], { + browsers, + feature: 'css-media-resolution' + }) +) + +// CSS text-align-last +let prefixTextAlignLast = require('caniuse-lite/data/features/css-text-align-last') + +f(prefixTextAlignLast, browsers => + prefix(['text-align-last'], { + browsers, + feature: 'css-text-align-last' + }) +) + +// Crisp Edges Image Rendering Algorithm +let prefixCrispedges = require('caniuse-lite/data/features/css-crisp-edges') + +f(prefixCrispedges, { match: /y x|a x #1/ }, browsers => + prefix(['pixelated'], { + browsers, + feature: 'css-crisp-edges', + props: ['image-rendering'] + }) +) + +f(prefixCrispedges, { match: /a x #2/ }, browsers => + prefix(['image-rendering'], { + browsers, + feature: 'css-crisp-edges' + }) +) + +// Logical Properties +let prefixLogicalProps = require('caniuse-lite/data/features/css-logical-props') + +f(prefixLogicalProps, browsers => + prefix( + [ + 'border-inline-start', + 'border-inline-end', + 'margin-inline-start', + 'margin-inline-end', + 'padding-inline-start', + 'padding-inline-end' + ], + { + browsers, + feature: 'css-logical-props' + } + ) +) + +f(prefixLogicalProps, { match: /x\s#2/ }, browsers => + prefix( + [ + 'border-block-start', + 'border-block-end', + 'margin-block-start', + 'margin-block-end', + 'padding-block-start', + 'padding-block-end' + ], + { + browsers, + feature: 'css-logical-props' + } + ) +) + +// CSS appearance +let prefixAppearance = require('caniuse-lite/data/features/css-appearance') + +f(prefixAppearance, { match: /#2|x/ }, browsers => + prefix(['appearance'], { + browsers, + feature: 'css-appearance' + }) +) + +// CSS Scroll snap points +let prefixSnappoints = require('caniuse-lite/data/features/css-snappoints') + +f(prefixSnappoints, browsers => + prefix( + [ + 'scroll-snap-type', + 'scroll-snap-coordinate', + 'scroll-snap-destination', + 'scroll-snap-points-x', + 'scroll-snap-points-y' + ], + { + browsers, + feature: 'css-snappoints' + } + ) +) + +// CSS Regions +let prefixRegions = require('caniuse-lite/data/features/css-regions') + +f(prefixRegions, browsers => + prefix(['flow-into', 'flow-from', 'region-fragment'], { + browsers, + feature: 'css-regions' + }) +) + +// CSS image-set +let prefixImageSet = require('caniuse-lite/data/features/css-image-set') + +f(prefixImageSet, browsers => + prefix(['image-set'], { + browsers, + feature: 'css-image-set', + props: [ + 'background', + 'background-image', + 'border-image', + 'cursor', + 'mask', + 'mask-image', + 'list-style', + 'list-style-image', + 'content' + ] + }) +) + +// Writing Mode +let prefixWritingMode = require('caniuse-lite/data/features/css-writing-mode') + +f(prefixWritingMode, { match: /a|x/ }, browsers => + prefix(['writing-mode'], { + browsers, + feature: 'css-writing-mode' + }) +) + +// Cross-Fade Function +let prefixCrossFade = require('caniuse-lite/data/features/css-cross-fade') + +f(prefixCrossFade, browsers => + prefix(['cross-fade'], { + browsers, + feature: 'css-cross-fade', + props: [ + 'background', + 'background-image', + 'border-image', + 'mask', + 'list-style', + 'list-style-image', + 'content', + 'mask-image' + ] + }) +) + +// Read Only selector +let prefixReadOnly = require('caniuse-lite/data/features/css-read-only-write') + +f(prefixReadOnly, browsers => + prefix([':read-only', ':read-write'], { + browsers, + feature: 'css-read-only-write', + selector: true + }) +) + +// Text Emphasize +let prefixTextEmphasis = require('caniuse-lite/data/features/text-emphasis') + +f(prefixTextEmphasis, browsers => + prefix( + [ + 'text-emphasis', + 'text-emphasis-position', + 'text-emphasis-style', + 'text-emphasis-color' + ], + { + browsers, + feature: 'text-emphasis' + } + ) +) + +// CSS Grid Layout +let prefixGrid = require('caniuse-lite/data/features/css-grid') + +f(prefixGrid, browsers => { + prefix(['display-grid', 'inline-grid'], { + browsers, + feature: 'css-grid', + props: ['display'] + }) + prefix( + [ + 'grid-template-columns', + 'grid-template-rows', + 'grid-row-start', + 'grid-column-start', + 'grid-row-end', + 'grid-column-end', + 'grid-row', + 'grid-column', + 'grid-area', + 'grid-template', + 'grid-template-areas', + 'place-self' + ], + { + browsers, + feature: 'css-grid' + } + ) +}) + +f(prefixGrid, { match: /a x/ }, browsers => + prefix(['grid-column-align', 'grid-row-align'], { + browsers, + feature: 'css-grid' + }) +) + +// CSS text-spacing +let prefixTextSpacing = require('caniuse-lite/data/features/css-text-spacing') + +f(prefixTextSpacing, browsers => + prefix(['text-spacing'], { + browsers, + feature: 'css-text-spacing' + }) +) + +// :any-link selector +let prefixAnyLink = require('caniuse-lite/data/features/css-any-link') + +f(prefixAnyLink, browsers => + prefix([':any-link'], { + browsers, + feature: 'css-any-link', + selector: true + }) +) + +// unicode-bidi + +let bidiIsolate = require('caniuse-lite/data/features/mdn-css-unicode-bidi-isolate') + +f(bidiIsolate, browsers => + prefix(['isolate'], { + browsers, + feature: 'css-unicode-bidi', + props: ['unicode-bidi'] + }) +) + +let bidiPlaintext = require('caniuse-lite/data/features/mdn-css-unicode-bidi-plaintext') + +f(bidiPlaintext, browsers => + prefix(['plaintext'], { + browsers, + feature: 'css-unicode-bidi', + props: ['unicode-bidi'] + }) +) + +let bidiOverride = require('caniuse-lite/data/features/mdn-css-unicode-bidi-isolate-override') + +f(bidiOverride, { match: /y x/ }, browsers => + prefix(['isolate-override'], { + browsers, + feature: 'css-unicode-bidi', + props: ['unicode-bidi'] + }) +) + +// overscroll-behavior selector +let prefixOverscroll = require('caniuse-lite/data/features/css-overscroll-behavior') + +f(prefixOverscroll, { match: /a #1/ }, browsers => + prefix(['overscroll-behavior'], { + browsers, + feature: 'css-overscroll-behavior' + }) +) + +// text-orientation +let prefixTextOrientation = require('caniuse-lite/data/features/css-text-orientation') + +f(prefixTextOrientation, browsers => + prefix(['text-orientation'], { + browsers, + feature: 'css-text-orientation' + }) +) + +// print-color-adjust +let prefixPrintAdjust = require('caniuse-lite/data/features/css-print-color-adjust') + +f(prefixPrintAdjust, browsers => + prefix(['print-color-adjust', 'color-adjust'], { + browsers, + feature: 'css-print-color-adjust' + }) +) diff --git a/client/node_modules/autoprefixer/lib/at-rule.js b/client/node_modules/autoprefixer/lib/at-rule.js new file mode 100644 index 0000000..d36a279 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/at-rule.js @@ -0,0 +1,35 @@ +let Prefixer = require('./prefixer') + +class AtRule extends Prefixer { + /** + * Clone and add prefixes for at-rule + */ + add(rule, prefix) { + let prefixed = prefix + rule.name + + let already = rule.parent.some( + i => i.name === prefixed && i.params === rule.params + ) + if (already) { + return undefined + } + + let cloned = this.clone(rule, { name: prefixed }) + return rule.parent.insertBefore(rule, cloned) + } + + /** + * Clone node with prefixes + */ + process(node) { + let parent = this.parentPrefix(node) + + for (let prefix of this.prefixes) { + if (!parent || parent === prefix) { + this.add(node, prefix) + } + } + } +} + +module.exports = AtRule diff --git a/client/node_modules/autoprefixer/lib/autoprefixer.d.ts b/client/node_modules/autoprefixer/lib/autoprefixer.d.ts new file mode 100644 index 0000000..6cad121 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/autoprefixer.d.ts @@ -0,0 +1,95 @@ +import { Stats } from 'browserslist' +import { Plugin } from 'postcss' + +declare function autoprefixer( + ...args: [...T, autoprefixer.Options] +): Plugin & autoprefixer.ExportedAPI + +declare function autoprefixer( + browsers: string[], + options?: autoprefixer.Options +): Plugin & autoprefixer.ExportedAPI + +declare function autoprefixer( + options?: autoprefixer.Options +): Plugin & autoprefixer.ExportedAPI + +declare namespace autoprefixer { + type GridValue = 'autoplace' | 'no-autoplace' + + interface Options { + /** environment for `Browserslist` */ + env?: string + + /** should Autoprefixer use Visual Cascade, if CSS is uncompressed */ + cascade?: boolean + + /** should Autoprefixer add prefixes. */ + add?: boolean + + /** should Autoprefixer [remove outdated] prefixes */ + remove?: boolean + + /** should Autoprefixer add prefixes for @supports parameters. */ + supports?: boolean + + /** should Autoprefixer add prefixes for flexbox properties */ + flexbox?: boolean | 'no-2009' + + /** should Autoprefixer add IE 10-11 prefixes for Grid Layout properties */ + grid?: boolean | GridValue + + /** custom usage statistics for > 10% in my stats browsers query */ + stats?: Stats + + /** + * list of queries for target browsers. + * Try to not use it. + * The best practice is to use `.browserslistrc` config or `browserslist` key in `package.json` + * to share target browsers with Babel, ESLint and Stylelint + */ + overrideBrowserslist?: string | string[] + + /** do not raise error on unknown browser version in `Browserslist` config. */ + ignoreUnknownVersions?: boolean + } + + interface ExportedAPI { + /** Autoprefixer data */ + data: { + browsers: { [browser: string]: object | undefined } + prefixes: { [prefixName: string]: object | undefined } + } + + /** Autoprefixer default browsers */ + defaults: string[] + + /** Inspect with default Autoprefixer */ + info(options?: { from?: string }): string + + options: Options + + browsers: string | string[] + } + + /** Autoprefixer data */ + let data: ExportedAPI['data'] + + /** Autoprefixer default browsers */ + let defaults: ExportedAPI['defaults'] + + /** Inspect with default Autoprefixer */ + let info: ExportedAPI['info'] + + let postcss: true +} + +declare global { + namespace NodeJS { + interface ProcessEnv { + AUTOPREFIXER_GRID?: autoprefixer.GridValue + } + } +} + +export = autoprefixer diff --git a/client/node_modules/autoprefixer/lib/autoprefixer.js b/client/node_modules/autoprefixer/lib/autoprefixer.js new file mode 100644 index 0000000..069409f --- /dev/null +++ b/client/node_modules/autoprefixer/lib/autoprefixer.js @@ -0,0 +1,164 @@ +let browserslist = require('browserslist') +let { agents } = require('caniuse-lite/dist/unpacker/agents') +let pico = require('picocolors') + +let dataPrefixes = require('../data/prefixes') +let Browsers = require('./browsers') +let getInfo = require('./info') +let Prefixes = require('./prefixes') + +let autoprefixerData = { browsers: agents, prefixes: dataPrefixes } + +const WARNING = + '\n' + + ' Replace Autoprefixer `browsers` option to Browserslist config.\n' + + ' Use `browserslist` key in `package.json` or `.browserslistrc` file.\n' + + '\n' + + ' Using `browsers` option can cause errors. Browserslist config can\n' + + ' be used for Babel, Autoprefixer, postcss-normalize and other tools.\n' + + '\n' + + ' If you really need to use option, rename it to `overrideBrowserslist`.\n' + + '\n' + + ' Learn more at:\n' + + ' https://github.com/browserslist/browserslist#readme\n' + + ' https://twitter.com/browserslist\n' + + '\n' + +function isPlainObject(obj) { + return Object.prototype.toString.apply(obj) === '[object Object]' +} + +let cache = new Map() + +function timeCapsule(result, prefixes) { + if (prefixes.browsers.selected.length === 0) { + return + } + if (prefixes.add.selectors.length > 0) { + return + } + if (Object.keys(prefixes.add).length > 2) { + return + } + /* c8 ignore next 11 */ + result.warn( + 'Autoprefixer target browsers do not need any prefixes.' + + 'You do not need Autoprefixer anymore.\n' + + 'Check your Browserslist config to be sure that your targets ' + + 'are set up correctly.\n' + + '\n' + + ' Learn more at:\n' + + ' https://github.com/postcss/autoprefixer#readme\n' + + ' https://github.com/browserslist/browserslist#readme\n' + + '\n' + ) +} + +module.exports = plugin + +function plugin(...reqs) { + let options + if (reqs.length === 1 && isPlainObject(reqs[0])) { + options = reqs[0] + reqs = undefined + } else if (reqs.length === 0 || (reqs.length === 1 && !reqs[0])) { + reqs = undefined + } else if (reqs.length <= 2 && (Array.isArray(reqs[0]) || !reqs[0])) { + options = reqs[1] + reqs = reqs[0] + } else if (typeof reqs[reqs.length - 1] === 'object') { + options = reqs.pop() + } + + if (!options) { + options = {} + } + + if (options.browser) { + throw new Error( + 'Change `browser` option to `overrideBrowserslist` in Autoprefixer' + ) + } else if (options.browserslist) { + throw new Error( + 'Change `browserslist` option to `overrideBrowserslist` in Autoprefixer' + ) + } + + if (options.overrideBrowserslist) { + reqs = options.overrideBrowserslist + } else if (options.browsers) { + if (typeof console !== 'undefined' && console.warn) { + console.warn( + pico.red(WARNING.replace(/`[^`]+`/g, i => pico.yellow(i.slice(1, -1)))) + ) + } + reqs = options.browsers + } + + let brwlstOpts = { + env: options.env, + ignoreUnknownVersions: options.ignoreUnknownVersions, + stats: options.stats + } + + function loadPrefixes(opts) { + let d = autoprefixerData + let browsers = new Browsers(d.browsers, reqs, opts, brwlstOpts) + let key = browsers.selected.join(', ') + JSON.stringify(options) + + if (!cache.has(key)) { + cache.set(key, new Prefixes(d.prefixes, browsers, options)) + } + + return cache.get(key) + } + + return { + browsers: reqs, + + info(opts) { + opts = opts || {} + opts.from = opts.from || process.cwd() + return getInfo(loadPrefixes(opts)) + }, + + options, + + postcssPlugin: 'autoprefixer', + prepare(result) { + let prefixes = loadPrefixes({ + env: options.env, + from: result.opts.from + }) + + return { + OnceExit(root) { + timeCapsule(result, prefixes) + if (options.remove !== false) { + prefixes.processor.remove(root, result) + } + if (options.add !== false) { + prefixes.processor.add(root, result) + } + } + } + } + } +} + +plugin.postcss = true + +/** + * Autoprefixer data + */ +plugin.data = autoprefixerData + +/** + * Autoprefixer default browsers + */ +plugin.defaults = browserslist.defaults + +/** + * Inspect with default Autoprefixer + */ +plugin.info = () => plugin().info() diff --git a/client/node_modules/autoprefixer/lib/brackets.js b/client/node_modules/autoprefixer/lib/brackets.js new file mode 100644 index 0000000..3bb1dad --- /dev/null +++ b/client/node_modules/autoprefixer/lib/brackets.js @@ -0,0 +1,51 @@ +function last(array) { + return array[array.length - 1] +} + +let brackets = { + /** + * Parse string to nodes tree + */ + parse(str) { + let current = [''] + let stack = [current] + + for (let sym of str) { + if (sym === '(') { + current = [''] + last(stack).push(current) + stack.push(current) + continue + } + + if (sym === ')') { + stack.pop() + current = last(stack) + current.push('') + continue + } + + current[current.length - 1] += sym + } + + return stack[0] + }, + + /** + * Generate output string by nodes tree + */ + stringify(ast) { + let result = '' + for (let i of ast) { + if (typeof i === 'object') { + result += `(${brackets.stringify(i)})` + continue + } + + result += i + } + return result + } +} + +module.exports = brackets diff --git a/client/node_modules/autoprefixer/lib/browsers.js b/client/node_modules/autoprefixer/lib/browsers.js new file mode 100644 index 0000000..b268c84 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/browsers.js @@ -0,0 +1,79 @@ +let browserslist = require('browserslist') +let { agents } = require('caniuse-lite/dist/unpacker/agents') + +let utils = require('./utils') + +class Browsers { + constructor(data, requirements, options, browserslistOpts) { + this.data = data + this.options = options || {} + this.browserslistOpts = browserslistOpts || {} + this.selected = this.parse(requirements) + } + + /** + * Return all prefixes for default browser data + */ + static prefixes() { + if (this.prefixesCache) { + return this.prefixesCache + } + + this.prefixesCache = [] + for (let name in agents) { + this.prefixesCache.push(`-${agents[name].prefix}-`) + } + + this.prefixesCache = utils + .uniq(this.prefixesCache) + .sort((a, b) => b.length - a.length) + + return this.prefixesCache + } + + /** + * Check is value contain any possible prefix + */ + static withPrefix(value) { + if (!this.prefixesRegexp) { + this.prefixesRegexp = new RegExp(this.prefixes().join('|')) + } + + return this.prefixesRegexp.test(value) + } + + /** + * Is browser is selected by requirements + */ + isSelected(browser) { + return this.selected.includes(browser) + } + + /** + * Return browsers selected by requirements + */ + parse(requirements) { + let opts = {} + for (let i in this.browserslistOpts) { + opts[i] = this.browserslistOpts[i] + } + opts.path = this.options.from + return browserslist(requirements, opts) + } + + /** + * Return prefix for selected browser + */ + prefix(browser) { + let [name, version] = browser.split(' ') + let data = this.data[name] + + let prefix = data.prefix_exceptions && data.prefix_exceptions[version] + if (!prefix) { + prefix = data.prefix + } + return `-${prefix}-` + } +} + +module.exports = Browsers diff --git a/client/node_modules/autoprefixer/lib/declaration.js b/client/node_modules/autoprefixer/lib/declaration.js new file mode 100644 index 0000000..9adb99d --- /dev/null +++ b/client/node_modules/autoprefixer/lib/declaration.js @@ -0,0 +1,187 @@ +let Browsers = require('./browsers') +let Prefixer = require('./prefixer') +let utils = require('./utils') + +class Declaration extends Prefixer { + /** + * Clone and add prefixes for declaration + */ + add(decl, prefix, prefixes, result) { + let prefixed = this.prefixed(decl.prop, prefix) + if ( + this.isAlready(decl, prefixed) || + this.otherPrefixes(decl.value, prefix) + ) { + return undefined + } + return this.insert(decl, prefix, prefixes, result) + } + + /** + * Calculate indentation to create visual cascade + */ + calcBefore(prefixes, decl, prefix = '') { + let max = this.maxPrefixed(prefixes, decl) + let diff = max - utils.removeNote(prefix).length + + let before = decl.raw('before') + if (diff > 0) { + before += Array(diff).fill(' ').join('') + } + + return before + } + + /** + * Always true, because we already get prefixer by property name + */ + check(/* decl */) { + return true + } + + /** + * Clone and insert new declaration + */ + insert(decl, prefix, prefixes) { + let cloned = this.set(this.clone(decl), prefix) + if (!cloned) return undefined + + let already = decl.parent.some( + i => i.prop === cloned.prop && i.value === cloned.value + ) + if (already) { + return undefined + } + + if (this.needCascade(decl)) { + cloned.raws.before = this.calcBefore(prefixes, decl, prefix) + } + return decl.parent.insertBefore(decl, cloned) + } + + /** + * Did this declaration has this prefix above + */ + isAlready(decl, prefixed) { + let already = this.all.group(decl).up(i => i.prop === prefixed) + if (!already) { + already = this.all.group(decl).down(i => i.prop === prefixed) + } + return already + } + + /** + * Return maximum length of possible prefixed property + */ + maxPrefixed(prefixes, decl) { + if (decl._autoprefixerMax) { + return decl._autoprefixerMax + } + + let max = 0 + for (let prefix of prefixes) { + prefix = utils.removeNote(prefix) + if (prefix.length > max) { + max = prefix.length + } + } + decl._autoprefixerMax = max + + return decl._autoprefixerMax + } + + /** + * Should we use visual cascade for prefixes + */ + needCascade(decl) { + if (!decl._autoprefixerCascade) { + decl._autoprefixerCascade = + this.all.options.cascade !== false && decl.raw('before').includes('\n') + } + return decl._autoprefixerCascade + } + + /** + * Return unprefixed version of property + */ + normalize(prop) { + return prop + } + + /** + * Return list of prefixed properties to clean old prefixes + */ + old(prop, prefix) { + return [this.prefixed(prop, prefix)] + } + + /** + * Check `value`, that it contain other prefixes, rather than `prefix` + */ + otherPrefixes(value, prefix) { + for (let other of Browsers.prefixes()) { + if (other === prefix) { + continue + } + if (value.includes(other)) { + return value.replace(/var\([^)]+\)/, '').includes(other) + } + } + return false + } + + /** + * Return prefixed version of property + */ + prefixed(prop, prefix) { + return prefix + prop + } + + /** + * Add spaces for visual cascade + */ + process(decl, result) { + if (!this.needCascade(decl)) { + super.process(decl, result) + return + } + + let prefixes = super.process(decl, result) + + if (!prefixes || !prefixes.length) { + return + } + + this.restoreBefore(decl) + decl.raws.before = this.calcBefore(prefixes, decl) + } + + /** + * Remove visual cascade + */ + restoreBefore(decl) { + let lines = decl.raw('before').split('\n') + let min = lines[lines.length - 1] + + this.all.group(decl).up(prefixed => { + let array = prefixed.raw('before').split('\n') + let last = array[array.length - 1] + if (last.length < min.length) { + min = last + } + }) + + lines[lines.length - 1] = min + decl.raws.before = lines.join('\n') + } + + /** + * Set prefix to declaration + */ + set(decl, prefix) { + decl.prop = this.prefixed(decl.prop, prefix) + return decl + } +} + +module.exports = Declaration diff --git a/client/node_modules/autoprefixer/lib/hacks/align-content.js b/client/node_modules/autoprefixer/lib/hacks/align-content.js new file mode 100644 index 0000000..d554274 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/align-content.js @@ -0,0 +1,49 @@ +let Declaration = require('../declaration') +let flexSpec = require('./flex-spec') + +class AlignContent extends Declaration { + /** + * Return property name by final spec + */ + normalize() { + return 'align-content' + } + + /** + * Change property name for 2012 spec + */ + prefixed(prop, prefix) { + let spec + ;[spec, prefix] = flexSpec(prefix) + if (spec === 2012) { + return prefix + 'flex-line-pack' + } + return super.prefixed(prop, prefix) + } + + /** + * Change value for 2012 spec and ignore prefix for 2009 + */ + set(decl, prefix) { + let spec = flexSpec(prefix)[0] + if (spec === 2012) { + decl.value = AlignContent.oldValues[decl.value] || decl.value + return super.set(decl, prefix) + } + if (spec === 'final') { + return super.set(decl, prefix) + } + return undefined + } +} + +AlignContent.names = ['align-content', 'flex-line-pack'] + +AlignContent.oldValues = { + 'flex-end': 'end', + 'flex-start': 'start', + 'space-around': 'distribute', + 'space-between': 'justify' +} + +module.exports = AlignContent diff --git a/client/node_modules/autoprefixer/lib/hacks/align-items.js b/client/node_modules/autoprefixer/lib/hacks/align-items.js new file mode 100644 index 0000000..9c12e65 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/align-items.js @@ -0,0 +1,46 @@ +let Declaration = require('../declaration') +let flexSpec = require('./flex-spec') + +class AlignItems extends Declaration { + /** + * Return property name by final spec + */ + normalize() { + return 'align-items' + } + + /** + * Change property name for 2009 and 2012 specs + */ + prefixed(prop, prefix) { + let spec + ;[spec, prefix] = flexSpec(prefix) + if (spec === 2009) { + return prefix + 'box-align' + } + if (spec === 2012) { + return prefix + 'flex-align' + } + return super.prefixed(prop, prefix) + } + + /** + * Change value for 2009 and 2012 specs + */ + set(decl, prefix) { + let spec = flexSpec(prefix)[0] + if (spec === 2009 || spec === 2012) { + decl.value = AlignItems.oldValues[decl.value] || decl.value + } + return super.set(decl, prefix) + } +} + +AlignItems.names = ['align-items', 'flex-align', 'box-align'] + +AlignItems.oldValues = { + 'flex-end': 'end', + 'flex-start': 'start' +} + +module.exports = AlignItems diff --git a/client/node_modules/autoprefixer/lib/hacks/align-self.js b/client/node_modules/autoprefixer/lib/hacks/align-self.js new file mode 100644 index 0000000..4070567 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/align-self.js @@ -0,0 +1,56 @@ +let Declaration = require('../declaration') +let flexSpec = require('./flex-spec') + +class AlignSelf extends Declaration { + check(decl) { + return ( + decl.parent && + !decl.parent.some(i => { + return i.prop && i.prop.startsWith('grid-') + }) + ) + } + + /** + * Return property name by final spec + */ + normalize() { + return 'align-self' + } + + /** + * Change property name for 2012 specs + */ + prefixed(prop, prefix) { + let spec + ;[spec, prefix] = flexSpec(prefix) + if (spec === 2012) { + return prefix + 'flex-item-align' + } + return super.prefixed(prop, prefix) + } + + /** + * Change value for 2012 spec and ignore prefix for 2009 + */ + set(decl, prefix) { + let spec = flexSpec(prefix)[0] + if (spec === 2012) { + decl.value = AlignSelf.oldValues[decl.value] || decl.value + return super.set(decl, prefix) + } + if (spec === 'final') { + return super.set(decl, prefix) + } + return undefined + } +} + +AlignSelf.names = ['align-self', 'flex-item-align'] + +AlignSelf.oldValues = { + 'flex-end': 'end', + 'flex-start': 'start' +} + +module.exports = AlignSelf diff --git a/client/node_modules/autoprefixer/lib/hacks/animation.js b/client/node_modules/autoprefixer/lib/hacks/animation.js new file mode 100644 index 0000000..7ce949a --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/animation.js @@ -0,0 +1,17 @@ +let Declaration = require('../declaration') + +class Animation extends Declaration { + /** + * Don’t add prefixes for modern values. + */ + check(decl) { + return !decl.value.split(/\s+/).some(i => { + let lower = i.toLowerCase() + return lower === 'reverse' || lower === 'alternate-reverse' + }) + } +} + +Animation.names = ['animation', 'animation-direction'] + +module.exports = Animation diff --git a/client/node_modules/autoprefixer/lib/hacks/appearance.js b/client/node_modules/autoprefixer/lib/hacks/appearance.js new file mode 100644 index 0000000..34be384 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/appearance.js @@ -0,0 +1,23 @@ +let Declaration = require('../declaration') +let utils = require('../utils') + +class Appearance extends Declaration { + constructor(name, prefixes, all) { + super(name, prefixes, all) + + if (this.prefixes) { + this.prefixes = utils.uniq( + this.prefixes.map(i => { + if (i === '-ms-') { + return '-webkit-' + } + return i + }) + ) + } + } +} + +Appearance.names = ['appearance'] + +module.exports = Appearance diff --git a/client/node_modules/autoprefixer/lib/hacks/autofill.js b/client/node_modules/autoprefixer/lib/hacks/autofill.js new file mode 100644 index 0000000..a9c49ce --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/autofill.js @@ -0,0 +1,26 @@ +let Selector = require('../selector') +let utils = require('../utils') + +class Autofill extends Selector { + constructor(name, prefixes, all) { + super(name, prefixes, all) + + if (this.prefixes) { + this.prefixes = utils.uniq(this.prefixes.map(() => '-webkit-')) + } + } + + /** + * Return different selectors depend on prefix + */ + prefixed(prefix) { + if (prefix === '-webkit-') { + return ':-webkit-autofill' + } + return `:${prefix}autofill` + } +} + +Autofill.names = [':autofill'] + +module.exports = Autofill diff --git a/client/node_modules/autoprefixer/lib/hacks/backdrop-filter.js b/client/node_modules/autoprefixer/lib/hacks/backdrop-filter.js new file mode 100644 index 0000000..f9b4b05 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/backdrop-filter.js @@ -0,0 +1,20 @@ +let Declaration = require('../declaration') +let utils = require('../utils') + +class BackdropFilter extends Declaration { + constructor(name, prefixes, all) { + super(name, prefixes, all) + + if (this.prefixes) { + this.prefixes = utils.uniq( + this.prefixes.map(i => { + return i === '-ms-' ? '-webkit-' : i + }) + ) + } + } +} + +BackdropFilter.names = ['backdrop-filter'] + +module.exports = BackdropFilter diff --git a/client/node_modules/autoprefixer/lib/hacks/background-clip.js b/client/node_modules/autoprefixer/lib/hacks/background-clip.js new file mode 100644 index 0000000..92c714c --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/background-clip.js @@ -0,0 +1,24 @@ +let Declaration = require('../declaration') +let utils = require('../utils') + +class BackgroundClip extends Declaration { + constructor(name, prefixes, all) { + super(name, prefixes, all) + + if (this.prefixes) { + this.prefixes = utils.uniq( + this.prefixes.map(i => { + return i === '-ms-' ? '-webkit-' : i + }) + ) + } + } + + check(decl) { + return decl.value.toLowerCase() === 'text' + } +} + +BackgroundClip.names = ['background-clip'] + +module.exports = BackgroundClip diff --git a/client/node_modules/autoprefixer/lib/hacks/background-size.js b/client/node_modules/autoprefixer/lib/hacks/background-size.js new file mode 100644 index 0000000..1fba894 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/background-size.js @@ -0,0 +1,23 @@ +let Declaration = require('../declaration') + +class BackgroundSize extends Declaration { + /** + * Duplication parameter for -webkit- browsers + */ + set(decl, prefix) { + let value = decl.value.toLowerCase() + if ( + prefix === '-webkit-' && + !value.includes(' ') && + value !== 'contain' && + value !== 'cover' + ) { + decl.value = decl.value + ' ' + decl.value + } + return super.set(decl, prefix) + } +} + +BackgroundSize.names = ['background-size'] + +module.exports = BackgroundSize diff --git a/client/node_modules/autoprefixer/lib/hacks/block-logical.js b/client/node_modules/autoprefixer/lib/hacks/block-logical.js new file mode 100644 index 0000000..cb795f7 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/block-logical.js @@ -0,0 +1,40 @@ +let Declaration = require('../declaration') + +class BlockLogical extends Declaration { + /** + * Return property name by spec + */ + normalize(prop) { + if (prop.includes('-before')) { + return prop.replace('-before', '-block-start') + } + return prop.replace('-after', '-block-end') + } + + /** + * Use old syntax for -moz- and -webkit- + */ + prefixed(prop, prefix) { + if (prop.includes('-start')) { + return prefix + prop.replace('-block-start', '-before') + } + return prefix + prop.replace('-block-end', '-after') + } +} + +BlockLogical.names = [ + 'border-block-start', + 'border-block-end', + 'margin-block-start', + 'margin-block-end', + 'padding-block-start', + 'padding-block-end', + 'border-before', + 'border-after', + 'margin-before', + 'margin-after', + 'padding-before', + 'padding-after' +] + +module.exports = BlockLogical diff --git a/client/node_modules/autoprefixer/lib/hacks/border-image.js b/client/node_modules/autoprefixer/lib/hacks/border-image.js new file mode 100644 index 0000000..f5cbd2c --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/border-image.js @@ -0,0 +1,15 @@ +let Declaration = require('../declaration') + +class BorderImage extends Declaration { + /** + * Remove fill parameter for prefixed declarations + */ + set(decl, prefix) { + decl.value = decl.value.replace(/\s+fill(\s)/, '$1') + return super.set(decl, prefix) + } +} + +BorderImage.names = ['border-image'] + +module.exports = BorderImage diff --git a/client/node_modules/autoprefixer/lib/hacks/border-radius.js b/client/node_modules/autoprefixer/lib/hacks/border-radius.js new file mode 100644 index 0000000..47ea835 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/border-radius.js @@ -0,0 +1,40 @@ +let Declaration = require('../declaration') + +class BorderRadius extends Declaration { + /** + * Return unprefixed version of property + */ + normalize(prop) { + return BorderRadius.toNormal[prop] || prop + } + + /** + * Change syntax, when add Mozilla prefix + */ + prefixed(prop, prefix) { + if (prefix === '-moz-') { + return prefix + (BorderRadius.toMozilla[prop] || prop) + } + return super.prefixed(prop, prefix) + } +} + +BorderRadius.names = ['border-radius'] + +BorderRadius.toMozilla = {} +BorderRadius.toNormal = {} + +for (let ver of ['top', 'bottom']) { + for (let hor of ['left', 'right']) { + let normal = `border-${ver}-${hor}-radius` + let mozilla = `border-radius-${ver}${hor}` + + BorderRadius.names.push(normal) + BorderRadius.names.push(mozilla) + + BorderRadius.toMozilla[normal] = mozilla + BorderRadius.toNormal[mozilla] = normal + } +} + +module.exports = BorderRadius diff --git a/client/node_modules/autoprefixer/lib/hacks/break-props.js b/client/node_modules/autoprefixer/lib/hacks/break-props.js new file mode 100644 index 0000000..b67b12f --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/break-props.js @@ -0,0 +1,63 @@ +let Declaration = require('../declaration') + +class BreakProps extends Declaration { + /** + * Don’t prefix some values + */ + insert(decl, prefix, prefixes) { + if (decl.prop !== 'break-inside') { + return super.insert(decl, prefix, prefixes) + } + if (/region/i.test(decl.value) || /page/i.test(decl.value)) { + return undefined + } + return super.insert(decl, prefix, prefixes) + } + + /** + * Return property name by final spec + */ + normalize(prop) { + if (prop.includes('inside')) { + return 'break-inside' + } + if (prop.includes('before')) { + return 'break-before' + } + return 'break-after' + } + + /** + * Change name for -webkit- and -moz- prefix + */ + prefixed(prop, prefix) { + return `${prefix}column-${prop}` + } + + /** + * Change prefixed value for avoid-column and avoid-page + */ + set(decl, prefix) { + if ( + (decl.prop === 'break-inside' && decl.value === 'avoid-column') || + decl.value === 'avoid-page' + ) { + decl.value = 'avoid' + } + return super.set(decl, prefix) + } +} + +BreakProps.names = [ + 'break-inside', + 'page-break-inside', + 'column-break-inside', + 'break-before', + 'page-break-before', + 'column-break-before', + 'break-after', + 'page-break-after', + 'column-break-after' +] + +module.exports = BreakProps diff --git a/client/node_modules/autoprefixer/lib/hacks/cross-fade.js b/client/node_modules/autoprefixer/lib/hacks/cross-fade.js new file mode 100644 index 0000000..caaa90d --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/cross-fade.js @@ -0,0 +1,35 @@ +let list = require('postcss').list + +let Value = require('../value') + +class CrossFade extends Value { + replace(string, prefix) { + return list + .space(string) + .map(value => { + if (value.slice(0, +this.name.length + 1) !== this.name + '(') { + return value + } + + let close = value.lastIndexOf(')') + let after = value.slice(close + 1) + let args = value.slice(this.name.length + 1, close) + + if (prefix === '-webkit-') { + let match = args.match(/\d*.?\d+%?/) + if (match) { + args = args.slice(match[0].length).trim() + args += `, ${match[0]}` + } else { + args += ', 0.5' + } + } + return prefix + this.name + '(' + args + ')' + after + }) + .join(' ') + } +} + +CrossFade.names = ['cross-fade'] + +module.exports = CrossFade diff --git a/client/node_modules/autoprefixer/lib/hacks/display-flex.js b/client/node_modules/autoprefixer/lib/hacks/display-flex.js new file mode 100644 index 0000000..663172c --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/display-flex.js @@ -0,0 +1,65 @@ +let OldValue = require('../old-value') +let Value = require('../value') +let flexSpec = require('./flex-spec') + +class DisplayFlex extends Value { + constructor(name, prefixes) { + super(name, prefixes) + if (name === 'display-flex') { + this.name = 'flex' + } + } + + /** + * Faster check for flex value + */ + check(decl) { + return decl.prop === 'display' && decl.value === this.name + } + + /** + * Change value for old specs + */ + old(prefix) { + let prefixed = this.prefixed(prefix) + if (!prefixed) return undefined + return new OldValue(this.name, prefixed) + } + + /** + * Return value by spec + */ + prefixed(prefix) { + let spec, value + ;[spec, prefix] = flexSpec(prefix) + + if (spec === 2009) { + if (this.name === 'flex') { + value = 'box' + } else { + value = 'inline-box' + } + } else if (spec === 2012) { + if (this.name === 'flex') { + value = 'flexbox' + } else { + value = 'inline-flexbox' + } + } else if (spec === 'final') { + value = this.name + } + + return prefix + value + } + + /** + * Add prefix to value depend on flebox spec version + */ + replace(string, prefix) { + return this.prefixed(prefix) + } +} + +DisplayFlex.names = ['display-flex', 'inline-flex'] + +module.exports = DisplayFlex diff --git a/client/node_modules/autoprefixer/lib/hacks/display-grid.js b/client/node_modules/autoprefixer/lib/hacks/display-grid.js new file mode 100644 index 0000000..290ec8b --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/display-grid.js @@ -0,0 +1,21 @@ +let Value = require('../value') + +class DisplayGrid extends Value { + constructor(name, prefixes) { + super(name, prefixes) + if (name === 'display-grid') { + this.name = 'grid' + } + } + + /** + * Faster check for flex value + */ + check(decl) { + return decl.prop === 'display' && decl.value === this.name + } +} + +DisplayGrid.names = ['display-grid', 'inline-grid'] + +module.exports = DisplayGrid diff --git a/client/node_modules/autoprefixer/lib/hacks/file-selector-button.js b/client/node_modules/autoprefixer/lib/hacks/file-selector-button.js new file mode 100644 index 0000000..18ebcea --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/file-selector-button.js @@ -0,0 +1,26 @@ +let Selector = require('../selector') +let utils = require('../utils') + +class FileSelectorButton extends Selector { + constructor(name, prefixes, all) { + super(name, prefixes, all) + + if (this.prefixes) { + this.prefixes = utils.uniq(this.prefixes.map(() => '-webkit-')) + } + } + + /** + * Return different selectors depend on prefix + */ + prefixed(prefix) { + if (prefix === '-webkit-') { + return '::-webkit-file-upload-button' + } + return `::${prefix}file-selector-button` + } +} + +FileSelectorButton.names = ['::file-selector-button'] + +module.exports = FileSelectorButton diff --git a/client/node_modules/autoprefixer/lib/hacks/filter-value.js b/client/node_modules/autoprefixer/lib/hacks/filter-value.js new file mode 100644 index 0000000..98e5f61 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/filter-value.js @@ -0,0 +1,14 @@ +let Value = require('../value') + +class FilterValue extends Value { + constructor(name, prefixes) { + super(name, prefixes) + if (name === 'filter-function') { + this.name = 'filter' + } + } +} + +FilterValue.names = ['filter', 'filter-function'] + +module.exports = FilterValue diff --git a/client/node_modules/autoprefixer/lib/hacks/filter.js b/client/node_modules/autoprefixer/lib/hacks/filter.js new file mode 100644 index 0000000..7ec6fbe --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/filter.js @@ -0,0 +1,19 @@ +let Declaration = require('../declaration') + +class Filter extends Declaration { + /** + * Check is it Internet Explorer filter + */ + check(decl) { + let v = decl.value + return ( + !v.toLowerCase().includes('alpha(') && + !v.includes('DXImageTransform.Microsoft') && + !v.includes('data:image/svg+xml') + ) + } +} + +Filter.names = ['filter'] + +module.exports = Filter diff --git a/client/node_modules/autoprefixer/lib/hacks/flex-basis.js b/client/node_modules/autoprefixer/lib/hacks/flex-basis.js new file mode 100644 index 0000000..3e913ee --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/flex-basis.js @@ -0,0 +1,39 @@ +let Declaration = require('../declaration') +let flexSpec = require('./flex-spec') + +class FlexBasis extends Declaration { + /** + * Return property name by final spec + */ + normalize() { + return 'flex-basis' + } + + /** + * Return flex property for 2012 spec + */ + prefixed(prop, prefix) { + let spec + ;[spec, prefix] = flexSpec(prefix) + if (spec === 2012) { + return prefix + 'flex-preferred-size' + } + return super.prefixed(prop, prefix) + } + + /** + * Ignore 2009 spec and use flex property for 2012 + */ + set(decl, prefix) { + let spec + ;[spec, prefix] = flexSpec(prefix) + if (spec === 2012 || spec === 'final') { + return super.set(decl, prefix) + } + return undefined + } +} + +FlexBasis.names = ['flex-basis', 'flex-preferred-size'] + +module.exports = FlexBasis diff --git a/client/node_modules/autoprefixer/lib/hacks/flex-direction.js b/client/node_modules/autoprefixer/lib/hacks/flex-direction.js new file mode 100644 index 0000000..e3928f9 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/flex-direction.js @@ -0,0 +1,72 @@ +let Declaration = require('../declaration') +let flexSpec = require('./flex-spec') + +class FlexDirection extends Declaration { + /** + * Use two properties for 2009 spec + */ + insert(decl, prefix, prefixes) { + let spec + ;[spec, prefix] = flexSpec(prefix) + if (spec !== 2009) { + return super.insert(decl, prefix, prefixes) + } + let already = decl.parent.some( + i => + i.prop === prefix + 'box-orient' || i.prop === prefix + 'box-direction' + ) + if (already) { + return undefined + } + + let v = decl.value + let dir, orient + if (v === 'inherit' || v === 'initial' || v === 'unset') { + orient = v + dir = v + } else { + orient = v.includes('row') ? 'horizontal' : 'vertical' + dir = v.includes('reverse') ? 'reverse' : 'normal' + } + + let cloned = this.clone(decl) + cloned.prop = prefix + 'box-orient' + cloned.value = orient + if (this.needCascade(decl)) { + cloned.raws.before = this.calcBefore(prefixes, decl, prefix) + } + decl.parent.insertBefore(decl, cloned) + + cloned = this.clone(decl) + cloned.prop = prefix + 'box-direction' + cloned.value = dir + if (this.needCascade(decl)) { + cloned.raws.before = this.calcBefore(prefixes, decl, prefix) + } + return decl.parent.insertBefore(decl, cloned) + } + + /** + * Return property name by final spec + */ + normalize() { + return 'flex-direction' + } + + /** + * Clean two properties for 2009 spec + */ + old(prop, prefix) { + let spec + ;[spec, prefix] = flexSpec(prefix) + if (spec === 2009) { + return [prefix + 'box-orient', prefix + 'box-direction'] + } else { + return super.old(prop, prefix) + } + } +} + +FlexDirection.names = ['flex-direction', 'box-direction', 'box-orient'] + +module.exports = FlexDirection diff --git a/client/node_modules/autoprefixer/lib/hacks/flex-flow.js b/client/node_modules/autoprefixer/lib/hacks/flex-flow.js new file mode 100644 index 0000000..4257ebd --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/flex-flow.js @@ -0,0 +1,53 @@ +let Declaration = require('../declaration') +let flexSpec = require('./flex-spec') + +class FlexFlow extends Declaration { + /** + * Use two properties for 2009 spec + */ + insert(decl, prefix, prefixes) { + let spec + ;[spec, prefix] = flexSpec(prefix) + if (spec !== 2009) { + return super.insert(decl, prefix, prefixes) + } + let values = decl.value + .split(/\s+/) + .filter(i => i !== 'wrap' && i !== 'nowrap' && 'wrap-reverse') + if (values.length === 0) { + return undefined + } + + let already = decl.parent.some( + i => + i.prop === prefix + 'box-orient' || i.prop === prefix + 'box-direction' + ) + if (already) { + return undefined + } + + let value = values[0] + let orient = value.includes('row') ? 'horizontal' : 'vertical' + let dir = value.includes('reverse') ? 'reverse' : 'normal' + + let cloned = this.clone(decl) + cloned.prop = prefix + 'box-orient' + cloned.value = orient + if (this.needCascade(decl)) { + cloned.raws.before = this.calcBefore(prefixes, decl, prefix) + } + decl.parent.insertBefore(decl, cloned) + + cloned = this.clone(decl) + cloned.prop = prefix + 'box-direction' + cloned.value = dir + if (this.needCascade(decl)) { + cloned.raws.before = this.calcBefore(prefixes, decl, prefix) + } + return decl.parent.insertBefore(decl, cloned) + } +} + +FlexFlow.names = ['flex-flow', 'box-direction', 'box-orient'] + +module.exports = FlexFlow diff --git a/client/node_modules/autoprefixer/lib/hacks/flex-grow.js b/client/node_modules/autoprefixer/lib/hacks/flex-grow.js new file mode 100644 index 0000000..b2faa71 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/flex-grow.js @@ -0,0 +1,30 @@ +let Declaration = require('../declaration') +let flexSpec = require('./flex-spec') + +class Flex extends Declaration { + /** + * Return property name by final spec + */ + normalize() { + return 'flex' + } + + /** + * Return flex property for 2009 and 2012 specs + */ + prefixed(prop, prefix) { + let spec + ;[spec, prefix] = flexSpec(prefix) + if (spec === 2009) { + return prefix + 'box-flex' + } + if (spec === 2012) { + return prefix + 'flex-positive' + } + return super.prefixed(prop, prefix) + } +} + +Flex.names = ['flex-grow', 'flex-positive'] + +module.exports = Flex diff --git a/client/node_modules/autoprefixer/lib/hacks/flex-shrink.js b/client/node_modules/autoprefixer/lib/hacks/flex-shrink.js new file mode 100644 index 0000000..1cc73da --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/flex-shrink.js @@ -0,0 +1,39 @@ +let Declaration = require('../declaration') +let flexSpec = require('./flex-spec') + +class FlexShrink extends Declaration { + /** + * Return property name by final spec + */ + normalize() { + return 'flex-shrink' + } + + /** + * Return flex property for 2012 spec + */ + prefixed(prop, prefix) { + let spec + ;[spec, prefix] = flexSpec(prefix) + if (spec === 2012) { + return prefix + 'flex-negative' + } + return super.prefixed(prop, prefix) + } + + /** + * Ignore 2009 spec and use flex property for 2012 + */ + set(decl, prefix) { + let spec + ;[spec, prefix] = flexSpec(prefix) + if (spec === 2012 || spec === 'final') { + return super.set(decl, prefix) + } + return undefined + } +} + +FlexShrink.names = ['flex-shrink', 'flex-negative'] + +module.exports = FlexShrink diff --git a/client/node_modules/autoprefixer/lib/hacks/flex-spec.js b/client/node_modules/autoprefixer/lib/hacks/flex-spec.js new file mode 100644 index 0000000..a077d66 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/flex-spec.js @@ -0,0 +1,19 @@ +/** + * Return flexbox spec versions by prefix + */ +module.exports = function (prefix) { + let spec + if (prefix === '-webkit- 2009' || prefix === '-moz-') { + spec = 2009 + } else if (prefix === '-ms-') { + spec = 2012 + } else if (prefix === '-webkit-') { + spec = 'final' + } + + if (prefix === '-webkit- 2009') { + prefix = '-webkit-' + } + + return [spec, prefix] +} diff --git a/client/node_modules/autoprefixer/lib/hacks/flex-wrap.js b/client/node_modules/autoprefixer/lib/hacks/flex-wrap.js new file mode 100644 index 0000000..489154d --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/flex-wrap.js @@ -0,0 +1,19 @@ +let Declaration = require('../declaration') +let flexSpec = require('./flex-spec') + +class FlexWrap extends Declaration { + /** + * Don't add prefix for 2009 spec + */ + set(decl, prefix) { + let spec = flexSpec(prefix)[0] + if (spec !== 2009) { + return super.set(decl, prefix) + } + return undefined + } +} + +FlexWrap.names = ['flex-wrap'] + +module.exports = FlexWrap diff --git a/client/node_modules/autoprefixer/lib/hacks/flex.js b/client/node_modules/autoprefixer/lib/hacks/flex.js new file mode 100644 index 0000000..146a394 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/flex.js @@ -0,0 +1,54 @@ +let list = require('postcss').list + +let Declaration = require('../declaration') +let flexSpec = require('./flex-spec') + +class Flex extends Declaration { + /** + * Return property name by final spec + */ + normalize() { + return 'flex' + } + + /** + * Change property name for 2009 spec + */ + prefixed(prop, prefix) { + let spec + ;[spec, prefix] = flexSpec(prefix) + if (spec === 2009) { + return prefix + 'box-flex' + } + return super.prefixed(prop, prefix) + } + + /** + * Spec 2009 supports only first argument + * Spec 2012 disallows unitless basis + */ + set(decl, prefix) { + let spec = flexSpec(prefix)[0] + if (spec === 2009) { + decl.value = list.space(decl.value)[0] + decl.value = Flex.oldValues[decl.value] || decl.value + return super.set(decl, prefix) + } + if (spec === 2012) { + let components = list.space(decl.value) + if (components.length === 3 && components[2] === '0') { + decl.value = components.slice(0, 2).concat('0px').join(' ') + } + } + return super.set(decl, prefix) + } +} + +Flex.names = ['flex', 'box-flex'] + +Flex.oldValues = { + auto: '1', + none: '0' +} + +module.exports = Flex diff --git a/client/node_modules/autoprefixer/lib/hacks/fullscreen.js b/client/node_modules/autoprefixer/lib/hacks/fullscreen.js new file mode 100644 index 0000000..5a74390 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/fullscreen.js @@ -0,0 +1,20 @@ +let Selector = require('../selector') + +class Fullscreen extends Selector { + /** + * Return different selectors depend on prefix + */ + prefixed(prefix) { + if (prefix === '-webkit-') { + return ':-webkit-full-screen' + } + if (prefix === '-moz-') { + return ':-moz-full-screen' + } + return `:${prefix}fullscreen` + } +} + +Fullscreen.names = [':fullscreen'] + +module.exports = Fullscreen diff --git a/client/node_modules/autoprefixer/lib/hacks/gradient.js b/client/node_modules/autoprefixer/lib/hacks/gradient.js new file mode 100644 index 0000000..fa26e24 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/gradient.js @@ -0,0 +1,450 @@ +let parser = require('postcss-value-parser') + +let OldValue = require('../old-value') +let utils = require('../utils') +let Value = require('../value') + +const IS_DIRECTION = /top|left|right|bottom/gi + +class Gradient extends Value { + /** + * Do not add non-webkit prefixes for list-style and object + */ + add(decl, prefix) { + let p = decl.prop + if (p.includes('mask')) { + if (prefix === '-webkit-' || prefix === '-webkit- old') { + return super.add(decl, prefix) + } + } else if ( + p === 'list-style' || + p === 'list-style-image' || + p === 'content' + ) { + if (prefix === '-webkit-' || prefix === '-webkit- old') { + return super.add(decl, prefix) + } + } else { + return super.add(decl, prefix) + } + return undefined + } + + /** + * Get div token from exists parameters + */ + cloneDiv(params) { + for (let i of params) { + if (i.type === 'div' && i.value === ',') { + return i + } + } + return { after: ' ', type: 'div', value: ',' } + } + + /** + * Change colors syntax to old webkit + */ + colorStops(params) { + let result = [] + for (let i = 0; i < params.length; i++) { + let pos + let param = params[i] + let item + if (i === 0) { + continue + } + + let color = parser.stringify(param[0]) + if (param[1] && param[1].type === 'word') { + pos = param[1].value + } else if (param[2] && param[2].type === 'word') { + pos = param[2].value + } + + let stop + if (i === 1 && (!pos || pos === '0%')) { + stop = `from(${color})` + } else if (i === params.length - 1 && (!pos || pos === '100%')) { + stop = `to(${color})` + } else if (pos) { + stop = `color-stop(${pos}, ${color})` + } else { + stop = `color-stop(${color})` + } + + let div = param[param.length - 1] + params[i] = [{ type: 'word', value: stop }] + if (div.type === 'div' && div.value === ',') { + item = params[i].push(div) + } + result.push(item) + } + return result + } + + /** + * Change new direction to old + */ + convertDirection(params) { + if (params.length > 0) { + if (params[0].value === 'to') { + this.fixDirection(params) + } else if (params[0].value.includes('deg')) { + this.fixAngle(params) + } else if (this.isRadial(params)) { + this.fixRadial(params) + } + } + return params + } + + /** + * Add 90 degrees + */ + fixAngle(params) { + let first = params[0].value + first = parseFloat(first) + first = Math.abs(450 - first) % 360 + first = this.roundFloat(first, 3) + params[0].value = `${first}deg` + } + + /** + * Replace `to top left` to `bottom right` + */ + fixDirection(params) { + params.splice(0, 2) + + for (let param of params) { + if (param.type === 'div') { + break + } + if (param.type === 'word') { + param.value = this.revertDirection(param.value) + } + } + } + + /** + * Fix radial direction syntax + */ + fixRadial(params) { + let first = [] + let second = [] + let a, b, c, i, next + + for (i = 0; i < params.length - 2; i++) { + a = params[i] + b = params[i + 1] + c = params[i + 2] + if (a.type === 'space' && b.value === 'at' && c.type === 'space') { + next = i + 3 + break + } else { + first.push(a) + } + } + + let div + for (i = next; i < params.length; i++) { + if (params[i].type === 'div') { + div = params[i] + break + } else { + second.push(params[i]) + } + } + + params.splice(0, i, ...second, div, ...first) + } + + /** + * Look for at word + */ + isRadial(params) { + let state = 'before' + for (let param of params) { + if (state === 'before' && param.type === 'space') { + state = 'at' + } else if (state === 'at' && param.value === 'at') { + state = 'after' + } else if (state === 'after' && param.type === 'space') { + return true + } else if (param.type === 'div') { + break + } else { + state = 'before' + } + } + return false + } + + /** + * Replace old direction to new + */ + newDirection(params) { + if (params[0].value === 'to') { + return params + } + IS_DIRECTION.lastIndex = 0 // reset search index of global regexp + if (!IS_DIRECTION.test(params[0].value)) { + return params + } + + params.unshift( + { + type: 'word', + value: 'to' + }, + { + type: 'space', + value: ' ' + } + ) + + for (let i = 2; i < params.length; i++) { + if (params[i].type === 'div') { + break + } + if (params[i].type === 'word') { + params[i].value = this.revertDirection(params[i].value) + } + } + + return params + } + + /** + * Normalize angle + */ + normalize(nodes, gradientName) { + if (!nodes[0]) return nodes + + if (/-?\d+(.\d+)?grad/.test(nodes[0].value)) { + nodes[0].value = this.normalizeUnit(nodes[0].value, 400) + } else if (/-?\d+(.\d+)?rad/.test(nodes[0].value)) { + nodes[0].value = this.normalizeUnit(nodes[0].value, 2 * Math.PI) + } else if (/-?\d+(.\d+)?turn/.test(nodes[0].value)) { + nodes[0].value = this.normalizeUnit(nodes[0].value, 1) + } else if (nodes[0].value.includes('deg')) { + let num = parseFloat(nodes[0].value) + num = ((num % 360) + 360) % 360 + nodes[0].value = `${num}deg` + } + + if ( + gradientName === 'linear-gradient' || + gradientName === 'repeating-linear-gradient' + ) { + let direction = nodes[0].value + + // Unitless zero for `` values are allowed in CSS gradients and transforms. + // Spec: https://github.com/w3c/csswg-drafts/commit/602789171429b2231223ab1e5acf8f7f11652eb3 + if (direction === '0deg' || direction === '0') { + nodes = this.replaceFirst(nodes, 'to', ' ', 'top') + } else if (direction === '90deg') { + nodes = this.replaceFirst(nodes, 'to', ' ', 'right') + } else if (direction === '180deg') { + nodes = this.replaceFirst(nodes, 'to', ' ', 'bottom') // default value + } else if (direction === '270deg') { + nodes = this.replaceFirst(nodes, 'to', ' ', 'left') + } + } + + return nodes + } + + /** + * Convert angle unit to deg + */ + normalizeUnit(str, full) { + let num = parseFloat(str) + let deg = (num / full) * 360 + return `${deg}deg` + } + + /** + * Remove old WebKit gradient too + */ + old(prefix) { + if (prefix === '-webkit-') { + let type + if (this.name === 'linear-gradient') { + type = 'linear' + } else if (this.name === 'repeating-linear-gradient') { + type = 'repeating-linear' + } else if (this.name === 'repeating-radial-gradient') { + type = 'repeating-radial' + } else { + type = 'radial' + } + let string = '-gradient' + let regexp = utils.regexp( + `-webkit-(${type}-gradient|gradient\\(\\s*${type})`, + false + ) + + return new OldValue(this.name, prefix + this.name, string, regexp) + } else { + return super.old(prefix) + } + } + + /** + * Change direction syntax to old webkit + */ + oldDirection(params) { + let div = this.cloneDiv(params[0]) + + if (params[0][0].value !== 'to') { + return params.unshift([ + { type: 'word', value: Gradient.oldDirections.bottom }, + div + ]) + } else { + let words = [] + for (let node of params[0].slice(2)) { + if (node.type === 'word') { + words.push(node.value.toLowerCase()) + } + } + + words = words.join(' ') + let old = Gradient.oldDirections[words] || words + + params[0] = [{ type: 'word', value: old }, div] + return params[0] + } + } + + /** + * Convert to old webkit syntax + */ + oldWebkit(node) { + let { nodes } = node + let string = parser.stringify(node.nodes) + + if (this.name !== 'linear-gradient') { + return false + } + if (nodes[0] && nodes[0].value.includes('deg')) { + return false + } + if ( + string.includes('px') || + string.includes('-corner') || + string.includes('-side') + ) { + return false + } + if (string.includes('var(')) { + return false + } + + let params = [[]] + for (let i of nodes) { + params[params.length - 1].push(i) + if (i.type === 'div' && i.value === ',') { + params.push([]) + } + } + + this.oldDirection(params) + this.colorStops(params) + + node.nodes = [] + for (let param of params) { + node.nodes.push(...param) + } + + node.nodes.unshift( + { type: 'word', value: 'linear' }, + this.cloneDiv(node.nodes) + ) + node.value = '-webkit-gradient' + + return true + } + + /** + * Change degrees for webkit prefix + */ + replace(string, prefix) { + let ast = parser(string) + for (let node of ast.nodes) { + let gradientName = this.name // gradient name + if (node.type === 'function' && node.value === gradientName) { + node.nodes = this.newDirection(node.nodes) + node.nodes = this.normalize(node.nodes, gradientName) + if (prefix === '-webkit- old') { + let changes = this.oldWebkit(node) + if (!changes) { + return false + } + } else { + node.nodes = this.convertDirection(node.nodes) + node.value = prefix + node.value + } + } + } + return ast.toString() + } + + /** + * Replace first token + */ + replaceFirst(params, ...words) { + let prefix = words.map(i => { + if (i === ' ') { + return { type: 'space', value: i } + } + return { type: 'word', value: i } + }) + return prefix.concat(params.slice(1)) + } + + revertDirection(word) { + return Gradient.directions[word.toLowerCase()] || word + } + + /** + * Round float and save digits under dot + */ + roundFloat(float, digits) { + return parseFloat(float.toFixed(digits)) + } +} + +Gradient.names = [ + 'linear-gradient', + 'repeating-linear-gradient', + 'radial-gradient', + 'repeating-radial-gradient' +] + +Gradient.directions = { + bottom: 'top', + left: 'right', + right: 'left', + top: 'bottom' // default value +} + +// Direction to replace +Gradient.oldDirections = { + 'bottom': 'left top, left bottom', + 'bottom left': 'right top, left bottom', + 'bottom right': 'left top, right bottom', + 'left': 'right top, left top', + + 'left bottom': 'right top, left bottom', + 'left top': 'right bottom, left top', + 'right': 'left top, right top', + 'right bottom': 'left top, right bottom', + 'right top': 'left bottom, right top', + 'top': 'left bottom, left top', + 'top left': 'right bottom, left top', + 'top right': 'left bottom, right top' +} + +module.exports = Gradient diff --git a/client/node_modules/autoprefixer/lib/hacks/grid-area.js b/client/node_modules/autoprefixer/lib/hacks/grid-area.js new file mode 100644 index 0000000..0a2d86c --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/grid-area.js @@ -0,0 +1,34 @@ +let Declaration = require('../declaration') +let utils = require('./grid-utils') + +class GridArea extends Declaration { + /** + * Translate grid-area to separate -ms- prefixed properties + */ + insert(decl, prefix, prefixes, result) { + if (prefix !== '-ms-') return super.insert(decl, prefix, prefixes) + + let values = utils.parse(decl) + + let [rowStart, rowSpan] = utils.translate(values, 0, 2) + let [columnStart, columnSpan] = utils.translate(values, 1, 3) + + ;[ + ['grid-row', rowStart], + ['grid-row-span', rowSpan], + ['grid-column', columnStart], + ['grid-column-span', columnSpan] + ].forEach(([prop, value]) => { + utils.insertDecl(decl, prop, value) + }) + + utils.warnTemplateSelectorNotFound(decl, result) + utils.warnIfGridRowColumnExists(decl, result) + + return undefined + } +} + +GridArea.names = ['grid-area'] + +module.exports = GridArea diff --git a/client/node_modules/autoprefixer/lib/hacks/grid-column-align.js b/client/node_modules/autoprefixer/lib/hacks/grid-column-align.js new file mode 100644 index 0000000..91f10f0 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/grid-column-align.js @@ -0,0 +1,28 @@ +let Declaration = require('../declaration') + +class GridColumnAlign extends Declaration { + /** + * Do not prefix flexbox values + */ + check(decl) { + return !decl.value.includes('flex-') && decl.value !== 'baseline' + } + + /** + * Change IE property back + */ + normalize() { + return 'justify-self' + } + + /** + * Change property name for IE + */ + prefixed(prop, prefix) { + return prefix + 'grid-column-align' + } +} + +GridColumnAlign.names = ['grid-column-align'] + +module.exports = GridColumnAlign diff --git a/client/node_modules/autoprefixer/lib/hacks/grid-end.js b/client/node_modules/autoprefixer/lib/hacks/grid-end.js new file mode 100644 index 0000000..63f6a42 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/grid-end.js @@ -0,0 +1,52 @@ +let Declaration = require('../declaration') +let { isPureNumber } = require('../utils') + +class GridEnd extends Declaration { + /** + * Change repeating syntax for IE + */ + insert(decl, prefix, prefixes, result) { + if (prefix !== '-ms-') return super.insert(decl, prefix, prefixes) + + let clonedDecl = this.clone(decl) + + let startProp = decl.prop.replace(/end$/, 'start') + let spanProp = prefix + decl.prop.replace(/end$/, 'span') + + if (decl.parent.some(i => i.prop === spanProp)) { + return undefined + } + + clonedDecl.prop = spanProp + + if (decl.value.includes('span')) { + clonedDecl.value = decl.value.replace(/span\s/i, '') + } else { + let startDecl + decl.parent.walkDecls(startProp, d => { + startDecl = d + }) + if (startDecl) { + if (isPureNumber(startDecl.value)) { + let value = Number(decl.value) - Number(startDecl.value) + '' + clonedDecl.value = value + } else { + return undefined + } + } else { + decl.warn( + result, + `Can not prefix ${decl.prop} (${startProp} is not found)` + ) + } + } + + decl.cloneBefore(clonedDecl) + + return undefined + } +} + +GridEnd.names = ['grid-row-end', 'grid-column-end'] + +module.exports = GridEnd diff --git a/client/node_modules/autoprefixer/lib/hacks/grid-row-align.js b/client/node_modules/autoprefixer/lib/hacks/grid-row-align.js new file mode 100644 index 0000000..cba8aee --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/grid-row-align.js @@ -0,0 +1,28 @@ +let Declaration = require('../declaration') + +class GridRowAlign extends Declaration { + /** + * Do not prefix flexbox values + */ + check(decl) { + return !decl.value.includes('flex-') && decl.value !== 'baseline' + } + + /** + * Change IE property back + */ + normalize() { + return 'align-self' + } + + /** + * Change property name for IE + */ + prefixed(prop, prefix) { + return prefix + 'grid-row-align' + } +} + +GridRowAlign.names = ['grid-row-align'] + +module.exports = GridRowAlign diff --git a/client/node_modules/autoprefixer/lib/hacks/grid-row-column.js b/client/node_modules/autoprefixer/lib/hacks/grid-row-column.js new file mode 100644 index 0000000..2199f78 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/grid-row-column.js @@ -0,0 +1,33 @@ +let Declaration = require('../declaration') +let utils = require('./grid-utils') + +class GridRowColumn extends Declaration { + /** + * Translate grid-row / grid-column to separate -ms- prefixed properties + */ + insert(decl, prefix, prefixes) { + if (prefix !== '-ms-') return super.insert(decl, prefix, prefixes) + + let values = utils.parse(decl) + let [start, span] = utils.translate(values, 0, 1) + + let hasStartValueSpan = values[0] && values[0].includes('span') + + if (hasStartValueSpan) { + span = values[0].join('').replace(/\D/g, '') + } + + ;[ + [decl.prop, start], + [`${decl.prop}-span`, span] + ].forEach(([prop, value]) => { + utils.insertDecl(decl, prop, value) + }) + + return undefined + } +} + +GridRowColumn.names = ['grid-row', 'grid-column'] + +module.exports = GridRowColumn diff --git a/client/node_modules/autoprefixer/lib/hacks/grid-rows-columns.js b/client/node_modules/autoprefixer/lib/hacks/grid-rows-columns.js new file mode 100644 index 0000000..f873f35 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/grid-rows-columns.js @@ -0,0 +1,125 @@ +let Declaration = require('../declaration') +let Processor = require('../processor') +let { + autoplaceGridItems, + getGridGap, + inheritGridGap, + prefixTrackProp, + prefixTrackValue +} = require('./grid-utils') + +class GridRowsColumns extends Declaration { + insert(decl, prefix, prefixes, result) { + if (prefix !== '-ms-') return super.insert(decl, prefix, prefixes) + + let { parent, prop, value } = decl + let isRowProp = prop.includes('rows') + let isColumnProp = prop.includes('columns') + + let hasGridTemplate = parent.some( + i => i.prop === 'grid-template' || i.prop === 'grid-template-areas' + ) + + /** + * Not to prefix rows declaration if grid-template(-areas) is present + */ + if (hasGridTemplate && isRowProp) { + return false + } + + let processor = new Processor({ options: {} }) + let status = processor.gridStatus(parent, result) + let gap = getGridGap(decl) + gap = inheritGridGap(decl, gap) || gap + + let gapValue = isRowProp ? gap.row : gap.column + + if ((status === 'no-autoplace' || status === true) && !hasGridTemplate) { + gapValue = null + } + + let prefixValue = prefixTrackValue({ + gap: gapValue, + value + }) + + /** + * Insert prefixes + */ + decl.cloneBefore({ + prop: prefixTrackProp({ prefix, prop }), + value: prefixValue + }) + + let autoflow = parent.nodes.find(i => i.prop === 'grid-auto-flow') + let autoflowValue = 'row' + + if (autoflow && !processor.disabled(autoflow, result)) { + autoflowValue = autoflow.value.trim() + } + if (status === 'autoplace') { + /** + * Show warning if grid-template-rows decl is not found + */ + let rowDecl = parent.nodes.find(i => i.prop === 'grid-template-rows') + + if (!rowDecl && hasGridTemplate) { + return undefined + } else if (!rowDecl && !hasGridTemplate) { + decl.warn( + result, + 'Autoplacement does not work without grid-template-rows property' + ) + return undefined + } + + /** + * Show warning if grid-template-columns decl is not found + */ + let columnDecl = parent.nodes.find(i => { + return i.prop === 'grid-template-columns' + }) + if (!columnDecl && !hasGridTemplate) { + decl.warn( + result, + 'Autoplacement does not work without grid-template-columns property' + ) + } + + /** + * Autoplace grid items + */ + if (isColumnProp && !hasGridTemplate) { + autoplaceGridItems(decl, result, gap, autoflowValue) + } + } + + return undefined + } + + /** + * Change IE property back + */ + normalize(prop) { + return prop.replace(/^grid-(rows|columns)/, 'grid-template-$1') + } + + /** + * Change property name for IE + */ + prefixed(prop, prefix) { + if (prefix === '-ms-') { + return prefixTrackProp({ prefix, prop }) + } + return super.prefixed(prop, prefix) + } +} + +GridRowsColumns.names = [ + 'grid-template-rows', + 'grid-template-columns', + 'grid-rows', + 'grid-columns' +] + +module.exports = GridRowsColumns diff --git a/client/node_modules/autoprefixer/lib/hacks/grid-start.js b/client/node_modules/autoprefixer/lib/hacks/grid-start.js new file mode 100644 index 0000000..32cebc1 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/grid-start.js @@ -0,0 +1,33 @@ +let Declaration = require('../declaration') + +class GridStart extends Declaration { + /** + * Do not add prefix for unsupported value in IE + */ + check(decl) { + let value = decl.value + return !value.includes('/') && !value.includes('span') + } + + /** + * Return a final spec property + */ + normalize(prop) { + return prop.replace('-start', '') + } + + /** + * Change property name for IE + */ + prefixed(prop, prefix) { + let result = super.prefixed(prop, prefix) + if (prefix === '-ms-') { + result = result.replace('-start', '') + } + return result + } +} + +GridStart.names = ['grid-row-start', 'grid-column-start'] + +module.exports = GridStart diff --git a/client/node_modules/autoprefixer/lib/hacks/grid-template-areas.js b/client/node_modules/autoprefixer/lib/hacks/grid-template-areas.js new file mode 100644 index 0000000..ffc9673 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/grid-template-areas.js @@ -0,0 +1,84 @@ +let Declaration = require('../declaration') +let { + getGridGap, + inheritGridGap, + parseGridAreas, + prefixTrackProp, + prefixTrackValue, + warnGridGap, + warnMissedAreas +} = require('./grid-utils') + +function getGridRows(tpl) { + return tpl + .trim() + .slice(1, -1) + .split(/["']\s*["']?/g) +} + +class GridTemplateAreas extends Declaration { + /** + * Translate grid-template-areas to separate -ms- prefixed properties + */ + insert(decl, prefix, prefixes, result) { + if (prefix !== '-ms-') return super.insert(decl, prefix, prefixes) + + let hasColumns = false + let hasRows = false + let parent = decl.parent + let gap = getGridGap(decl) + gap = inheritGridGap(decl, gap) || gap + + // remove already prefixed rows + // to prevent doubling prefixes + parent.walkDecls(/-ms-grid-rows/, i => i.remove()) + + // add empty tracks to rows + parent.walkDecls(/grid-template-(rows|columns)/, trackDecl => { + if (trackDecl.prop === 'grid-template-rows') { + hasRows = true + let { prop, value } = trackDecl + trackDecl.cloneBefore({ + prop: prefixTrackProp({ prefix, prop }), + value: prefixTrackValue({ gap: gap.row, value }) + }) + } else { + hasColumns = true + } + }) + + let gridRows = getGridRows(decl.value) + + if (hasColumns && !hasRows && gap.row && gridRows.length > 1) { + decl.cloneBefore({ + prop: '-ms-grid-rows', + raws: {}, + value: prefixTrackValue({ + gap: gap.row, + value: `repeat(${gridRows.length}, auto)` + }) + }) + } + + // warnings + warnGridGap({ + decl, + gap, + hasColumns, + result + }) + + let areas = parseGridAreas({ + gap, + rows: gridRows + }) + + warnMissedAreas(areas, decl, result) + + return decl + } +} + +GridTemplateAreas.names = ['grid-template-areas'] + +module.exports = GridTemplateAreas diff --git a/client/node_modules/autoprefixer/lib/hacks/grid-template.js b/client/node_modules/autoprefixer/lib/hacks/grid-template.js new file mode 100644 index 0000000..4e28637 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/grid-template.js @@ -0,0 +1,69 @@ +let Declaration = require('../declaration') +let { + getGridGap, + inheritGridGap, + parseTemplate, + warnGridGap, + warnMissedAreas +} = require('./grid-utils') + +class GridTemplate extends Declaration { + /** + * Translate grid-template to separate -ms- prefixed properties + */ + insert(decl, prefix, prefixes, result) { + if (prefix !== '-ms-') return super.insert(decl, prefix, prefixes) + + if (decl.parent.some(i => i.prop === '-ms-grid-rows')) { + return undefined + } + + let gap = getGridGap(decl) + + /** + * we must insert inherited gap values in some cases: + * if we are inside media query && if we have no grid-gap value + */ + let inheritedGap = inheritGridGap(decl, gap) + + let { areas, columns, rows } = parseTemplate({ + decl, + gap: inheritedGap || gap + }) + + let hasAreas = Object.keys(areas).length > 0 + let hasRows = Boolean(rows) + let hasColumns = Boolean(columns) + + warnGridGap({ + decl, + gap, + hasColumns, + result + }) + + warnMissedAreas(areas, decl, result) + + if ((hasRows && hasColumns) || hasAreas) { + decl.cloneBefore({ + prop: '-ms-grid-rows', + raws: {}, + value: rows + }) + } + + if (hasColumns) { + decl.cloneBefore({ + prop: '-ms-grid-columns', + raws: {}, + value: columns + }) + } + + return decl + } +} + +GridTemplate.names = ['grid-template'] + +module.exports = GridTemplate diff --git a/client/node_modules/autoprefixer/lib/hacks/grid-utils.js b/client/node_modules/autoprefixer/lib/hacks/grid-utils.js new file mode 100644 index 0000000..d423bfc --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/grid-utils.js @@ -0,0 +1,1117 @@ +let parser = require('postcss-value-parser') +let list = require('postcss').list + +let uniq = require('../utils').uniq +let escapeRegexp = require('../utils').escapeRegexp +let splitSelector = require('../utils').splitSelector + +function convert(value) { + if ( + value && + value.length === 2 && + value[0] === 'span' && + parseInt(value[1], 10) > 0 + ) { + return [false, parseInt(value[1], 10)] + } + + if (value && value.length === 1 && parseInt(value[0], 10) > 0) { + return [parseInt(value[0], 10), false] + } + + return [false, false] +} + +exports.translate = translate + +function translate(values, startIndex, endIndex) { + let startValue = values[startIndex] + let endValue = values[endIndex] + + if (!startValue) { + return [false, false] + } + + let [start, spanStart] = convert(startValue) + let [end, spanEnd] = convert(endValue) + + if (start && !endValue) { + return [start, false] + } + + if (spanStart && end) { + return [end - spanStart, spanStart] + } + + if (start && spanEnd) { + return [start, spanEnd] + } + + if (start && end) { + return [start, end - start] + } + + return [false, false] +} + +exports.parse = parse + +function parse(decl) { + let node = parser(decl.value) + + let values = [] + let current = 0 + values[current] = [] + + for (let i of node.nodes) { + if (i.type === 'div') { + current += 1 + values[current] = [] + } else if (i.type === 'word') { + values[current].push(i.value) + } + } + + return values +} + +exports.insertDecl = insertDecl + +function insertDecl(decl, prop, value) { + if (value && !decl.parent.some(i => i.prop === `-ms-${prop}`)) { + decl.cloneBefore({ + prop: `-ms-${prop}`, + value: value.toString() + }) + } +} + +// Track transforms + +exports.prefixTrackProp = prefixTrackProp + +function prefixTrackProp({ prefix, prop }) { + return prefix + prop.replace('template-', '') +} + +function transformRepeat({ nodes }, { gap }) { + let { count, size } = nodes.reduce( + (result, node) => { + if (node.type === 'div' && node.value === ',') { + result.key = 'size' + } else { + result[result.key].push(parser.stringify(node)) + } + return result + }, + { + count: [], + key: 'count', + size: [] + } + ) + + // insert gap values + if (gap) { + size = size.filter(i => i.trim()) + let val = [] + for (let i = 1; i <= count; i++) { + size.forEach((item, index) => { + if (index > 0 || i > 1) { + val.push(gap) + } + val.push(item) + }) + } + + return val.join(' ') + } + + return `(${size.join('')})[${count.join('')}]` +} + +exports.prefixTrackValue = prefixTrackValue + +function prefixTrackValue({ gap, value }) { + let result = parser(value).nodes.reduce((nodes, node) => { + if (node.type === 'function' && node.value === 'repeat') { + nodes.push({ + type: 'word', + value: transformRepeat(node, { gap }) + }) + return nodes + } + if (gap && node.type === 'space') { + nodes.push( + { + type: 'space', + value: ' ' + }, + { + type: 'word', + value: gap + }, + node + ) + return nodes + } + nodes.push(node) + return nodes + }, []) + + return parser.stringify(result) +} + +// Parse grid-template-areas + +const DOTS = /^\.+$/ + +function track(start, end) { + return { end, span: end - start, start } +} + +function getColumns(line) { + return line.trim().split(/\s+/g) +} + +exports.parseGridAreas = parseGridAreas + +function parseGridAreas({ gap, rows }) { + return rows.reduce((areas, line, rowIndex) => { + if (gap.row) rowIndex *= 2 + + if (line.trim() === '') return areas + + getColumns(line).forEach((area, columnIndex) => { + if (DOTS.test(area)) return + + if (gap.column) columnIndex *= 2 + + if (typeof areas[area] === 'undefined') { + areas[area] = { + column: track(columnIndex + 1, columnIndex + 2), + row: track(rowIndex + 1, rowIndex + 2) + } + } else { + let { column, row } = areas[area] + + column.start = Math.min(column.start, columnIndex + 1) + column.end = Math.max(column.end, columnIndex + 2) + column.span = column.end - column.start + + row.start = Math.min(row.start, rowIndex + 1) + row.end = Math.max(row.end, rowIndex + 2) + row.span = row.end - row.start + } + }) + + return areas + }, {}) +} + +// Parse grid-template + +function testTrack(node) { + return node.type === 'word' && /^\[.+]$/.test(node.value) +} + +function verifyRowSize(result) { + if (result.areas.length > result.rows.length) { + result.rows.push('auto') + } + return result +} + +exports.parseTemplate = parseTemplate + +function parseTemplate({ decl, gap }) { + let gridTemplate = parser(decl.value).nodes.reduce( + (result, node) => { + let { type, value } = node + + if (testTrack(node) || type === 'space') return result + + // area + if (type === 'string') { + result = verifyRowSize(result) + result.areas.push(value) + } + + // values and function + if (type === 'word' || type === 'function') { + result[result.key].push(parser.stringify(node)) + } + + // divider(/) + if (type === 'div' && value === '/') { + result.key = 'columns' + result = verifyRowSize(result) + } + + return result + }, + { + areas: [], + columns: [], + key: 'rows', + rows: [] + } + ) + + return { + areas: parseGridAreas({ + gap, + rows: gridTemplate.areas + }), + columns: prefixTrackValue({ + gap: gap.column, + value: gridTemplate.columns.join(' ') + }), + rows: prefixTrackValue({ + gap: gap.row, + value: gridTemplate.rows.join(' ') + }) + } +} + +// Insert parsed grid areas + +/** + * Get an array of -ms- prefixed props and values + * @param {Object} [area] area object with column and row data + * @param {Boolean} [addRowSpan] should we add grid-column-row value? + * @param {Boolean} [addColumnSpan] should we add grid-column-span value? + * @return {Array} + */ +function getMSDecls(area, addRowSpan = false, addColumnSpan = false) { + let result = [ + { + prop: '-ms-grid-row', + value: String(area.row.start) + } + ] + if (area.row.span > 1 || addRowSpan) { + result.push({ + prop: '-ms-grid-row-span', + value: String(area.row.span) + }) + } + result.push({ + prop: '-ms-grid-column', + value: String(area.column.start) + }) + if (area.column.span > 1 || addColumnSpan) { + result.push({ + prop: '-ms-grid-column-span', + value: String(area.column.span) + }) + } + return result +} + +function getParentMedia(parent) { + if (parent.type === 'atrule' && parent.name === 'media') { + return parent + } + if (!parent.parent) { + return false + } + return getParentMedia(parent.parent) +} + +/** + * change selectors for rules with duplicate grid-areas. + * @param {Array} rules + * @param {Array} templateSelectors + * @return {Array} rules with changed selectors + */ +function changeDuplicateAreaSelectors(ruleSelectors, templateSelectors) { + ruleSelectors = ruleSelectors.map(selector => { + let selectorBySpace = list.space(selector) + let selectorByComma = list.comma(selector) + + if (selectorBySpace.length > selectorByComma.length) { + selector = selectorBySpace.slice(-1).join('') + } + return selector + }) + + return ruleSelectors.map(ruleSelector => { + let newSelector = templateSelectors.map((tplSelector, index) => { + let space = index === 0 ? '' : ' ' + return `${space}${tplSelector} > ${ruleSelector}` + }) + + return newSelector + }) +} + +/** + * check if selector of rules are equal + * @param {Rule} ruleA + * @param {Rule} ruleB + * @return {Boolean} + */ +function selectorsEqual(ruleA, ruleB) { + return ruleA.selectors.some(sel => { + return ruleB.selectors.includes(sel) + }) +} + +/** + * Parse data from all grid-template(-areas) declarations + * @param {Root} css css root + * @return {Object} parsed data + */ +function parseGridTemplatesData(css) { + let parsed = [] + + // we walk through every grid-template(-areas) declaration and store + // data with the same area names inside the item + css.walkDecls(/grid-template(-areas)?$/, d => { + let rule = d.parent + let media = getParentMedia(rule) + let gap = getGridGap(d) + let inheritedGap = inheritGridGap(d, gap) + let { areas } = parseTemplate({ decl: d, gap: inheritedGap || gap }) + let areaNames = Object.keys(areas) + + // skip node if it doesn't have areas + if (areaNames.length === 0) { + return true + } + + // check parsed array for item that include the same area names + // return index of that item + let index = parsed.reduce((acc, { allAreas }, idx) => { + let hasAreas = allAreas && areaNames.some(area => allAreas.includes(area)) + return hasAreas ? idx : acc + }, null) + + if (index !== null) { + // index is found, add the grid-template data to that item + let { allAreas, rules } = parsed[index] + + // check if rule has no duplicate area names + let hasNoDuplicates = rules.some(r => { + return r.hasDuplicates === false && selectorsEqual(r, rule) + }) + + let duplicatesFound = false + + // check need to gather all duplicate area names + let duplicateAreaNames = rules.reduce((acc, r) => { + if (!r.params && selectorsEqual(r, rule)) { + duplicatesFound = true + return r.duplicateAreaNames + } + if (!duplicatesFound) { + areaNames.forEach(name => { + if (r.areas[name]) { + acc.push(name) + } + }) + } + return uniq(acc) + }, []) + + // update grid-row/column-span values for areas with duplicate + // area names. @see #1084 and #1146 + rules.forEach(r => { + areaNames.forEach(name => { + let area = r.areas[name] + if (area && area.row.span !== areas[name].row.span) { + areas[name].row.updateSpan = true + } + + if (area && area.column.span !== areas[name].column.span) { + areas[name].column.updateSpan = true + } + }) + }) + + parsed[index].allAreas = uniq([...allAreas, ...areaNames]) + parsed[index].rules.push({ + areas, + duplicateAreaNames, + hasDuplicates: !hasNoDuplicates, + node: rule, + params: media.params, + selectors: rule.selectors + }) + } else { + // index is NOT found, push the new item to the parsed array + parsed.push({ + allAreas: areaNames, + areasCount: 0, + rules: [ + { + areas, + duplicateAreaNames: [], + duplicateRules: [], + hasDuplicates: false, + node: rule, + params: media.params, + selectors: rule.selectors + } + ] + }) + } + + return undefined + }) + + return parsed +} + +/** + * insert prefixed grid-area declarations + * @param {Root} css css root + * @param {Function} isDisabled check if the rule is disabled + * @return {void} + */ +exports.insertAreas = insertAreas + +function insertAreas(css, isDisabled) { + // parse grid-template declarations + let gridTemplatesData = parseGridTemplatesData(css) + + // return undefined if no declarations found + if (gridTemplatesData.length === 0) { + return undefined + } + + // we need to store the rules that we will insert later + let rulesToInsert = {} + + css.walkDecls('grid-area', gridArea => { + let gridAreaRule = gridArea.parent + let hasPrefixedRow = gridAreaRule.first.prop === '-ms-grid-row' + let gridAreaMedia = getParentMedia(gridAreaRule) + + if (isDisabled(gridArea)) { + return undefined + } + + let gridAreaRuleIndex = css.index(gridAreaMedia || gridAreaRule) + + let value = gridArea.value + // found the data that matches grid-area identifier + let data = gridTemplatesData.filter(d => d.allAreas.includes(value))[0] + + if (!data) { + return true + } + + let lastArea = data.allAreas[data.allAreas.length - 1] + let selectorBySpace = list.space(gridAreaRule.selector) + let selectorByComma = list.comma(gridAreaRule.selector) + let selectorIsComplex = + selectorBySpace.length > 1 && + selectorBySpace.length > selectorByComma.length + + // prevent doubling of prefixes + if (hasPrefixedRow) { + return false + } + + // create the empty object with the key as the last area name + // e.g if we have templates with "a b c" values, "c" will be the last area + if (!rulesToInsert[lastArea]) { + rulesToInsert[lastArea] = {} + } + + let lastRuleIsSet = false + + // walk through every grid-template rule data + for (let rule of data.rules) { + let area = rule.areas[value] + let hasDuplicateName = rule.duplicateAreaNames.includes(value) + + // if we can't find the area name, update lastRule and continue + if (!area) { + let lastRule = rulesToInsert[lastArea].lastRule + let lastRuleIndex + if (lastRule) { + lastRuleIndex = css.index(lastRule) + } else { + /* c8 ignore next 2 */ + lastRuleIndex = -1 + } + + if (gridAreaRuleIndex > lastRuleIndex) { + rulesToInsert[lastArea].lastRule = gridAreaMedia || gridAreaRule + } + continue + } + + // for grid-templates inside media rule we need to create empty + // array to push prefixed grid-area rules later + if (rule.params && !rulesToInsert[lastArea][rule.params]) { + rulesToInsert[lastArea][rule.params] = [] + } + + if ((!rule.hasDuplicates || !hasDuplicateName) && !rule.params) { + // grid-template has no duplicates and not inside media rule + + getMSDecls(area, false, false) + .reverse() + .forEach(i => + gridAreaRule.prepend( + Object.assign(i, { + raws: { + between: gridArea.raws.between + } + }) + ) + ) + + rulesToInsert[lastArea].lastRule = gridAreaRule + lastRuleIsSet = true + } else if (rule.hasDuplicates && !rule.params && !selectorIsComplex) { + // grid-template has duplicates and not inside media rule + let cloned = gridAreaRule.clone() + cloned.removeAll() + + getMSDecls(area, area.row.updateSpan, area.column.updateSpan) + .reverse() + .forEach(i => + cloned.prepend( + Object.assign(i, { + raws: { + between: gridArea.raws.between + } + }) + ) + ) + + cloned.selectors = changeDuplicateAreaSelectors( + cloned.selectors, + rule.selectors + ) + + if (rulesToInsert[lastArea].lastRule) { + rulesToInsert[lastArea].lastRule.after(cloned) + } + rulesToInsert[lastArea].lastRule = cloned + lastRuleIsSet = true + } else if ( + rule.hasDuplicates && + !rule.params && + selectorIsComplex && + gridAreaRule.selector.includes(rule.selectors[0]) + ) { + // grid-template has duplicates and not inside media rule + // and the selector is complex + gridAreaRule.walkDecls(/-ms-grid-(row|column)/, d => d.remove()) + getMSDecls(area, area.row.updateSpan, area.column.updateSpan) + .reverse() + .forEach(i => + gridAreaRule.prepend( + Object.assign(i, { + raws: { + between: gridArea.raws.between + } + }) + ) + ) + } else if (rule.params) { + // grid-template is inside media rule + // if we're inside media rule, we need to store prefixed rules + // inside rulesToInsert object to be able to preserve the order of media + // rules and merge them easily + let cloned = gridAreaRule.clone() + cloned.removeAll() + + getMSDecls(area, area.row.updateSpan, area.column.updateSpan) + .reverse() + .forEach(i => + cloned.prepend( + Object.assign(i, { + raws: { + between: gridArea.raws.between + } + }) + ) + ) + + if (rule.hasDuplicates && hasDuplicateName) { + cloned.selectors = changeDuplicateAreaSelectors( + cloned.selectors, + rule.selectors + ) + } + + cloned.raws = rule.node.raws + + if (css.index(rule.node.parent) > gridAreaRuleIndex) { + // append the prefixed rules right inside media rule + // with grid-template + rule.node.parent.append(cloned) + } else { + // store the rule to insert later + rulesToInsert[lastArea][rule.params].push(cloned) + } + + // set new rule as last rule ONLY if we didn't set lastRule for + // this grid-area before + if (!lastRuleIsSet) { + rulesToInsert[lastArea].lastRule = gridAreaMedia || gridAreaRule + } + } + } + + return undefined + }) + + // append stored rules inside the media rules + Object.keys(rulesToInsert).forEach(area => { + let data = rulesToInsert[area] + let lastRule = data.lastRule + Object.keys(data) + .reverse() + .filter(p => p !== 'lastRule') + .forEach(params => { + if (data[params].length > 0 && lastRule) { + lastRule.after({ name: 'media', params }) + lastRule.next().append(data[params]) + } + }) + }) + + return undefined +} + +/** + * Warn user if grid area identifiers are not found + * @param {Object} areas + * @param {Declaration} decl + * @param {Result} result + * @return {void} + */ +exports.warnMissedAreas = warnMissedAreas + +function warnMissedAreas(areas, decl, result) { + let missed = Object.keys(areas) + + decl.root().walkDecls('grid-area', gridArea => { + missed = missed.filter(e => e !== gridArea.value) + }) + + if (missed.length > 0) { + decl.warn(result, 'Can not find grid areas: ' + missed.join(', ')) + } + + return undefined +} + +/** + * compare selectors with grid-area rule and grid-template rule + * show warning if grid-template selector is not found + * (this function used for grid-area rule) + * @param {Declaration} decl + * @param {Result} result + * @return {void} + */ +exports.warnTemplateSelectorNotFound = warnTemplateSelectorNotFound + +function warnTemplateSelectorNotFound(decl, result) { + let rule = decl.parent + let root = decl.root() + let duplicatesFound = false + + // slice selector array. Remove the last part (for comparison) + let slicedSelectorArr = list + .space(rule.selector) + .filter(str => str !== '>') + .slice(0, -1) + + // we need to compare only if selector is complex. + // e.g '.grid-cell' is simple, but '.parent > .grid-cell' is complex + if (slicedSelectorArr.length > 0) { + let gridTemplateFound = false + let foundAreaSelector = null + + root.walkDecls(/grid-template(-areas)?$/, d => { + let parent = d.parent + let templateSelectors = parent.selectors + + let { areas } = parseTemplate({ decl: d, gap: getGridGap(d) }) + let hasArea = areas[decl.value] + + // find the the matching selectors + for (let tplSelector of templateSelectors) { + if (gridTemplateFound) { + break + } + let tplSelectorArr = list.space(tplSelector).filter(str => str !== '>') + + gridTemplateFound = tplSelectorArr.every( + (item, idx) => item === slicedSelectorArr[idx] + ) + } + + if (gridTemplateFound || !hasArea) { + return true + } + + if (!foundAreaSelector) { + foundAreaSelector = parent.selector + } + + // if we found the duplicate area with different selector + if (foundAreaSelector && foundAreaSelector !== parent.selector) { + duplicatesFound = true + } + + return undefined + }) + + // warn user if we didn't find template + if (!gridTemplateFound && duplicatesFound) { + decl.warn( + result, + 'Autoprefixer cannot find a grid-template ' + + `containing the duplicate grid-area "${decl.value}" ` + + `with full selector matching: ${slicedSelectorArr.join(' ')}` + ) + } + } +} + +/** + * warn user if both grid-area and grid-(row|column) + * declarations are present in the same rule + * @param {Declaration} decl + * @param {Result} result + * @return {void} + */ +exports.warnIfGridRowColumnExists = warnIfGridRowColumnExists + +function warnIfGridRowColumnExists(decl, result) { + let rule = decl.parent + let decls = [] + rule.walkDecls(/^grid-(row|column)/, d => { + if ( + !d.prop.endsWith('-end') && + !d.value.startsWith('span') && + !d.prop.endsWith('-gap') + ) { + decls.push(d) + } + }) + if (decls.length > 0) { + decls.forEach(d => { + d.warn( + result, + 'You already have a grid-area declaration present in the rule. ' + + `You should use either grid-area or ${d.prop}, not both` + ) + }) + } + + return undefined +} + +// Gap utils + +exports.getGridGap = getGridGap + +function getGridGap(decl) { + let gap = {} + + // try to find gap + let testGap = /^(grid-)?((row|column)-)?gap$/ + decl.parent.walkDecls(testGap, ({ prop, value }) => { + if (/^(grid-)?gap$/.test(prop)) { + let [row, , column] = parser(value).nodes + + gap.row = row && parser.stringify(row) + gap.column = column ? parser.stringify(column) : gap.row + } + if (/^(grid-)?row-gap$/.test(prop)) gap.row = value + if (/^(grid-)?column-gap$/.test(prop)) gap.column = value + }) + + return gap +} + +/** + * parse media parameters (for example 'min-width: 500px') + * @param {String} params parameter to parse + * @return {} + */ +function parseMediaParams(params) { + if (!params) { + return [] + } + let parsed = parser(params) + let prop + let value + + parsed.walk(node => { + if (node.type === 'word' && /min|max/g.test(node.value)) { + prop = node.value + } else if (node.value.includes('px')) { + value = parseInt(node.value.replace(/\D/g, '')) + } + }) + + return [prop, value] +} + +/** + * Compare the selectors and decide if we + * need to inherit gap from compared selector or not. + * @type {String} selA + * @type {String} selB + * @return {Boolean} + */ +function shouldInheritGap(selA, selB) { + let result + + // get arrays of selector split in 3-deep array + let splitSelectorArrA = splitSelector(selA) + let splitSelectorArrB = splitSelector(selB) + + if (splitSelectorArrA[0].length < splitSelectorArrB[0].length) { + // abort if selectorA has lower descendant specificity then selectorB + // (e.g '.grid' and '.hello .world .grid') + return false + } else if (splitSelectorArrA[0].length > splitSelectorArrB[0].length) { + // if selectorA has higher descendant specificity then selectorB + // (e.g '.foo .bar .grid' and '.grid') + + let idx = splitSelectorArrA[0].reduce((res, [item], index) => { + let firstSelectorPart = splitSelectorArrB[0][0][0] + if (item === firstSelectorPart) { + return index + } + return false + }, false) + + if (idx) { + result = splitSelectorArrB[0].every((arr, index) => { + return arr.every( + (part, innerIndex) => + // because selectorA has more space elements, we need to slice + // selectorA array by 'idx' number to compare them + splitSelectorArrA[0].slice(idx)[index][innerIndex] === part + ) + }) + } + } else { + // if selectorA has the same descendant specificity as selectorB + // this condition covers cases such as: '.grid.foo.bar' and '.grid' + result = splitSelectorArrB.some(byCommaArr => { + return byCommaArr.every((bySpaceArr, index) => { + return bySpaceArr.every( + (part, innerIndex) => splitSelectorArrA[0][index][innerIndex] === part + ) + }) + }) + } + + return result +} +/** + * inherit grid gap values from the closest rule above + * with the same selector + * @param {Declaration} decl + * @param {Object} gap gap values + * @return {Object | Boolean} return gap values or false (if not found) + */ +exports.inheritGridGap = inheritGridGap + +function inheritGridGap(decl, gap) { + let rule = decl.parent + let mediaRule = getParentMedia(rule) + let root = rule.root() + + // get an array of selector split in 3-deep array + let splitSelectorArr = splitSelector(rule.selector) + + // abort if the rule already has gaps + if (Object.keys(gap).length > 0) { + return false + } + + // e.g ['min-width'] + let [prop] = parseMediaParams(mediaRule.params) + + let lastBySpace = splitSelectorArr[0] + + // get escaped value from the selector + // if we have '.grid-2.foo.bar' selector, will be '\.grid\-2' + let escaped = escapeRegexp(lastBySpace[lastBySpace.length - 1][0]) + + let regexp = new RegExp(`(${escaped}$)|(${escaped}[,.])`) + + // find the closest rule with the same selector + let closestRuleGap + root.walkRules(regexp, r => { + let gridGap + + // abort if are checking the same rule + if (rule.toString() === r.toString()) { + return false + } + + // find grid-gap values + r.walkDecls('grid-gap', d => (gridGap = getGridGap(d))) + + // skip rule without gaps + if (!gridGap || Object.keys(gridGap).length === 0) { + return true + } + + // skip rules that should not be inherited from + if (!shouldInheritGap(rule.selector, r.selector)) { + return true + } + + let media = getParentMedia(r) + if (media) { + // if we are inside media, we need to check that media props match + // e.g ('min-width' === 'min-width') + let propToCompare = parseMediaParams(media.params)[0] + if (propToCompare === prop) { + closestRuleGap = gridGap + return true + } + } else { + closestRuleGap = gridGap + return true + } + + return undefined + }) + + // if we find the closest gap object + if (closestRuleGap && Object.keys(closestRuleGap).length > 0) { + return closestRuleGap + } + return false +} + +exports.warnGridGap = warnGridGap + +function warnGridGap({ decl, gap, hasColumns, result }) { + let hasBothGaps = gap.row && gap.column + if (!hasColumns && (hasBothGaps || (gap.column && !gap.row))) { + delete gap.column + decl.warn( + result, + 'Can not implement grid-gap without grid-template-columns' + ) + } +} + +/** + * normalize the grid-template-rows/columns values + * @param {String} str grid-template-rows/columns value + * @return {Array} normalized array with values + * @example + * let normalized = normalizeRowColumn('1fr repeat(2, 20px 50px) 1fr') + * normalized // <= ['1fr', '20px', '50px', '20px', '50px', '1fr'] + */ +function normalizeRowColumn(str) { + let normalized = parser(str).nodes.reduce((result, node) => { + if (node.type === 'function' && node.value === 'repeat') { + let key = 'count' + + let [count, value] = node.nodes.reduce( + (acc, n) => { + if (n.type === 'word' && key === 'count') { + acc[0] = Math.abs(parseInt(n.value)) + return acc + } + if (n.type === 'div' && n.value === ',') { + key = 'value' + return acc + } + if (key === 'value') { + acc[1] += parser.stringify(n) + } + return acc + }, + [0, ''] + ) + + if (count) { + for (let i = 0; i < count; i++) { + result.push(value) + } + } + + return result + } + if (node.type === 'space') { + return result + } + result.push(parser.stringify(node)) + return result + }, []) + + return normalized +} + +exports.autoplaceGridItems = autoplaceGridItems + +/** + * Autoplace grid items + * @param {Declaration} decl + * @param {Result} result + * @param {Object} gap gap values + * @param {String} autoflowValue grid-auto-flow value + * @return {void} + * @see https://github.com/postcss/autoprefixer/issues/1148 + */ +function autoplaceGridItems(decl, result, gap, autoflowValue = 'row') { + let { parent } = decl + + let rowDecl = parent.nodes.find(i => i.prop === 'grid-template-rows') + let rows = normalizeRowColumn(rowDecl.value) + let columns = normalizeRowColumn(decl.value) + + // Build array of area names with dummy values. If we have 3 columns and + // 2 rows, filledRows will be equal to ['1 2 3', '4 5 6'] + let filledRows = rows.map((_, rowIndex) => { + return Array.from( + { length: columns.length }, + (v, k) => k + rowIndex * columns.length + 1 + ).join(' ') + }) + + let areas = parseGridAreas({ gap, rows: filledRows }) + let keys = Object.keys(areas) + let items = keys.map(i => areas[i]) + + // Change the order of cells if grid-auto-flow value is 'column' + if (autoflowValue.includes('column')) { + items = items.sort((a, b) => a.column.start - b.column.start) + } + + // Insert new rules + items.reverse().forEach((item, index) => { + let { column, row } = item + let nodeSelector = parent.selectors + .map(sel => sel + ` > *:nth-child(${keys.length - index})`) + .join(', ') + + // create new rule + let node = parent.clone().removeAll() + + // change rule selector + node.selector = nodeSelector + + // insert prefixed row/column values + node.append({ prop: '-ms-grid-row', value: row.start }) + node.append({ prop: '-ms-grid-column', value: column.start }) + + // insert rule + parent.after(node) + }) + + return undefined +} diff --git a/client/node_modules/autoprefixer/lib/hacks/image-rendering.js b/client/node_modules/autoprefixer/lib/hacks/image-rendering.js new file mode 100644 index 0000000..38b571b --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/image-rendering.js @@ -0,0 +1,48 @@ +let Declaration = require('../declaration') + +class ImageRendering extends Declaration { + /** + * Add hack only for crisp-edges + */ + check(decl) { + return decl.value === 'pixelated' + } + + /** + * Return property name by spec + */ + normalize() { + return 'image-rendering' + } + + /** + * Change property name for IE + */ + prefixed(prop, prefix) { + if (prefix === '-ms-') { + return '-ms-interpolation-mode' + } + return super.prefixed(prop, prefix) + } + + /** + * Warn on old value + */ + process(node, result) { + return super.process(node, result) + } + + /** + * Change property and value for IE + */ + set(decl, prefix) { + if (prefix !== '-ms-') return super.set(decl, prefix) + decl.prop = '-ms-interpolation-mode' + decl.value = 'nearest-neighbor' + return decl + } +} + +ImageRendering.names = ['image-rendering', 'interpolation-mode'] + +module.exports = ImageRendering diff --git a/client/node_modules/autoprefixer/lib/hacks/image-set.js b/client/node_modules/autoprefixer/lib/hacks/image-set.js new file mode 100644 index 0000000..fecd088 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/image-set.js @@ -0,0 +1,18 @@ +let Value = require('../value') + +class ImageSet extends Value { + /** + * Use non-standard name for WebKit and Firefox + */ + replace(string, prefix) { + let fixed = super.replace(string, prefix) + if (prefix === '-webkit-') { + fixed = fixed.replace(/("[^"]+"|'[^']+')(\s+\d+\w)/gi, 'url($1)$2') + } + return fixed + } +} + +ImageSet.names = ['image-set'] + +module.exports = ImageSet diff --git a/client/node_modules/autoprefixer/lib/hacks/inline-logical.js b/client/node_modules/autoprefixer/lib/hacks/inline-logical.js new file mode 100644 index 0000000..31dc968 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/inline-logical.js @@ -0,0 +1,34 @@ +let Declaration = require('../declaration') + +class InlineLogical extends Declaration { + /** + * Return property name by spec + */ + normalize(prop) { + return prop.replace(/(margin|padding|border)-(start|end)/, '$1-inline-$2') + } + + /** + * Use old syntax for -moz- and -webkit- + */ + prefixed(prop, prefix) { + return prefix + prop.replace('-inline', '') + } +} + +InlineLogical.names = [ + 'border-inline-start', + 'border-inline-end', + 'margin-inline-start', + 'margin-inline-end', + 'padding-inline-start', + 'padding-inline-end', + 'border-start', + 'border-end', + 'margin-start', + 'margin-end', + 'padding-start', + 'padding-end' +] + +module.exports = InlineLogical diff --git a/client/node_modules/autoprefixer/lib/hacks/intrinsic.js b/client/node_modules/autoprefixer/lib/hacks/intrinsic.js new file mode 100644 index 0000000..7c5bb50 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/intrinsic.js @@ -0,0 +1,61 @@ +let OldValue = require('../old-value') +let Value = require('../value') + +function regexp(name) { + return new RegExp(`(^|[\\s,(])(${name}($|[\\s),]))`, 'gi') +} + +class Intrinsic extends Value { + add(decl, prefix) { + if (decl.prop.includes('grid') && prefix !== '-webkit-') { + return undefined + } + return super.add(decl, prefix) + } + + isStretch() { + return ( + this.name === 'stretch' || + this.name === 'fill' || + this.name === 'fill-available' + ) + } + + old(prefix) { + let prefixed = prefix + this.name + if (this.isStretch()) { + if (prefix === '-moz-') { + prefixed = '-moz-available' + } else if (prefix === '-webkit-') { + prefixed = '-webkit-fill-available' + } + } + return new OldValue(this.name, prefixed, prefixed, regexp(prefixed)) + } + + regexp() { + if (!this.regexpCache) this.regexpCache = regexp(this.name) + return this.regexpCache + } + + replace(string, prefix) { + if (prefix === '-moz-' && this.isStretch()) { + return string.replace(this.regexp(), '$1-moz-available$3') + } + if (prefix === '-webkit-' && this.isStretch()) { + return string.replace(this.regexp(), '$1-webkit-fill-available$3') + } + return super.replace(string, prefix) + } +} + +Intrinsic.names = [ + 'max-content', + 'min-content', + 'fit-content', + 'fill', + 'fill-available', + 'stretch' +] + +module.exports = Intrinsic diff --git a/client/node_modules/autoprefixer/lib/hacks/justify-content.js b/client/node_modules/autoprefixer/lib/hacks/justify-content.js new file mode 100644 index 0000000..fd954ba --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/justify-content.js @@ -0,0 +1,54 @@ +let Declaration = require('../declaration') +let flexSpec = require('./flex-spec') + +class JustifyContent extends Declaration { + /** + * Return property name by final spec + */ + normalize() { + return 'justify-content' + } + + /** + * Change property name for 2009 and 2012 specs + */ + prefixed(prop, prefix) { + let spec + ;[spec, prefix] = flexSpec(prefix) + if (spec === 2009) { + return prefix + 'box-pack' + } + if (spec === 2012) { + return prefix + 'flex-pack' + } + return super.prefixed(prop, prefix) + } + + /** + * Change value for 2009 and 2012 specs + */ + set(decl, prefix) { + let spec = flexSpec(prefix)[0] + if (spec === 2009 || spec === 2012) { + let value = JustifyContent.oldValues[decl.value] || decl.value + decl.value = value + if (spec !== 2009 || value !== 'distribute') { + return super.set(decl, prefix) + } + } else if (spec === 'final') { + return super.set(decl, prefix) + } + return undefined + } +} + +JustifyContent.names = ['justify-content', 'flex-pack', 'box-pack'] + +JustifyContent.oldValues = { + 'flex-end': 'end', + 'flex-start': 'start', + 'space-around': 'distribute', + 'space-between': 'justify' +} + +module.exports = JustifyContent diff --git a/client/node_modules/autoprefixer/lib/hacks/mask-border.js b/client/node_modules/autoprefixer/lib/hacks/mask-border.js new file mode 100644 index 0000000..d5efde2 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/mask-border.js @@ -0,0 +1,38 @@ +let Declaration = require('../declaration') + +class MaskBorder extends Declaration { + /** + * Return property name by final spec + */ + normalize() { + return this.name.replace('box-image', 'border') + } + + /** + * Return flex property for 2012 spec + */ + prefixed(prop, prefix) { + let result = super.prefixed(prop, prefix) + if (prefix === '-webkit-') { + result = result.replace('border', 'box-image') + } + return result + } +} + +MaskBorder.names = [ + 'mask-border', + 'mask-border-source', + 'mask-border-slice', + 'mask-border-width', + 'mask-border-outset', + 'mask-border-repeat', + 'mask-box-image', + 'mask-box-image-source', + 'mask-box-image-slice', + 'mask-box-image-width', + 'mask-box-image-outset', + 'mask-box-image-repeat' +] + +module.exports = MaskBorder diff --git a/client/node_modules/autoprefixer/lib/hacks/mask-composite.js b/client/node_modules/autoprefixer/lib/hacks/mask-composite.js new file mode 100644 index 0000000..a30df13 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/mask-composite.js @@ -0,0 +1,88 @@ +let Declaration = require('../declaration') + +class MaskComposite extends Declaration { + /** + * Prefix mask-composite for webkit + */ + insert(decl, prefix, prefixes) { + let isCompositeProp = decl.prop === 'mask-composite' + + let compositeValues + + if (isCompositeProp) { + compositeValues = decl.value.split(',') + } else { + compositeValues = decl.value.match(MaskComposite.regexp) || [] + } + + compositeValues = compositeValues.map(el => el.trim()).filter(el => el) + let hasCompositeValues = compositeValues.length + + let compositeDecl + + if (hasCompositeValues) { + compositeDecl = this.clone(decl) + compositeDecl.value = compositeValues + .map(value => MaskComposite.oldValues[value] || value) + .join(', ') + + if (compositeValues.includes('intersect')) { + compositeDecl.value += ', xor' + } + + compositeDecl.prop = prefix + 'mask-composite' + } + + if (isCompositeProp) { + if (!hasCompositeValues) { + return undefined + } + + if (this.needCascade(decl)) { + compositeDecl.raws.before = this.calcBefore(prefixes, decl, prefix) + } + + return decl.parent.insertBefore(decl, compositeDecl) + } + + let cloned = this.clone(decl) + cloned.prop = prefix + cloned.prop + + if (hasCompositeValues) { + cloned.value = cloned.value.replace(MaskComposite.regexp, '') + } + + if (this.needCascade(decl)) { + cloned.raws.before = this.calcBefore(prefixes, decl, prefix) + } + + decl.parent.insertBefore(decl, cloned) + + if (!hasCompositeValues) { + return decl + } + + if (this.needCascade(decl)) { + compositeDecl.raws.before = this.calcBefore(prefixes, decl, prefix) + } + return decl.parent.insertBefore(decl, compositeDecl) + } +} + +MaskComposite.names = ['mask', 'mask-composite'] + +MaskComposite.oldValues = { + add: 'source-over', + exclude: 'xor', + intersect: 'source-in', + subtract: 'source-out' +} + +MaskComposite.regexp = new RegExp( + `\\s+(${Object.keys(MaskComposite.oldValues).join( + '|' + )})\\b(?!\\))\\s*(?=[,])`, + 'ig' +) + +module.exports = MaskComposite diff --git a/client/node_modules/autoprefixer/lib/hacks/order.js b/client/node_modules/autoprefixer/lib/hacks/order.js new file mode 100644 index 0000000..d507afe --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/order.js @@ -0,0 +1,42 @@ +let Declaration = require('../declaration') +let flexSpec = require('./flex-spec') + +class Order extends Declaration { + /** + * Return property name by final spec + */ + normalize() { + return 'order' + } + + /** + * Change property name for 2009 and 2012 specs + */ + prefixed(prop, prefix) { + let spec + ;[spec, prefix] = flexSpec(prefix) + if (spec === 2009) { + return prefix + 'box-ordinal-group' + } + if (spec === 2012) { + return prefix + 'flex-order' + } + return super.prefixed(prop, prefix) + } + + /** + * Fix value for 2009 spec + */ + set(decl, prefix) { + let spec = flexSpec(prefix)[0] + if (spec === 2009 && /\d/.test(decl.value)) { + decl.value = (parseInt(decl.value) + 1).toString() + return super.set(decl, prefix) + } + return super.set(decl, prefix) + } +} + +Order.names = ['order', 'flex-order', 'box-ordinal-group'] + +module.exports = Order diff --git a/client/node_modules/autoprefixer/lib/hacks/overscroll-behavior.js b/client/node_modules/autoprefixer/lib/hacks/overscroll-behavior.js new file mode 100644 index 0000000..03bd7d4 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/overscroll-behavior.js @@ -0,0 +1,33 @@ +let Declaration = require('../declaration') + +class OverscrollBehavior extends Declaration { + /** + * Return property name by spec + */ + normalize() { + return 'overscroll-behavior' + } + + /** + * Change property name for IE + */ + prefixed(prop, prefix) { + return prefix + 'scroll-chaining' + } + + /** + * Change value for IE + */ + set(decl, prefix) { + if (decl.value === 'auto') { + decl.value = 'chained' + } else if (decl.value === 'none' || decl.value === 'contain') { + decl.value = 'none' + } + return super.set(decl, prefix) + } +} + +OverscrollBehavior.names = ['overscroll-behavior', 'scroll-chaining'] + +module.exports = OverscrollBehavior diff --git a/client/node_modules/autoprefixer/lib/hacks/pixelated.js b/client/node_modules/autoprefixer/lib/hacks/pixelated.js new file mode 100644 index 0000000..6084826 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/pixelated.js @@ -0,0 +1,34 @@ +let OldValue = require('../old-value') +let Value = require('../value') + +class Pixelated extends Value { + /** + * Different name for WebKit and Firefox + */ + old(prefix) { + if (prefix === '-webkit-') { + return new OldValue(this.name, '-webkit-optimize-contrast') + } + if (prefix === '-moz-') { + return new OldValue(this.name, '-moz-crisp-edges') + } + return super.old(prefix) + } + + /** + * Use non-standard name for WebKit and Firefox + */ + replace(string, prefix) { + if (prefix === '-webkit-') { + return string.replace(this.regexp(), '$1-webkit-optimize-contrast') + } + if (prefix === '-moz-') { + return string.replace(this.regexp(), '$1-moz-crisp-edges') + } + return super.replace(string, prefix) + } +} + +Pixelated.names = ['pixelated'] + +module.exports = Pixelated diff --git a/client/node_modules/autoprefixer/lib/hacks/place-self.js b/client/node_modules/autoprefixer/lib/hacks/place-self.js new file mode 100644 index 0000000..e0ce3e8 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/place-self.js @@ -0,0 +1,32 @@ +let Declaration = require('../declaration') +let utils = require('./grid-utils') + +class PlaceSelf extends Declaration { + /** + * Translate place-self to separate -ms- prefixed properties + */ + insert(decl, prefix, prefixes) { + if (prefix !== '-ms-') return super.insert(decl, prefix, prefixes) + + // prevent doubling of prefixes + if (decl.parent.some(i => i.prop === '-ms-grid-row-align')) { + return undefined + } + + let [[first, second]] = utils.parse(decl) + + if (second) { + utils.insertDecl(decl, 'grid-row-align', first) + utils.insertDecl(decl, 'grid-column-align', second) + } else { + utils.insertDecl(decl, 'grid-row-align', first) + utils.insertDecl(decl, 'grid-column-align', first) + } + + return undefined + } +} + +PlaceSelf.names = ['place-self'] + +module.exports = PlaceSelf diff --git a/client/node_modules/autoprefixer/lib/hacks/placeholder-shown.js b/client/node_modules/autoprefixer/lib/hacks/placeholder-shown.js new file mode 100644 index 0000000..c29525e --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/placeholder-shown.js @@ -0,0 +1,19 @@ +let Selector = require('../selector') + +class PlaceholderShown extends Selector { + /** + * Return different selectors depend on prefix + */ + prefixed(prefix) { + if (prefix === '-moz-') { + return ':-moz-placeholder' + } else if (prefix === '-ms-') { + return ':-ms-input-placeholder' + } + return `:${prefix}placeholder-shown` + } +} + +PlaceholderShown.names = [':placeholder-shown'] + +module.exports = PlaceholderShown diff --git a/client/node_modules/autoprefixer/lib/hacks/placeholder.js b/client/node_modules/autoprefixer/lib/hacks/placeholder.js new file mode 100644 index 0000000..45730a5 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/placeholder.js @@ -0,0 +1,33 @@ +let Selector = require('../selector') + +class Placeholder extends Selector { + /** + * Add old mozilla to possible prefixes + */ + possible() { + return super.possible().concat(['-moz- old', '-ms- old']) + } + + /** + * Return different selectors depend on prefix + */ + prefixed(prefix) { + if (prefix === '-webkit-') { + return '::-webkit-input-placeholder' + } + if (prefix === '-ms-') { + return '::-ms-input-placeholder' + } + if (prefix === '-ms- old') { + return ':-ms-input-placeholder' + } + if (prefix === '-moz- old') { + return ':-moz-placeholder' + } + return `::${prefix}placeholder` + } +} + +Placeholder.names = ['::placeholder'] + +module.exports = Placeholder diff --git a/client/node_modules/autoprefixer/lib/hacks/print-color-adjust.js b/client/node_modules/autoprefixer/lib/hacks/print-color-adjust.js new file mode 100644 index 0000000..6526a8e --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/print-color-adjust.js @@ -0,0 +1,25 @@ +let Declaration = require('../declaration') + +class PrintColorAdjust extends Declaration { + /** + * Return property name by spec + */ + normalize() { + return 'print-color-adjust' + } + + /** + * Change property name for WebKit-based browsers + */ + prefixed(prop, prefix) { + if (prefix === '-moz-') { + return 'color-adjust' + } else { + return prefix + 'print-color-adjust' + } + } +} + +PrintColorAdjust.names = ['print-color-adjust', 'color-adjust'] + +module.exports = PrintColorAdjust diff --git a/client/node_modules/autoprefixer/lib/hacks/text-decoration-skip-ink.js b/client/node_modules/autoprefixer/lib/hacks/text-decoration-skip-ink.js new file mode 100644 index 0000000..25dc4db --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/text-decoration-skip-ink.js @@ -0,0 +1,23 @@ +let Declaration = require('../declaration') + +class TextDecorationSkipInk extends Declaration { + /** + * Change prefix for ink value + */ + set(decl, prefix) { + if (decl.prop === 'text-decoration-skip-ink' && decl.value === 'auto') { + decl.prop = prefix + 'text-decoration-skip' + decl.value = 'ink' + return decl + } else { + return super.set(decl, prefix) + } + } +} + +TextDecorationSkipInk.names = [ + 'text-decoration-skip-ink', + 'text-decoration-skip' +] + +module.exports = TextDecorationSkipInk diff --git a/client/node_modules/autoprefixer/lib/hacks/text-decoration.js b/client/node_modules/autoprefixer/lib/hacks/text-decoration.js new file mode 100644 index 0000000..148d98a --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/text-decoration.js @@ -0,0 +1,25 @@ +let Declaration = require('../declaration') + +const BASIC = [ + 'none', + 'underline', + 'overline', + 'line-through', + 'blink', + 'inherit', + 'initial', + 'unset' +] + +class TextDecoration extends Declaration { + /** + * Do not add prefixes for basic values. + */ + check(decl) { + return decl.value.split(/\s+/).some(i => !BASIC.includes(i)) + } +} + +TextDecoration.names = ['text-decoration'] + +module.exports = TextDecoration diff --git a/client/node_modules/autoprefixer/lib/hacks/text-emphasis-position.js b/client/node_modules/autoprefixer/lib/hacks/text-emphasis-position.js new file mode 100644 index 0000000..0d04f8b --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/text-emphasis-position.js @@ -0,0 +1,14 @@ +let Declaration = require('../declaration') + +class TextEmphasisPosition extends Declaration { + set(decl, prefix) { + if (prefix === '-webkit-') { + decl.value = decl.value.replace(/\s*(right|left)\s*/i, '') + } + return super.set(decl, prefix) + } +} + +TextEmphasisPosition.names = ['text-emphasis-position'] + +module.exports = TextEmphasisPosition diff --git a/client/node_modules/autoprefixer/lib/hacks/transform-decl.js b/client/node_modules/autoprefixer/lib/hacks/transform-decl.js new file mode 100644 index 0000000..cecd06d --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/transform-decl.js @@ -0,0 +1,79 @@ +let Declaration = require('../declaration') + +class TransformDecl extends Declaration { + /** + * Is transform contain 3D commands + */ + contain3d(decl) { + if (decl.prop === 'transform-origin') { + return false + } + + for (let func of TransformDecl.functions3d) { + if (decl.value.includes(`${func}(`)) { + return true + } + } + + return false + } + + /** + * Don't add prefix for IE in keyframes + */ + insert(decl, prefix, prefixes) { + if (prefix === '-ms-') { + if (!this.contain3d(decl) && !this.keyframeParents(decl)) { + return super.insert(decl, prefix, prefixes) + } + } else if (prefix === '-o-') { + if (!this.contain3d(decl)) { + return super.insert(decl, prefix, prefixes) + } + } else { + return super.insert(decl, prefix, prefixes) + } + return undefined + } + + /** + * Recursively check all parents for @keyframes + */ + keyframeParents(decl) { + let { parent } = decl + while (parent) { + if (parent.type === 'atrule' && parent.name === 'keyframes') { + return true + } + ;({ parent } = parent) + } + return false + } + + /** + * Replace rotateZ to rotate for IE 9 + */ + set(decl, prefix) { + decl = super.set(decl, prefix) + if (prefix === '-ms-') { + decl.value = decl.value.replace(/rotatez/gi, 'rotate') + } + return decl + } +} + +TransformDecl.names = ['transform', 'transform-origin'] + +TransformDecl.functions3d = [ + 'matrix3d', + 'translate3d', + 'translateZ', + 'scale3d', + 'scaleZ', + 'rotate3d', + 'rotateX', + 'rotateY', + 'perspective' +] + +module.exports = TransformDecl diff --git a/client/node_modules/autoprefixer/lib/hacks/user-select.js b/client/node_modules/autoprefixer/lib/hacks/user-select.js new file mode 100644 index 0000000..f73831d --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/user-select.js @@ -0,0 +1,33 @@ +let Declaration = require('../declaration') + +class UserSelect extends Declaration { + /** + * Avoid prefixing all in IE + */ + insert(decl, prefix, prefixes) { + if (decl.value === 'all' && prefix === '-ms-') { + return undefined + } else if ( + decl.value === 'contain' && + (prefix === '-moz-' || prefix === '-webkit-') + ) { + return undefined + } else { + return super.insert(decl, prefix, prefixes) + } + } + + /** + * Change prefixed value for IE + */ + set(decl, prefix) { + if (prefix === '-ms-' && decl.value === 'contain') { + decl.value = 'element' + } + return super.set(decl, prefix) + } +} + +UserSelect.names = ['user-select'] + +module.exports = UserSelect diff --git a/client/node_modules/autoprefixer/lib/hacks/writing-mode.js b/client/node_modules/autoprefixer/lib/hacks/writing-mode.js new file mode 100644 index 0000000..71c8eeb --- /dev/null +++ b/client/node_modules/autoprefixer/lib/hacks/writing-mode.js @@ -0,0 +1,42 @@ +let Declaration = require('../declaration') + +class WritingMode extends Declaration { + insert(decl, prefix, prefixes) { + if (prefix === '-ms-') { + let cloned = this.set(this.clone(decl), prefix) + + if (this.needCascade(decl)) { + cloned.raws.before = this.calcBefore(prefixes, decl, prefix) + } + let direction = 'ltr' + + decl.parent.nodes.forEach(i => { + if (i.prop === 'direction') { + if (i.value === 'rtl' || i.value === 'ltr') direction = i.value + } + }) + + cloned.value = WritingMode.msValues[direction][decl.value] || decl.value + return decl.parent.insertBefore(decl, cloned) + } + + return super.insert(decl, prefix, prefixes) + } +} + +WritingMode.names = ['writing-mode'] + +WritingMode.msValues = { + ltr: { + 'horizontal-tb': 'lr-tb', + 'vertical-lr': 'tb-lr', + 'vertical-rl': 'tb-rl' + }, + rtl: { + 'horizontal-tb': 'rl-tb', + 'vertical-lr': 'bt-lr', + 'vertical-rl': 'bt-rl' + } +} + +module.exports = WritingMode diff --git a/client/node_modules/autoprefixer/lib/info.js b/client/node_modules/autoprefixer/lib/info.js new file mode 100644 index 0000000..a313486 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/info.js @@ -0,0 +1,123 @@ +let browserslist = require('browserslist') + +function capitalize(str) { + return str.slice(0, 1).toUpperCase() + str.slice(1) +} + +const NAMES = { + and_chr: 'Chrome for Android', + and_ff: 'Firefox for Android', + and_qq: 'QQ Browser', + and_uc: 'UC for Android', + baidu: 'Baidu Browser', + ie: 'IE', + ie_mob: 'IE Mobile', + ios_saf: 'iOS Safari', + kaios: 'KaiOS Browser', + op_mini: 'Opera Mini', + op_mob: 'Opera Mobile', + samsung: 'Samsung Internet' +} + +function prefix(name, prefixes, note) { + let out = ` ${name}` + if (note) out += ' *' + out += ': ' + out += prefixes.map(i => i.replace(/^-(.*)-$/g, '$1')).join(', ') + out += '\n' + return out +} + +module.exports = function (prefixes) { + if (prefixes.browsers.selected.length === 0) { + return 'No browsers selected' + } + + let versions = {} + for (let browser of prefixes.browsers.selected) { + let parts = browser.split(' ') + let name = parts[0] + let version = parts[1] + + name = NAMES[name] || capitalize(name) + if (versions[name]) { + versions[name].push(version) + } else { + versions[name] = [version] + } + } + + let out = 'Browsers:\n' + for (let browser in versions) { + let list = versions[browser] + list = list.sort((a, b) => parseFloat(b) - parseFloat(a)) + out += ` ${browser}: ${list.join(', ')}\n` + } + + let coverage = browserslist.coverage(prefixes.browsers.selected) + let round = Math.round(coverage * 100) / 100.0 + out += `\nThese browsers account for ${round}% of all users globally\n` + + let atrules = [] + for (let name in prefixes.add) { + let data = prefixes.add[name] + if (name[0] === '@' && data.prefixes) { + atrules.push(prefix(name, data.prefixes)) + } + } + if (atrules.length > 0) { + out += `\nAt-Rules:\n${atrules.sort().join('')}` + } + + let selectors = [] + for (let selector of prefixes.add.selectors) { + if (selector.prefixes) { + selectors.push(prefix(selector.name, selector.prefixes)) + } + } + if (selectors.length > 0) { + out += `\nSelectors:\n${selectors.sort().join('')}` + } + + let values = [] + let props = [] + let hadGrid = false + for (let name in prefixes.add) { + let data = prefixes.add[name] + if (name[0] !== '@' && data.prefixes) { + let grid = name.indexOf('grid-') === 0 + if (grid) hadGrid = true + props.push(prefix(name, data.prefixes, grid)) + } + + if (!Array.isArray(data.values)) { + continue + } + for (let value of data.values) { + let grid = value.name.includes('grid') + if (grid) hadGrid = true + let string = prefix(value.name, value.prefixes, grid) + if (!values.includes(string)) { + values.push(string) + } + } + } + + if (props.length > 0) { + out += `\nProperties:\n${props.sort().join('')}` + } + if (values.length > 0) { + out += `\nValues:\n${values.sort().join('')}` + } + if (hadGrid) { + out += '\n* - Prefixes will be added only on grid: true option.\n' + } + + if (!atrules.length && !selectors.length && !props.length && !values.length) { + out += + "\nAwesome! Your browsers don't require any vendor prefixes." + + '\nNow you can remove Autoprefixer from build steps.' + } + + return out +} diff --git a/client/node_modules/autoprefixer/lib/old-selector.js b/client/node_modules/autoprefixer/lib/old-selector.js new file mode 100644 index 0000000..ca98d07 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/old-selector.js @@ -0,0 +1,67 @@ +class OldSelector { + constructor(selector, prefix) { + this.prefix = prefix + this.prefixed = selector.prefixed(this.prefix) + this.regexp = selector.regexp(this.prefix) + + this.prefixeds = selector + .possible() + .map(x => [selector.prefixed(x), selector.regexp(x)]) + + this.unprefixed = selector.name + this.nameRegexp = selector.regexp() + } + + /** + * Does rule contain an unnecessary prefixed selector + */ + check(rule) { + if (!rule.selector.includes(this.prefixed)) { + return false + } + if (!rule.selector.match(this.regexp)) { + return false + } + if (this.isHack(rule)) { + return false + } + return true + } + + /** + * Is rule a hack without unprefixed version bottom + */ + isHack(rule) { + let index = rule.parent.index(rule) + 1 + let rules = rule.parent.nodes + + while (index < rules.length) { + let before = rules[index].selector + if (!before) { + return true + } + + if (before.includes(this.unprefixed) && before.match(this.nameRegexp)) { + return false + } + + let some = false + for (let [string, regexp] of this.prefixeds) { + if (before.includes(string) && before.match(regexp)) { + some = true + break + } + } + + if (!some) { + return true + } + + index += 1 + } + + return true + } +} + +module.exports = OldSelector diff --git a/client/node_modules/autoprefixer/lib/old-value.js b/client/node_modules/autoprefixer/lib/old-value.js new file mode 100644 index 0000000..63a2643 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/old-value.js @@ -0,0 +1,22 @@ +let utils = require('./utils') + +class OldValue { + constructor(unprefixed, prefixed, string, regexp) { + this.unprefixed = unprefixed + this.prefixed = prefixed + this.string = string || prefixed + this.regexp = regexp || utils.regexp(prefixed) + } + + /** + * Check, that value contain old value + */ + check(value) { + if (value.includes(this.string)) { + return !!value.match(this.regexp) + } + return false + } +} + +module.exports = OldValue diff --git a/client/node_modules/autoprefixer/lib/prefixer.js b/client/node_modules/autoprefixer/lib/prefixer.js new file mode 100644 index 0000000..ba9e4c1 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/prefixer.js @@ -0,0 +1,144 @@ +let Browsers = require('./browsers') +let utils = require('./utils') +let vendor = require('./vendor') + +/** + * Recursively clone objects + */ +function clone(obj, parent) { + let cloned = new obj.constructor() + + for (let i of Object.keys(obj || {})) { + let value = obj[i] + if (i === 'parent' && typeof value === 'object') { + if (parent) { + cloned[i] = parent + } + } else if (i === 'source' || i === null) { + cloned[i] = value + } else if (Array.isArray(value)) { + cloned[i] = value.map(x => clone(x, cloned)) + } else if ( + i !== '_autoprefixerPrefix' && + i !== '_autoprefixerValues' && + i !== 'proxyCache' + ) { + if (typeof value === 'object' && value !== null) { + value = clone(value, cloned) + } + cloned[i] = value + } + } + + return cloned +} + +class Prefixer { + constructor(name, prefixes, all) { + this.prefixes = prefixes + this.name = name + this.all = all + } + + /** + * Clone node and clean autprefixer custom caches + */ + static clone(node, overrides) { + let cloned = clone(node) + for (let name in overrides) { + cloned[name] = overrides[name] + } + return cloned + } + + /** + * Add hack to selected names + */ + static hack(klass) { + if (!this.hacks) { + this.hacks = {} + } + return klass.names.map(name => { + this.hacks[name] = klass + return this.hacks[name] + }) + } + + /** + * Load hacks for some names + */ + static load(name, prefixes, all) { + let Klass = this.hacks && this.hacks[name] + if (Klass) { + return new Klass(name, prefixes, all) + } else { + return new this(name, prefixes, all) + } + } + + /** + * Shortcut for Prefixer.clone + */ + clone(node, overrides) { + return Prefixer.clone(node, overrides) + } + + /** + * Find prefix in node parents + */ + parentPrefix(node) { + let prefix + + if (typeof node._autoprefixerPrefix !== 'undefined') { + prefix = node._autoprefixerPrefix + } else if (node.type === 'decl' && node.prop[0] === '-') { + prefix = vendor.prefix(node.prop) + } else if (node.type === 'root') { + prefix = false + } else if ( + node.type === 'rule' && + node.selector.includes(':-') && + /:(-\w+-)/.test(node.selector) + ) { + prefix = node.selector.match(/:(-\w+-)/)[1] + } else if (node.type === 'atrule' && node.name[0] === '-') { + prefix = vendor.prefix(node.name) + } else { + prefix = this.parentPrefix(node.parent) + } + + if (!Browsers.prefixes().includes(prefix)) { + prefix = false + } + + node._autoprefixerPrefix = prefix + + return node._autoprefixerPrefix + } + + /** + * Clone node with prefixes + */ + process(node, result) { + if (!this.check(node)) { + return undefined + } + + let parent = this.parentPrefix(node) + + let prefixes = this.prefixes.filter( + prefix => !parent || parent === utils.removeNote(prefix) + ) + + let added = [] + for (let prefix of prefixes) { + if (this.add(node, prefix, added.concat([prefix]), result)) { + added.push(prefix) + } + } + + return added + } +} + +module.exports = Prefixer diff --git a/client/node_modules/autoprefixer/lib/prefixes.js b/client/node_modules/autoprefixer/lib/prefixes.js new file mode 100644 index 0000000..a314dba --- /dev/null +++ b/client/node_modules/autoprefixer/lib/prefixes.js @@ -0,0 +1,428 @@ +let AtRule = require('./at-rule') +let Browsers = require('./browsers') +let Declaration = require('./declaration') +let hackAlignContent = require('./hacks/align-content') +let hackAlignItems = require('./hacks/align-items') +let hackAlignSelf = require('./hacks/align-self') +let hackAnimation = require('./hacks/animation') +let hackAppearance = require('./hacks/appearance') +let hackAutofill = require('./hacks/autofill') +let hackBackdropFilter = require('./hacks/backdrop-filter') +let hackBackgroundClip = require('./hacks/background-clip') +let hackBackgroundSize = require('./hacks/background-size') +let hackBlockLogical = require('./hacks/block-logical') +let hackBorderImage = require('./hacks/border-image') +let hackBorderRadius = require('./hacks/border-radius') +let hackBreakProps = require('./hacks/break-props') +let hackCrossFade = require('./hacks/cross-fade') +let hackDisplayFlex = require('./hacks/display-flex') +let hackDisplayGrid = require('./hacks/display-grid') +let hackFileSelectorButton = require('./hacks/file-selector-button') +let hackFilter = require('./hacks/filter') +let hackFilterValue = require('./hacks/filter-value') +let hackFlex = require('./hacks/flex') +let hackFlexBasis = require('./hacks/flex-basis') +let hackFlexDirection = require('./hacks/flex-direction') +let hackFlexFlow = require('./hacks/flex-flow') +let hackFlexGrow = require('./hacks/flex-grow') +let hackFlexShrink = require('./hacks/flex-shrink') +let hackFlexWrap = require('./hacks/flex-wrap') +let hackFullscreen = require('./hacks/fullscreen') +let hackGradient = require('./hacks/gradient') +let hackGridArea = require('./hacks/grid-area') +let hackGridColumnAlign = require('./hacks/grid-column-align') +let hackGridEnd = require('./hacks/grid-end') +let hackGridRowAlign = require('./hacks/grid-row-align') +let hackGridRowColumn = require('./hacks/grid-row-column') +let hackGridRowsColumns = require('./hacks/grid-rows-columns') +let hackGridStart = require('./hacks/grid-start') +let hackGridTemplate = require('./hacks/grid-template') +let hackGridTemplateAreas = require('./hacks/grid-template-areas') +let hackImageRendering = require('./hacks/image-rendering') +let hackImageSet = require('./hacks/image-set') +let hackInlineLogical = require('./hacks/inline-logical') +let hackIntrinsic = require('./hacks/intrinsic') +let hackJustifyContent = require('./hacks/justify-content') +let hackMaskBorder = require('./hacks/mask-border') +let hackMaskComposite = require('./hacks/mask-composite') +let hackOrder = require('./hacks/order') +let hackOverscrollBehavior = require('./hacks/overscroll-behavior') +let hackPixelated = require('./hacks/pixelated') +let hackPlaceSelf = require('./hacks/place-self') +let hackPlaceholder = require('./hacks/placeholder') +let hackPlaceholderShown = require('./hacks/placeholder-shown') +let hackPrintColorAdjust = require('./hacks/print-color-adjust') +let hackTextDecoration = require('./hacks/text-decoration') +let hackTextDecorationSkipInk = require('./hacks/text-decoration-skip-ink') +let hackTextEmphasisPosition = require('./hacks/text-emphasis-position') +let hackTransformDecl = require('./hacks/transform-decl') +let hackUserSelect = require('./hacks/user-select') +let hackWritingMode = require('./hacks/writing-mode') +let Processor = require('./processor') +let Resolution = require('./resolution') +let Selector = require('./selector') +let Supports = require('./supports') +let Transition = require('./transition') +let utils = require('./utils') +let Value = require('./value') +let vendor = require('./vendor') + +Selector.hack(hackAutofill) +Selector.hack(hackFullscreen) +Selector.hack(hackPlaceholder) +Selector.hack(hackPlaceholderShown) +Selector.hack(hackFileSelectorButton) +Declaration.hack(hackFlex) +Declaration.hack(hackOrder) +Declaration.hack(hackFilter) +Declaration.hack(hackGridEnd) +Declaration.hack(hackAnimation) +Declaration.hack(hackFlexFlow) +Declaration.hack(hackFlexGrow) +Declaration.hack(hackFlexWrap) +Declaration.hack(hackGridArea) +Declaration.hack(hackPlaceSelf) +Declaration.hack(hackGridStart) +Declaration.hack(hackAlignSelf) +Declaration.hack(hackAppearance) +Declaration.hack(hackFlexBasis) +Declaration.hack(hackMaskBorder) +Declaration.hack(hackMaskComposite) +Declaration.hack(hackAlignItems) +Declaration.hack(hackUserSelect) +Declaration.hack(hackFlexShrink) +Declaration.hack(hackBreakProps) +Declaration.hack(hackWritingMode) +Declaration.hack(hackBorderImage) +Declaration.hack(hackAlignContent) +Declaration.hack(hackBorderRadius) +Declaration.hack(hackBlockLogical) +Declaration.hack(hackGridTemplate) +Declaration.hack(hackInlineLogical) +Declaration.hack(hackGridRowAlign) +Declaration.hack(hackTransformDecl) +Declaration.hack(hackFlexDirection) +Declaration.hack(hackImageRendering) +Declaration.hack(hackBackdropFilter) +Declaration.hack(hackBackgroundClip) +Declaration.hack(hackTextDecoration) +Declaration.hack(hackJustifyContent) +Declaration.hack(hackBackgroundSize) +Declaration.hack(hackGridRowColumn) +Declaration.hack(hackGridRowsColumns) +Declaration.hack(hackGridColumnAlign) +Declaration.hack(hackOverscrollBehavior) +Declaration.hack(hackGridTemplateAreas) +Declaration.hack(hackPrintColorAdjust) +Declaration.hack(hackTextEmphasisPosition) +Declaration.hack(hackTextDecorationSkipInk) +Value.hack(hackGradient) +Value.hack(hackIntrinsic) +Value.hack(hackPixelated) +Value.hack(hackImageSet) +Value.hack(hackCrossFade) +Value.hack(hackDisplayFlex) +Value.hack(hackDisplayGrid) +Value.hack(hackFilterValue) + +let declsCache = new Map() + +class Prefixes { + constructor(data, browsers, options = {}) { + this.data = data + this.browsers = browsers + this.options = options + ;[this.add, this.remove] = this.preprocess(this.select(this.data)) + this.transition = new Transition(this) + this.processor = new Processor(this) + } + + /** + * Return clone instance to remove all prefixes + */ + cleaner() { + if (this.cleanerCache) { + return this.cleanerCache + } + + if (this.browsers.selected.length) { + let empty = new Browsers(this.browsers.data, []) + this.cleanerCache = new Prefixes(this.data, empty, this.options) + } else { + return this + } + + return this.cleanerCache + } + + /** + * Declaration loader with caching + */ + decl(prop) { + if (!declsCache.has(prop)) { + declsCache.set(prop, Declaration.load(prop)) + } + + return declsCache.get(prop) + } + + /** + * Group declaration by unprefixed property to check them + */ + group(decl) { + let rule = decl.parent + let index = rule.index(decl) + let { length } = rule.nodes + let unprefixed = this.unprefixed(decl.prop) + + let checker = (step, callback) => { + index += step + while (index >= 0 && index < length) { + let other = rule.nodes[index] + if (other.type === 'decl') { + if (step === -1 && other.prop === unprefixed) { + if (!Browsers.withPrefix(other.value)) { + break + } + } + + if (this.unprefixed(other.prop) !== unprefixed) { + break + } else if (callback(other) === true) { + return true + } + + if (step === 1 && other.prop === unprefixed) { + if (!Browsers.withPrefix(other.value)) { + break + } + } + } + + index += step + } + return false + } + + return { + down(callback) { + return checker(1, callback) + }, + up(callback) { + return checker(-1, callback) + } + } + } + + /** + * Normalize prefix for remover + */ + normalize(prop) { + return this.decl(prop).normalize(prop) + } + + /** + * Return prefixed version of property + */ + prefixed(prop, prefix) { + prop = vendor.unprefixed(prop) + return this.decl(prop).prefixed(prop, prefix) + } + + /** + * Cache prefixes data to fast CSS processing + */ + preprocess(selected) { + let add = { + '@supports': new Supports(Prefixes, this), + 'selectors': [] + } + for (let name in selected.add) { + let prefixes = selected.add[name] + if (name === '@keyframes' || name === '@viewport') { + add[name] = new AtRule(name, prefixes, this) + } else if (name === '@resolution') { + add[name] = new Resolution(name, prefixes, this) + } else if (this.data[name].selector) { + add.selectors.push(Selector.load(name, prefixes, this)) + } else { + let props = this.data[name].props + + if (props) { + let value = Value.load(name, prefixes, this) + for (let prop of props) { + if (!add[prop]) { + add[prop] = { values: [] } + } + add[prop].values.push(value) + } + } else { + let values = (add[name] && add[name].values) || [] + add[name] = Declaration.load(name, prefixes, this) + add[name].values = values + } + } + } + + let remove = { selectors: [] } + for (let name in selected.remove) { + let prefixes = selected.remove[name] + if (this.data[name].selector) { + let selector = Selector.load(name, prefixes) + for (let prefix of prefixes) { + remove.selectors.push(selector.old(prefix)) + } + } else if (name === '@keyframes' || name === '@viewport') { + for (let prefix of prefixes) { + let prefixed = `@${prefix}${name.slice(1)}` + remove[prefixed] = { remove: true } + } + } else if (name === '@resolution') { + remove[name] = new Resolution(name, prefixes, this) + } else { + let props = this.data[name].props + if (props) { + let value = Value.load(name, [], this) + for (let prefix of prefixes) { + let old = value.old(prefix) + if (old) { + for (let prop of props) { + if (!remove[prop]) { + remove[prop] = {} + } + if (!remove[prop].values) { + remove[prop].values = [] + } + remove[prop].values.push(old) + } + } + } + } else { + for (let p of prefixes) { + let olds = this.decl(name).old(name, p) + if (name === 'align-self') { + let a = add[name] && add[name].prefixes + if (a) { + if (p === '-webkit- 2009' && a.includes('-webkit-')) { + continue + } else if (p === '-webkit-' && a.includes('-webkit- 2009')) { + continue + } + } + } + for (let prefixed of olds) { + if (!remove[prefixed]) { + remove[prefixed] = {} + } + remove[prefixed].remove = true + } + } + } + } + } + + return [add, remove] + } + + /** + * Select prefixes from data, which is necessary for selected browsers + */ + select(list) { + let selected = { add: {}, remove: {} } + + for (let name in list) { + let data = list[name] + let add = data.browsers.map(i => { + let params = i.split(' ') + return { + browser: `${params[0]} ${params[1]}`, + note: params[2] + } + }) + + let notes = add + .filter(i => i.note) + .map(i => `${this.browsers.prefix(i.browser)} ${i.note}`) + notes = utils.uniq(notes) + + add = add + .filter(i => this.browsers.isSelected(i.browser)) + .map(i => { + let prefix = this.browsers.prefix(i.browser) + if (i.note) { + return `${prefix} ${i.note}` + } else { + return prefix + } + }) + add = this.sort(utils.uniq(add)) + + if (this.options.flexbox === 'no-2009') { + add = add.filter(i => !i.includes('2009')) + } + + let all = data.browsers.map(i => this.browsers.prefix(i)) + if (data.mistakes) { + all = all.concat(data.mistakes) + } + all = all.concat(notes) + all = utils.uniq(all) + + if (add.length) { + selected.add[name] = add + if (add.length < all.length) { + selected.remove[name] = all.filter(i => !add.includes(i)) + } + } else { + selected.remove[name] = all + } + } + + return selected + } + + /** + * Sort vendor prefixes + */ + sort(prefixes) { + return prefixes.sort((a, b) => { + let aLength = utils.removeNote(a).length + let bLength = utils.removeNote(b).length + + if (aLength === bLength) { + return b.length - a.length + } else { + return bLength - aLength + } + }) + } + + /** + * Return unprefixed version of property + */ + unprefixed(prop) { + let value = this.normalize(vendor.unprefixed(prop)) + if (value === 'flex-direction') { + value = 'flex-flow' + } + return value + } + + /** + * Return values, which must be prefixed in selected property + */ + values(type, prop) { + let data = this[type] + + let global = data['*'] && data['*'].values + let values = data[prop] && data[prop].values + + if (global && values) { + return utils.uniq(global.concat(values)) + } else { + return global || values || [] + } + } +} + +module.exports = Prefixes diff --git a/client/node_modules/autoprefixer/lib/processor.js b/client/node_modules/autoprefixer/lib/processor.js new file mode 100644 index 0000000..e884ffb --- /dev/null +++ b/client/node_modules/autoprefixer/lib/processor.js @@ -0,0 +1,710 @@ +let parser = require('postcss-value-parser') + +let Value = require('./value') +let insertAreas = require('./hacks/grid-utils').insertAreas + +const OLD_LINEAR = /(^|[^-])linear-gradient\(\s*(top|left|right|bottom)/i +const OLD_RADIAL = /(^|[^-])radial-gradient\(\s*\d+(\w*|%)\s+\d+(\w*|%)\s*,/i +const IGNORE_NEXT = /(!\s*)?autoprefixer:\s*ignore\s+next/i +const GRID_REGEX = /(!\s*)?autoprefixer\s*grid:\s*(on|off|(no-)?autoplace)/i + +const SIZES = [ + 'width', + 'height', + 'min-width', + 'max-width', + 'min-height', + 'max-height', + 'inline-size', + 'min-inline-size', + 'max-inline-size', + 'block-size', + 'min-block-size', + 'max-block-size' +] + +function hasGridTemplate(decl) { + return decl.parent.some( + i => i.prop === 'grid-template' || i.prop === 'grid-template-areas' + ) +} + +function hasRowsAndColumns(decl) { + let hasRows = decl.parent.some(i => i.prop === 'grid-template-rows') + let hasColumns = decl.parent.some(i => i.prop === 'grid-template-columns') + return hasRows && hasColumns +} + +function insideGrid(decl) { + return decl.parent.nodes.some(node => { + if (node.type !== 'decl') return false + let displayGrid = + node.prop === 'display' && /(inline-)?grid/.test(node.value) + let gridTemplate = node.prop.startsWith('grid-template') + let gridGap = /^grid-([A-z]+-)?gap/.test(node.prop) + return displayGrid || gridTemplate || gridGap + }) +} + +class Processor { + constructor(prefixes) { + this.prefixes = prefixes + } + + /** + * Add necessary prefixes + */ + add(css, result) { + // At-rules + let resolution = this.prefixes.add['@resolution'] + let keyframes = this.prefixes.add['@keyframes'] + let viewport = this.prefixes.add['@viewport'] + let supports = this.prefixes.add['@supports'] + + css.walkAtRules(rule => { + if (rule.name === 'keyframes') { + if (!this.disabled(rule, result)) { + return keyframes && keyframes.process(rule) + } + } else if (rule.name === 'viewport') { + if (!this.disabled(rule, result)) { + return viewport && viewport.process(rule) + } + } else if (rule.name === 'supports') { + if ( + this.prefixes.options.supports !== false && + !this.disabled(rule, result) + ) { + return supports.process(rule) + } + } else if (rule.name === 'media' && rule.params.includes('-resolution')) { + if (!this.disabled(rule, result)) { + return resolution && resolution.process(rule) + } + } + + return undefined + }) + + // Selectors + css.walkRules(rule => { + if (this.disabled(rule, result)) return undefined + + return this.prefixes.add.selectors.map(selector => { + return selector.process(rule, result) + }) + }) + + let gridPrefixes = + this.gridStatus(css, result) && + this.prefixes.add['grid-area'] && + this.prefixes.add['grid-area'].prefixes + + css.walkDecls(decl => { + if (this.disabledDecl(decl, result)) return undefined + + let parent = decl.parent + let prop = decl.prop + let value = decl.value + + if (prop === 'color-adjust') { + if (parent.every(i => i.prop !== 'print-color-adjust')) { + result.warn( + 'Replace color-adjust to print-color-adjust. ' + + 'The color-adjust shorthand is currently deprecated.', + { node: decl } + ) + } + } else if (prop === 'grid-row-span') { + result.warn( + 'grid-row-span is not part of final Grid Layout. Use grid-row.', + { node: decl } + ) + return undefined + } else if (prop === 'grid-column-span') { + result.warn( + 'grid-column-span is not part of final Grid Layout. Use grid-column.', + { node: decl } + ) + return undefined + } else if (prop === 'display' && value === 'box') { + result.warn( + 'You should write display: flex by final spec ' + + 'instead of display: box', + { node: decl } + ) + return undefined + } else if (prop === 'text-emphasis-position') { + if (value === 'under' || value === 'over') { + result.warn( + 'You should use 2 values for text-emphasis-position ' + + 'For example, `under left` instead of just `under`.', + { node: decl } + ) + } + } else if (prop === 'text-decoration-skip' && value === 'ink') { + result.warn( + 'Replace text-decoration-skip: ink to ' + + 'text-decoration-skip-ink: auto, because spec had been changed', + { node: decl } + ) + } else { + if (gridPrefixes && this.gridStatus(decl, result)) { + if (decl.value === 'subgrid') { + result.warn('IE does not support subgrid', { node: decl }) + } + if (/^(align|justify|place)-items$/.test(prop) && insideGrid(decl)) { + let fixed = prop.replace('-items', '-self') + result.warn( + `IE does not support ${prop} on grid containers. ` + + `Try using ${fixed} on child elements instead: ` + + `${decl.parent.selector} > * { ${fixed}: ${decl.value} }`, + { node: decl } + ) + } else if ( + /^(align|justify|place)-content$/.test(prop) && + insideGrid(decl) + ) { + result.warn(`IE does not support ${decl.prop} on grid containers`, { + node: decl + }) + } else if (prop === 'display' && decl.value === 'contents') { + result.warn( + 'Please do not use display: contents; ' + + 'if you have grid setting enabled', + { node: decl } + ) + return undefined + } else if (decl.prop === 'grid-gap') { + let status = this.gridStatus(decl, result) + if ( + status === 'autoplace' && + !hasRowsAndColumns(decl) && + !hasGridTemplate(decl) + ) { + result.warn( + 'grid-gap only works if grid-template(-areas) is being ' + + 'used or both rows and columns have been declared ' + + 'and cells have not been manually ' + + 'placed inside the explicit grid', + { node: decl } + ) + } else if ( + (status === true || status === 'no-autoplace') && + !hasGridTemplate(decl) + ) { + result.warn( + 'grid-gap only works if grid-template(-areas) is being used', + { node: decl } + ) + } + } else if (prop === 'grid-auto-columns') { + result.warn('grid-auto-columns is not supported by IE', { + node: decl + }) + return undefined + } else if (prop === 'grid-auto-rows') { + result.warn('grid-auto-rows is not supported by IE', { node: decl }) + return undefined + } else if (prop === 'grid-auto-flow') { + let hasRows = parent.some(i => i.prop === 'grid-template-rows') + let hasCols = parent.some(i => i.prop === 'grid-template-columns') + + if (hasGridTemplate(decl)) { + result.warn('grid-auto-flow is not supported by IE', { + node: decl + }) + } else if (value.includes('dense')) { + result.warn('grid-auto-flow: dense is not supported by IE', { + node: decl + }) + } else if (!hasRows && !hasCols) { + result.warn( + 'grid-auto-flow works only if grid-template-rows and ' + + 'grid-template-columns are present in the same rule', + { node: decl } + ) + } + return undefined + } else if (value.includes('auto-fit')) { + result.warn('auto-fit value is not supported by IE', { + node: decl, + word: 'auto-fit' + }) + return undefined + } else if (value.includes('auto-fill')) { + result.warn('auto-fill value is not supported by IE', { + node: decl, + word: 'auto-fill' + }) + return undefined + } else if (prop.startsWith('grid-template') && value.includes('[')) { + result.warn( + 'Autoprefixer currently does not support line names. ' + + 'Try using grid-template-areas instead.', + { node: decl, word: '[' } + ) + } + } + if (value.includes('radial-gradient')) { + if (OLD_RADIAL.test(decl.value)) { + result.warn( + 'Gradient has outdated direction syntax. ' + + 'New syntax is like `closest-side at 0 0` ' + + 'instead of `0 0, closest-side`.', + { node: decl } + ) + } else { + let ast = parser(value) + + for (let i of ast.nodes) { + if (i.type === 'function' && i.value === 'radial-gradient') { + for (let word of i.nodes) { + if (word.type === 'word') { + if (word.value === 'cover') { + result.warn( + 'Gradient has outdated direction syntax. ' + + 'Replace `cover` to `farthest-corner`.', + { node: decl } + ) + } else if (word.value === 'contain') { + result.warn( + 'Gradient has outdated direction syntax. ' + + 'Replace `contain` to `closest-side`.', + { node: decl } + ) + } + } + } + } + } + } + } + if (value.includes('linear-gradient')) { + if (OLD_LINEAR.test(value)) { + result.warn( + 'Gradient has outdated direction syntax. ' + + 'New syntax is like `to left` instead of `right`.', + { node: decl } + ) + } + } + } + + if (SIZES.includes(decl.prop)) { + if (!decl.value.includes('-fill-available')) { + if (decl.value.includes('fill-available')) { + result.warn( + 'Replace fill-available to stretch, ' + + 'because spec had been changed', + { node: decl } + ) + } else if (decl.value.includes('fill')) { + let ast = parser(value) + if (ast.nodes.some(i => i.type === 'word' && i.value === 'fill')) { + result.warn( + 'Replace fill to stretch, because spec had been changed', + { node: decl } + ) + } + } + } + } + + let prefixer + + if (decl.prop === 'transition' || decl.prop === 'transition-property') { + // Transition + return this.prefixes.transition.add(decl, result) + } else if (decl.prop === 'align-self') { + // align-self flexbox or grid + let display = this.displayType(decl) + if (display !== 'grid' && this.prefixes.options.flexbox !== false) { + prefixer = this.prefixes.add['align-self'] + if (prefixer && prefixer.prefixes) { + prefixer.process(decl) + } + } + if (this.gridStatus(decl, result) !== false) { + prefixer = this.prefixes.add['grid-row-align'] + if (prefixer && prefixer.prefixes) { + return prefixer.process(decl, result) + } + } + } else if (decl.prop === 'justify-self') { + // justify-self flexbox or grid + if (this.gridStatus(decl, result) !== false) { + prefixer = this.prefixes.add['grid-column-align'] + if (prefixer && prefixer.prefixes) { + return prefixer.process(decl, result) + } + } + } else if (decl.prop === 'place-self') { + prefixer = this.prefixes.add['place-self'] + if ( + prefixer && + prefixer.prefixes && + this.gridStatus(decl, result) !== false + ) { + return prefixer.process(decl, result) + } + } else { + // Properties + prefixer = this.prefixes.add[decl.prop] + if (prefixer && prefixer.prefixes) { + return prefixer.process(decl, result) + } + } + + return undefined + }) + + // Insert grid-area prefixes. We need to be able to store the different + // rules as a data and hack API is not enough for this + if (this.gridStatus(css, result)) { + insertAreas(css, this.disabled) + } + + // Values + return css.walkDecls(decl => { + if (this.disabledValue(decl, result)) return + + let unprefixed = this.prefixes.unprefixed(decl.prop) + let list = this.prefixes.values('add', unprefixed) + if (Array.isArray(list)) { + for (let value of list) { + if (value.process) value.process(decl, result) + } + } + Value.save(this.prefixes, decl) + }) + } + + /** + * Check for control comment and global options + */ + disabled(node, result) { + if (!node) return false + + if (node._autoprefixerDisabled !== undefined) { + return node._autoprefixerDisabled + } + + if (node.parent) { + let p = node.prev() + if (p && p.type === 'comment' && IGNORE_NEXT.test(p.text)) { + node._autoprefixerDisabled = true + node._autoprefixerSelfDisabled = true + return true + } + } + + let value = null + if (node.nodes) { + let status + node.each(i => { + if (i.type !== 'comment') return + if (/(!\s*)?autoprefixer:\s*(off|on)/i.test(i.text)) { + if (typeof status !== 'undefined') { + result.warn( + 'Second Autoprefixer control comment ' + + 'was ignored. Autoprefixer applies control ' + + 'comment to whole block, not to next rules.', + { node: i } + ) + } else { + status = /on/i.test(i.text) + } + } + }) + + if (status !== undefined) { + value = !status + } + } + if (!node.nodes || value === null) { + if (node.parent) { + let isParentDisabled = this.disabled(node.parent, result) + if (node.parent._autoprefixerSelfDisabled === true) { + value = false + } else { + value = isParentDisabled + } + } else { + value = false + } + } + node._autoprefixerDisabled = value + return value + } + + /** + * Check for grid/flexbox options. + */ + disabledDecl(node, result) { + if (node.type === 'decl' && this.gridStatus(node, result) === false) { + if (node.prop.includes('grid') || node.prop === 'justify-items') { + return true + } + } + if (node.type === 'decl' && this.prefixes.options.flexbox === false) { + let other = ['order', 'justify-content', 'align-items', 'align-content'] + if (node.prop.includes('flex') || other.includes(node.prop)) { + return true + } + } + + return this.disabled(node, result) + } + + /** + * Check for grid/flexbox options. + */ + disabledValue(node, result) { + if (this.gridStatus(node, result) === false && node.type === 'decl') { + if (node.prop === 'display' && node.value.includes('grid')) { + return true + } + } + if (this.prefixes.options.flexbox === false && node.type === 'decl') { + if (node.prop === 'display' && node.value.includes('flex')) { + return true + } + } + if (node.type === 'decl' && node.prop === 'content') { + return true + } + + return this.disabled(node, result) + } + + /** + * Is it flebox or grid rule + */ + displayType(decl) { + for (let i of decl.parent.nodes) { + if (i.prop !== 'display') { + continue + } + + if (i.value.includes('flex')) { + return 'flex' + } + + if (i.value.includes('grid')) { + return 'grid' + } + } + + return false + } + + /** + * Set grid option via control comment + */ + gridStatus(node, result) { + if (!node) return false + + if (node._autoprefixerGridStatus !== undefined) { + return node._autoprefixerGridStatus + } + + let value = null + if (node.nodes) { + let status + node.each(i => { + if (i.type !== 'comment') return + if (GRID_REGEX.test(i.text)) { + let hasAutoplace = /:\s*autoplace/i.test(i.text) + let noAutoplace = /no-autoplace/i.test(i.text) + if (typeof status !== 'undefined') { + result.warn( + 'Second Autoprefixer grid control comment was ' + + 'ignored. Autoprefixer applies control comments to the whole ' + + 'block, not to the next rules.', + { node: i } + ) + } else if (hasAutoplace) { + status = 'autoplace' + } else if (noAutoplace) { + status = true + } else { + status = /on/i.test(i.text) + } + } + }) + + if (status !== undefined) { + value = status + } + } + + if (node.type === 'atrule' && node.name === 'supports') { + let params = node.params + if (params.includes('grid') && params.includes('auto')) { + value = false + } + } + + if (!node.nodes || value === null) { + if (node.parent) { + let isParentGrid = this.gridStatus(node.parent, result) + if (node.parent._autoprefixerSelfDisabled === true) { + value = false + } else { + value = isParentGrid + } + } else if (typeof this.prefixes.options.grid !== 'undefined') { + value = this.prefixes.options.grid + } else if (typeof process.env.AUTOPREFIXER_GRID !== 'undefined') { + if (process.env.AUTOPREFIXER_GRID === 'autoplace') { + value = 'autoplace' + } else { + value = true + } + } else { + value = false + } + } + + node._autoprefixerGridStatus = value + return value + } + + /** + * Normalize spaces in cascade declaration group + */ + reduceSpaces(decl) { + let stop = false + this.prefixes.group(decl).up(() => { + stop = true + return true + }) + if (stop) { + return + } + + let parts = decl.raw('before').split('\n') + let prevMin = parts[parts.length - 1].length + /** @type {number|false} */ + let diff = false + + this.prefixes.group(decl).down(other => { + parts = other.raw('before').split('\n') + let last = parts.length - 1 + + if (parts[last].length > prevMin) { + if (diff === false) { + diff = parts[last].length - prevMin + } + + parts[last] = parts[last].slice(0, -diff) + other.raws.before = parts.join('\n') + } + }) + } + + /** + * Remove unnecessary pefixes + */ + remove(css, result) { + // At-rules + let resolution = this.prefixes.remove['@resolution'] + + css.walkAtRules((rule, i) => { + if (this.prefixes.remove[`@${rule.name}`]) { + if (!this.disabled(rule, result)) { + rule.parent.removeChild(i) + } + } else if ( + rule.name === 'media' && + rule.params.includes('-resolution') && + resolution + ) { + resolution.clean(rule) + } + }) + + // Selectors + css.walkRules((rule, i) => { + if (this.disabled(rule, result)) return + + for (let checker of this.prefixes.remove.selectors) { + if (checker.check(rule)) { + rule.parent.removeChild(i) + return + } + } + }) + + return css.walkDecls((decl, i) => { + if (this.disabled(decl, result)) return + + let rule = decl.parent + let unprefixed = this.prefixes.unprefixed(decl.prop) + + // Transition + if (decl.prop === 'transition' || decl.prop === 'transition-property') { + this.prefixes.transition.remove(decl) + } + + // Properties + if ( + this.prefixes.remove[decl.prop] && + this.prefixes.remove[decl.prop].remove + ) { + let notHack = this.prefixes.group(decl).down(other => { + return this.prefixes.normalize(other.prop) === unprefixed + }) + + if (unprefixed === 'flex-flow') { + notHack = true + } + + if (decl.prop === '-webkit-box-orient') { + let hacks = { 'flex-direction': true, 'flex-flow': true } + if (!decl.parent.some(j => hacks[j.prop])) return + } + + if (notHack && !this.withHackValue(decl)) { + if (decl.raw('before').includes('\n')) { + this.reduceSpaces(decl) + } + rule.removeChild(i) + return + } + } + + // Values + for (let checker of this.prefixes.values('remove', unprefixed)) { + if (!checker.check) continue + if (!checker.check(decl.value)) continue + + unprefixed = checker.unprefixed + let notHack = this.prefixes.group(decl).down(other => { + return other.value.includes(unprefixed) + }) + + if (notHack) { + rule.removeChild(i) + return + } + } + }) + } + + /** + * Some rare old values, which is not in standard + */ + withHackValue(decl) { + return ( + (decl.prop === '-webkit-background-clip' && decl.value === 'text') || + // Do not remove -webkit-box-orient when -webkit-line-clamp is present. + // https://github.com/postcss/autoprefixer/issues/1510 + (decl.prop === '-webkit-box-orient' && + decl.parent.some(d => d.prop === '-webkit-line-clamp')) + ) + } +} + +module.exports = Processor diff --git a/client/node_modules/autoprefixer/lib/resolution.js b/client/node_modules/autoprefixer/lib/resolution.js new file mode 100644 index 0000000..4b71564 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/resolution.js @@ -0,0 +1,97 @@ +let FractionJs = require('fraction.js') + +let Prefixer = require('./prefixer') +let utils = require('./utils') + +const REGEXP = /(min|max)-resolution\s*:\s*\d*\.?\d+(dppx|dpcm|dpi|x)/gi +const SPLIT = /(min|max)-resolution(\s*:\s*)(\d*\.?\d+)(dppx|dpcm|dpi|x)/i + +class Resolution extends Prefixer { + /** + * Remove prefixed queries + */ + clean(rule) { + if (!this.bad) { + this.bad = [] + for (let prefix of this.prefixes) { + this.bad.push(this.prefixName(prefix, 'min')) + this.bad.push(this.prefixName(prefix, 'max')) + } + } + + rule.params = utils.editList(rule.params, queries => { + return queries.filter(query => this.bad.every(i => !query.includes(i))) + }) + } + + /** + * Return prefixed query name + */ + prefixName(prefix, name) { + if (prefix === '-moz-') { + return name + '--moz-device-pixel-ratio' + } else { + return prefix + name + '-device-pixel-ratio' + } + } + + /** + * Return prefixed query + */ + prefixQuery(prefix, name, colon, value, units) { + value = new FractionJs(value) + + // 1dpcm = 2.54dpi + // 1dppx = 96dpi + if (units === 'dpi') { + value = value.div(96) + } else if (units === 'dpcm') { + value = value.mul(2.54).div(96) + } + value = value.simplify() + + if (prefix === '-o-') { + value = value.n + '/' + value.d + } + return this.prefixName(prefix, name) + colon + value + } + + /** + * Add prefixed queries + */ + process(rule) { + let parent = this.parentPrefix(rule) + let prefixes = parent ? [parent] : this.prefixes + + rule.params = utils.editList(rule.params, (origin, prefixed) => { + for (let query of origin) { + if ( + !query.includes('min-resolution') && + !query.includes('max-resolution') + ) { + prefixed.push(query) + continue + } + + for (let prefix of prefixes) { + let processed = query.replace(REGEXP, str => { + let parts = str.match(SPLIT) + return this.prefixQuery( + prefix, + parts[1], + parts[2], + parts[3], + parts[4] + ) + }) + prefixed.push(processed) + } + prefixed.push(query) + } + + return utils.uniq(prefixed) + }) + } +} + +module.exports = Resolution diff --git a/client/node_modules/autoprefixer/lib/selector.js b/client/node_modules/autoprefixer/lib/selector.js new file mode 100644 index 0000000..3aaa6ff --- /dev/null +++ b/client/node_modules/autoprefixer/lib/selector.js @@ -0,0 +1,150 @@ +let { list } = require('postcss') + +let Browsers = require('./browsers') +let OldSelector = require('./old-selector') +let Prefixer = require('./prefixer') +let utils = require('./utils') + +class Selector extends Prefixer { + constructor(name, prefixes, all) { + super(name, prefixes, all) + this.regexpCache = new Map() + } + + /** + * Clone and add prefixes for at-rule + */ + add(rule, prefix) { + let prefixeds = this.prefixeds(rule) + + if (this.already(rule, prefixeds, prefix)) { + return + } + + let cloned = this.clone(rule, { selector: prefixeds[this.name][prefix] }) + rule.parent.insertBefore(rule, cloned) + } + + /** + * Is rule already prefixed before + */ + already(rule, prefixeds, prefix) { + let index = rule.parent.index(rule) - 1 + + while (index >= 0) { + let before = rule.parent.nodes[index] + + if (before.type !== 'rule') { + return false + } + + let some = false + for (let key in prefixeds[this.name]) { + let prefixed = prefixeds[this.name][key] + if (before.selector === prefixed) { + if (prefix === key) { + return true + } else { + some = true + break + } + } + } + if (!some) { + return false + } + + index -= 1 + } + + return false + } + + /** + * Is rule selectors need to be prefixed + */ + check(rule) { + if (rule.selector.includes(this.name)) { + return !!rule.selector.match(this.regexp()) + } + + return false + } + + /** + * Return function to fast find prefixed selector + */ + old(prefix) { + return new OldSelector(this, prefix) + } + + /** + * All possible prefixes + */ + possible() { + return Browsers.prefixes() + } + + /** + * Return prefixed version of selector + */ + prefixed(prefix) { + return this.name.replace(/^(\W*)/, `$1${prefix}`) + } + + /** + * Return all possible selector prefixes + */ + prefixeds(rule) { + if (rule._autoprefixerPrefixeds) { + if (rule._autoprefixerPrefixeds[this.name]) { + return rule._autoprefixerPrefixeds + } + } else { + rule._autoprefixerPrefixeds = {} + } + + let prefixeds = {} + if (rule.selector.includes(',')) { + let ruleParts = list.comma(rule.selector) + let toProcess = ruleParts.filter(el => el.includes(this.name)) + + for (let prefix of this.possible()) { + prefixeds[prefix] = toProcess + .map(el => this.replace(el, prefix)) + .join(', ') + } + } else { + for (let prefix of this.possible()) { + prefixeds[prefix] = this.replace(rule.selector, prefix) + } + } + + rule._autoprefixerPrefixeds[this.name] = prefixeds + return rule._autoprefixerPrefixeds + } + + /** + * Lazy loadRegExp for name + */ + regexp(prefix) { + if (!this.regexpCache.has(prefix)) { + let name = prefix ? this.prefixed(prefix) : this.name + this.regexpCache.set( + prefix, + new RegExp(`(^|[^:"'=])${utils.escapeRegexp(name)}`, 'gi') + ) + } + + return this.regexpCache.get(prefix) + } + + /** + * Replace selectors by prefixed one + */ + replace(selector, prefix) { + return selector.replace(this.regexp(), `$1${this.prefixed(prefix)}`) + } +} + +module.exports = Selector diff --git a/client/node_modules/autoprefixer/lib/supports.js b/client/node_modules/autoprefixer/lib/supports.js new file mode 100644 index 0000000..3ed5133 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/supports.js @@ -0,0 +1,302 @@ +let featureQueries = require('caniuse-lite/data/features/css-featurequeries.js') +let feature = require('caniuse-lite/dist/unpacker/feature') +let { parse } = require('postcss') + +let brackets = require('./brackets') +let Browsers = require('./browsers') +let utils = require('./utils') +let Value = require('./value') + +let data = feature(featureQueries) + +let supported = [] +for (let browser in data.stats) { + let versions = data.stats[browser] + for (let version in versions) { + let support = versions[version] + if (/y/.test(support)) { + supported.push(browser + ' ' + version) + } + } +} + +class Supports { + constructor(Prefixes, all) { + this.Prefixes = Prefixes + this.all = all + } + + /** + * Add prefixes + */ + add(nodes, all) { + return nodes.map(i => { + if (this.isProp(i)) { + let prefixed = this.prefixed(i[0]) + if (prefixed.length > 1) { + return this.convert(prefixed) + } + + return i + } + + if (typeof i === 'object') { + return this.add(i, all) + } + + return i + }) + } + + /** + * Clean brackets with one child + */ + cleanBrackets(nodes) { + return nodes.map(i => { + if (typeof i !== 'object') { + return i + } + + if (i.length === 1 && typeof i[0] === 'object') { + return this.cleanBrackets(i[0]) + } + + return this.cleanBrackets(i) + }) + } + + /** + * Add " or " between properties and convert it to brackets format + */ + convert(progress) { + let result = [''] + for (let i of progress) { + result.push([`${i.prop}: ${i.value}`]) + result.push(' or ') + } + result[result.length - 1] = '' + return result + } + + /** + * Check global options + */ + disabled(node) { + if (!this.all.options.grid) { + if (node.prop === 'display' && node.value.includes('grid')) { + return true + } + if (node.prop.includes('grid') || node.prop === 'justify-items') { + return true + } + } + + if (this.all.options.flexbox === false) { + if (node.prop === 'display' && node.value.includes('flex')) { + return true + } + let other = ['order', 'justify-content', 'align-items', 'align-content'] + if (node.prop.includes('flex') || other.includes(node.prop)) { + return true + } + } + + return false + } + + /** + * Return true if prefixed property has no unprefixed + */ + isHack(all, unprefixed) { + let check = new RegExp(`(\\(|\\s)${utils.escapeRegexp(unprefixed)}:`) + return !check.test(all) + } + + /** + * Return true if brackets node is "not" word + */ + isNot(node) { + return typeof node === 'string' && /not\s*/i.test(node) + } + + /** + * Return true if brackets node is "or" word + */ + isOr(node) { + return typeof node === 'string' && /\s*or\s*/i.test(node) + } + + /** + * Return true if brackets node is (prop: value) + */ + isProp(node) { + return ( + typeof node === 'object' && + node.length === 1 && + typeof node[0] === 'string' + ) + } + + /** + * Compress value functions into a string nodes + */ + normalize(nodes) { + if (typeof nodes !== 'object') { + return nodes + } + + nodes = nodes.filter(i => i !== '') + + if (typeof nodes[0] === 'string') { + let firstNode = nodes[0].trim() + + if ( + firstNode.includes(':') || + firstNode === 'selector' || + firstNode === 'not selector' + ) { + return [brackets.stringify(nodes)] + } + } + return nodes.map(i => this.normalize(i)) + } + + /** + * Parse string into declaration property and value + */ + parse(str) { + let parts = str.split(':') + let prop = parts[0] + let value = parts[1] + if (!value) value = '' + return [prop.trim(), value.trim()] + } + + /** + * Return array of Declaration with all necessary prefixes + */ + prefixed(str) { + let rule = this.virtual(str) + if (this.disabled(rule.first)) { + return rule.nodes + } + + let result = { warn: () => null } + + let prefixer = this.prefixer().add[rule.first.prop] + prefixer && prefixer.process && prefixer.process(rule.first, result) + + for (let decl of rule.nodes) { + for (let value of this.prefixer().values('add', rule.first.prop)) { + value.process(decl) + } + Value.save(this.all, decl) + } + + return rule.nodes + } + + /** + * Return prefixer only with @supports supported browsers + */ + prefixer() { + if (this.prefixerCache) { + return this.prefixerCache + } + + let filtered = this.all.browsers.selected.filter(i => { + return supported.includes(i) + }) + + let browsers = new Browsers( + this.all.browsers.data, + filtered, + this.all.options + ) + this.prefixerCache = new this.Prefixes( + this.all.data, + browsers, + this.all.options + ) + return this.prefixerCache + } + + /** + * Add prefixed declaration + */ + process(rule) { + let ast = brackets.parse(rule.params) + ast = this.normalize(ast) + ast = this.remove(ast, rule.params) + ast = this.add(ast, rule.params) + ast = this.cleanBrackets(ast) + rule.params = brackets.stringify(ast) + } + + /** + * Remove all unnecessary prefixes + */ + remove(nodes, all) { + let i = 0 + while (i < nodes.length) { + if ( + !this.isNot(nodes[i - 1]) && + this.isProp(nodes[i]) && + this.isOr(nodes[i + 1]) + ) { + if (this.toRemove(nodes[i][0], all)) { + nodes.splice(i, 2) + continue + } + + i += 2 + continue + } + + if (typeof nodes[i] === 'object') { + nodes[i] = this.remove(nodes[i], all) + } + + i += 1 + } + return nodes + } + + /** + * Return true if we need to remove node + */ + toRemove(str, all) { + let [prop, value] = this.parse(str) + let unprefixed = this.all.unprefixed(prop) + + let cleaner = this.all.cleaner() + + if ( + cleaner.remove[prop] && + cleaner.remove[prop].remove && + !this.isHack(all, unprefixed) + ) { + return true + } + + for (let checker of cleaner.values('remove', unprefixed)) { + if (checker.check(value)) { + return true + } + } + + return false + } + + /** + * Create virtual rule to process it by prefixer + */ + virtual(str) { + let [prop, value] = this.parse(str) + let rule = parse('a{}').first + rule.append({ prop, raws: { before: '' }, value }) + return rule + } +} + +module.exports = Supports diff --git a/client/node_modules/autoprefixer/lib/transition.js b/client/node_modules/autoprefixer/lib/transition.js new file mode 100644 index 0000000..1c9b343 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/transition.js @@ -0,0 +1,329 @@ +let { list } = require('postcss') +let parser = require('postcss-value-parser') + +let Browsers = require('./browsers') +let vendor = require('./vendor') + +class Transition { + constructor(prefixes) { + this.props = ['transition', 'transition-property'] + this.prefixes = prefixes + } + + /** + * Process transition and add prefixes for all necessary properties + */ + add(decl, result) { + let prefix, prop + let add = this.prefixes.add[decl.prop] + let vendorPrefixes = this.ruleVendorPrefixes(decl) + let declPrefixes = vendorPrefixes || (add && add.prefixes) || [] + + let params = this.parse(decl.value) + let names = params.map(i => this.findProp(i)) + let added = [] + + if (names.some(i => i[0] === '-')) { + return + } + + for (let param of params) { + prop = this.findProp(param) + if (prop[0] === '-') continue + + let prefixer = this.prefixes.add[prop] + if (!prefixer || !prefixer.prefixes) continue + + for (prefix of prefixer.prefixes) { + if (vendorPrefixes && !vendorPrefixes.some(p => prefix.includes(p))) { + continue + } + + let prefixed = this.prefixes.prefixed(prop, prefix) + if (prefixed !== '-ms-transform' && !names.includes(prefixed)) { + if (!this.disabled(prop, prefix)) { + added.push(this.clone(prop, prefixed, param)) + } + } + } + } + + params = params.concat(added) + let value = this.stringify(params) + + let webkitClean = this.stringify( + this.cleanFromUnprefixed(params, '-webkit-') + ) + if (declPrefixes.includes('-webkit-')) { + this.cloneBefore(decl, `-webkit-${decl.prop}`, webkitClean) + } + this.cloneBefore(decl, decl.prop, webkitClean) + if (declPrefixes.includes('-o-')) { + let operaClean = this.stringify(this.cleanFromUnprefixed(params, '-o-')) + this.cloneBefore(decl, `-o-${decl.prop}`, operaClean) + } + + for (prefix of declPrefixes) { + if (prefix !== '-webkit-' && prefix !== '-o-') { + let prefixValue = this.stringify( + this.cleanOtherPrefixes(params, prefix) + ) + this.cloneBefore(decl, prefix + decl.prop, prefixValue) + } + } + + if (value !== decl.value && !this.already(decl, decl.prop, value)) { + this.checkForWarning(result, decl) + decl.cloneBefore() + decl.value = value + } + } + + /** + * Does we already have this declaration + */ + already(decl, prop, value) { + return decl.parent.some(i => i.prop === prop && i.value === value) + } + + /** + * Show transition-property warning + */ + checkForWarning(result, decl) { + if (decl.prop !== 'transition-property') { + return + } + + let isPrefixed = false + let hasAssociatedProp = false + + decl.parent.each(i => { + if (i.type !== 'decl') { + return undefined + } + if (i.prop.indexOf('transition-') !== 0) { + return undefined + } + let values = list.comma(i.value) + // check if current Rule's transition-property comma separated value list needs prefixes + if (i.prop === 'transition-property') { + values.forEach(value => { + let lookup = this.prefixes.add[value] + if (lookup && lookup.prefixes && lookup.prefixes.length > 0) { + isPrefixed = true + } + }) + return undefined + } + // check if another transition-* prop in current Rule has comma separated value list + hasAssociatedProp = hasAssociatedProp || values.length > 1 + return false + }) + + if (isPrefixed && hasAssociatedProp) { + decl.warn( + result, + 'Replace transition-property to transition, ' + + 'because Autoprefixer could not support ' + + 'any cases of transition-property ' + + 'and other transition-*' + ) + } + } + + /** + * Remove all non-webkit prefixes and unprefixed params if we have prefixed + */ + cleanFromUnprefixed(params, prefix) { + let remove = params + .map(i => this.findProp(i)) + .filter(i => i.slice(0, prefix.length) === prefix) + .map(i => this.prefixes.unprefixed(i)) + + let result = [] + for (let param of params) { + let prop = this.findProp(param) + let p = vendor.prefix(prop) + if (!remove.includes(prop) && (p === prefix || p === '')) { + result.push(param) + } + } + return result + } + + cleanOtherPrefixes(params, prefix) { + return params.filter(param => { + let current = vendor.prefix(this.findProp(param)) + return current === '' || current === prefix + }) + } + + /** + * Return new param array with different name + */ + clone(origin, name, param) { + let result = [] + let changed = false + for (let i of param) { + if (!changed && i.type === 'word' && i.value === origin) { + result.push({ type: 'word', value: name }) + changed = true + } else { + result.push(i) + } + } + return result + } + + /** + * Add declaration if it is not exist + */ + cloneBefore(decl, prop, value) { + if (!this.already(decl, prop, value)) { + decl.cloneBefore({ prop, value }) + } + } + + /** + * Check property for disabled by option + */ + disabled(prop, prefix) { + let other = ['order', 'justify-content', 'align-self', 'align-content'] + if (prop.includes('flex') || other.includes(prop)) { + if (this.prefixes.options.flexbox === false) { + return true + } + + if (this.prefixes.options.flexbox === 'no-2009') { + return prefix.includes('2009') + } + } + return undefined + } + + /** + * Find or create separator + */ + div(params) { + for (let param of params) { + for (let node of param) { + if (node.type === 'div' && node.value === ',') { + return node + } + } + } + return { after: ' ', type: 'div', value: ',' } + } + + /** + * Find property name + */ + findProp(param) { + let prop = param[0].value + if (/^\d/.test(prop)) { + for (let [i, token] of param.entries()) { + if (i !== 0 && token.type === 'word') { + return token.value + } + } + } + return prop + } + + /** + * Parse properties list to array + */ + parse(value) { + let ast = parser(value) + let result = [] + let param = [] + for (let node of ast.nodes) { + param.push(node) + if (node.type === 'div' && node.value === ',') { + result.push(param) + param = [] + } + } + result.push(param) + return result.filter(i => i.length > 0) + } + + /** + * Process transition and remove all unnecessary properties + */ + remove(decl) { + let params = this.parse(decl.value) + params = params.filter(i => { + let prop = this.prefixes.remove[this.findProp(i)] + return !prop || !prop.remove + }) + let value = this.stringify(params) + + if (decl.value === value) { + return + } + + if (params.length === 0) { + decl.remove() + return + } + + let double = decl.parent.some(i => { + return i.prop === decl.prop && i.value === value + }) + let smaller = decl.parent.some(i => { + return i !== decl && i.prop === decl.prop && i.value.length > value.length + }) + + if (double || smaller) { + decl.remove() + return + } + + decl.value = value + } + + /** + * Check if transition prop is inside vendor specific rule + */ + ruleVendorPrefixes(decl) { + let { parent } = decl + + if (parent.type !== 'rule') { + return false + } else if (!parent.selector.includes(':-')) { + return false + } + + let selectors = Browsers.prefixes().filter(s => + parent.selector.includes(':' + s) + ) + + return selectors.length > 0 ? selectors : false + } + + /** + * Return properties string from array + */ + stringify(params) { + if (params.length === 0) { + return '' + } + let nodes = [] + for (let param of params) { + if (param[param.length - 1].type !== 'div') { + param.push(this.div(params)) + } + nodes.push(...param) + } + if (nodes[0].type === 'div') { + nodes = nodes.slice(1) + } + if (nodes[nodes.length - 1].type === 'div') { + nodes = nodes.slice(0, -1) + } + return parser.stringify({ nodes }) + } +} + +module.exports = Transition diff --git a/client/node_modules/autoprefixer/lib/utils.js b/client/node_modules/autoprefixer/lib/utils.js new file mode 100644 index 0000000..2309e8e --- /dev/null +++ b/client/node_modules/autoprefixer/lib/utils.js @@ -0,0 +1,93 @@ +let { list } = require('postcss') + +/** + * Throw special error, to tell beniary, + * that this error is from Autoprefixer. + */ +module.exports.error = function (text) { + let err = new Error(text) + err.autoprefixer = true + throw err +} + +/** + * Return array, that doesn’t contain duplicates. + */ +module.exports.uniq = function (array) { + return [...new Set(array)] +} + +/** + * Return "-webkit-" on "-webkit- old" + */ +module.exports.removeNote = function (string) { + if (!string.includes(' ')) { + return string + } + + return string.split(' ')[0] +} + +/** + * Escape RegExp symbols + */ +module.exports.escapeRegexp = function (string) { + return string.replace(/[$()*+-.?[\\\]^{|}]/g, '\\$&') +} + +/** + * Return regexp to check, that CSS string contain word + */ +module.exports.regexp = function (word, escape = true) { + if (escape) { + word = this.escapeRegexp(word) + } + return new RegExp(`(^|[\\s,(])(${word}($|[\\s(,]))`, 'gi') +} + +/** + * Change comma list + */ +module.exports.editList = function (value, callback) { + let origin = list.comma(value) + let changed = callback(origin, []) + + if (origin === changed) { + return value + } + + let join = value.match(/,\s*/) + join = join ? join[0] : ', ' + return changed.join(join) +} + +/** + * Split the selector into parts. + * It returns 3 level deep array because selectors can be comma + * separated (1), space separated (2), and combined (3) + * @param {String} selector selector string + * @return {Array>} 3 level deep array of split selector + * @see utils.test.js for examples + */ +module.exports.splitSelector = function (selector) { + return list.comma(selector).map(i => { + return list.space(i).map(k => { + return k.split(/(?=\.|#)/g) + }) + }) +} + +/** + * Return true if a given value only contains numbers. + * @param {*} value + * @returns {boolean} + */ +module.exports.isPureNumber = function (value) { + if (typeof value === 'number') { + return true + } + if (typeof value === 'string') { + return /^[0-9]+$/.test(value) + } + return false +} diff --git a/client/node_modules/autoprefixer/lib/value.js b/client/node_modules/autoprefixer/lib/value.js new file mode 100644 index 0000000..39d2915 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/value.js @@ -0,0 +1,125 @@ +let OldValue = require('./old-value') +let Prefixer = require('./prefixer') +let utils = require('./utils') +let vendor = require('./vendor') + +class Value extends Prefixer { + /** + * Clone decl for each prefixed values + */ + static save(prefixes, decl) { + let prop = decl.prop + let result = [] + + for (let prefix in decl._autoprefixerValues) { + let value = decl._autoprefixerValues[prefix] + + if (value === decl.value) { + continue + } + + let item + let propPrefix = vendor.prefix(prop) + + if (propPrefix === '-pie-') { + continue + } + + if (propPrefix === prefix) { + item = decl.value = value + result.push(item) + continue + } + + let prefixed = prefixes.prefixed(prop, prefix) + let rule = decl.parent + + if (!rule.every(i => i.prop !== prefixed)) { + result.push(item) + continue + } + + let trimmed = value.replace(/\s+/, ' ') + let already = rule.some( + i => i.prop === decl.prop && i.value.replace(/\s+/, ' ') === trimmed + ) + + if (already) { + result.push(item) + continue + } + + let cloned = this.clone(decl, { value }) + item = decl.parent.insertBefore(decl, cloned) + + result.push(item) + } + + return result + } + + /** + * Save values with next prefixed token + */ + add(decl, prefix) { + if (!decl._autoprefixerValues) { + decl._autoprefixerValues = {} + } + let value = decl._autoprefixerValues[prefix] || this.value(decl) + + let before + do { + before = value + value = this.replace(value, prefix) + if (value === false) return + } while (value !== before) + + decl._autoprefixerValues[prefix] = value + } + + /** + * Is declaration need to be prefixed + */ + check(decl) { + let value = decl.value + if (!value.includes(this.name)) { + return false + } + + return !!value.match(this.regexp()) + } + + /** + * Return function to fast find prefixed value + */ + old(prefix) { + return new OldValue(this.name, prefix + this.name) + } + + /** + * Lazy regexp loading + */ + regexp() { + return this.regexpCache || (this.regexpCache = utils.regexp(this.name)) + } + + /** + * Add prefix to values in string + */ + replace(string, prefix) { + return string.replace(this.regexp(), `$1${prefix}$2`) + } + + /** + * Get value with comments if it was not changed + */ + value(decl) { + if (decl.raws.value && decl.raws.value.value === decl.value) { + return decl.raws.value.raw + } else { + return decl.value + } + } +} + +module.exports = Value diff --git a/client/node_modules/autoprefixer/lib/vendor.js b/client/node_modules/autoprefixer/lib/vendor.js new file mode 100644 index 0000000..099ffc1 --- /dev/null +++ b/client/node_modules/autoprefixer/lib/vendor.js @@ -0,0 +1,14 @@ +module.exports = { + prefix(prop) { + let match = prop.match(/^(-\w+-)/) + if (match) { + return match[0] + } + + return '' + }, + + unprefixed(prop) { + return prop.replace(/^-\w+-/, '') + } +} diff --git a/client/node_modules/autoprefixer/package.json b/client/node_modules/autoprefixer/package.json new file mode 100644 index 0000000..5d02203 --- /dev/null +++ b/client/node_modules/autoprefixer/package.json @@ -0,0 +1,48 @@ +{ + "name": "autoprefixer", + "version": "10.5.0", + "description": "Parse CSS and add vendor prefixes to CSS rules using values from the Can I Use website", + "keywords": [ + "autoprefixer", + "css", + "postcss", + "postcss-plugin", + "prefix" + ], + "bugs": { + "url": "https://github.com/postcss/autoprefixer/issues" + }, + "license": "MIT", + "author": "Andrey Sitnik ", + "repository": "postcss/autoprefixer", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/autoprefixer" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": "bin/autoprefixer", + "main": "lib/autoprefixer.js", + "types": "lib/autoprefixer.d.ts", + "dependencies": { + "browserslist": "^4.28.2", + "caniuse-lite": "^1.0.30001787", + "fraction.js": "^5.3.4", + "picocolors": "^1.1.1", + "postcss-value-parser": "^4.2.0" + }, + "peerDependencies": { + "postcss": "^8.1.0" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } +} diff --git a/client/node_modules/detect-libc/LICENSE b/client/node_modules/detect-libc/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/client/node_modules/detect-libc/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/client/node_modules/detect-libc/README.md b/client/node_modules/detect-libc/README.md new file mode 100644 index 0000000..23212fd --- /dev/null +++ b/client/node_modules/detect-libc/README.md @@ -0,0 +1,163 @@ +# detect-libc + +Node.js module to detect details of the C standard library (libc) +implementation provided by a given Linux system. + +Currently supports detection of GNU glibc and MUSL libc. + +Provides asychronous and synchronous functions for the +family (e.g. `glibc`, `musl`) and version (e.g. `1.23`, `1.2.3`). + +The version numbers of libc implementations +are not guaranteed to be semver-compliant. + +For previous v1.x releases, please see the +[v1](https://github.com/lovell/detect-libc/tree/v1) branch. + +## Install + +```sh +npm install detect-libc +``` + +## API + +### GLIBC + +```ts +const GLIBC: string = 'glibc'; +``` + +A String constant containing the value `glibc`. + +### MUSL + +```ts +const MUSL: string = 'musl'; +``` + +A String constant containing the value `musl`. + +### family + +```ts +function family(): Promise; +``` + +Resolves asychronously with: + +* `glibc` or `musl` when the libc family can be determined +* `null` when the libc family cannot be determined +* `null` when run on a non-Linux platform + +```js +const { family, GLIBC, MUSL } = require('detect-libc'); + +switch (await family()) { + case GLIBC: ... + case MUSL: ... + case null: ... +} +``` + +### familySync + +```ts +function familySync(): string | null; +``` + +Synchronous version of `family()`. + +```js +const { familySync, GLIBC, MUSL } = require('detect-libc'); + +switch (familySync()) { + case GLIBC: ... + case MUSL: ... + case null: ... +} +``` + +### version + +```ts +function version(): Promise; +``` + +Resolves asychronously with: + +* The version when it can be determined +* `null` when the libc family cannot be determined +* `null` when run on a non-Linux platform + +```js +const { version } = require('detect-libc'); + +const v = await version(); +if (v) { + const [major, minor, patch] = v.split('.'); +} +``` + +### versionSync + +```ts +function versionSync(): string | null; +``` + +Synchronous version of `version()`. + +```js +const { versionSync } = require('detect-libc'); + +const v = versionSync(); +if (v) { + const [major, minor, patch] = v.split('.'); +} +``` + +### isNonGlibcLinux + +```ts +function isNonGlibcLinux(): Promise; +``` + +Resolves asychronously with: + +* `false` when the libc family is `glibc` +* `true` when the libc family is not `glibc` +* `false` when run on a non-Linux platform + +```js +const { isNonGlibcLinux } = require('detect-libc'); + +if (await isNonGlibcLinux()) { ... } +``` + +### isNonGlibcLinuxSync + +```ts +function isNonGlibcLinuxSync(): boolean; +``` + +Synchronous version of `isNonGlibcLinux()`. + +```js +const { isNonGlibcLinuxSync } = require('detect-libc'); + +if (isNonGlibcLinuxSync()) { ... } +``` + +## Licensing + +Copyright 2017 Lovell Fuller and others. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0.html) + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/client/node_modules/detect-libc/index.d.ts b/client/node_modules/detect-libc/index.d.ts new file mode 100644 index 0000000..4c0fb2b --- /dev/null +++ b/client/node_modules/detect-libc/index.d.ts @@ -0,0 +1,14 @@ +// Copyright 2017 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +export const GLIBC: 'glibc'; +export const MUSL: 'musl'; + +export function family(): Promise; +export function familySync(): string | null; + +export function isNonGlibcLinux(): Promise; +export function isNonGlibcLinuxSync(): boolean; + +export function version(): Promise; +export function versionSync(): string | null; diff --git a/client/node_modules/detect-libc/lib/detect-libc.js b/client/node_modules/detect-libc/lib/detect-libc.js new file mode 100644 index 0000000..01299b4 --- /dev/null +++ b/client/node_modules/detect-libc/lib/detect-libc.js @@ -0,0 +1,313 @@ +// Copyright 2017 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const childProcess = require('child_process'); +const { isLinux, getReport } = require('./process'); +const { LDD_PATH, SELF_PATH, readFile, readFileSync } = require('./filesystem'); +const { interpreterPath } = require('./elf'); + +let cachedFamilyInterpreter; +let cachedFamilyFilesystem; +let cachedVersionFilesystem; + +const command = 'getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true'; +let commandOut = ''; + +const safeCommand = () => { + if (!commandOut) { + return new Promise((resolve) => { + childProcess.exec(command, (err, out) => { + commandOut = err ? ' ' : out; + resolve(commandOut); + }); + }); + } + return commandOut; +}; + +const safeCommandSync = () => { + if (!commandOut) { + try { + commandOut = childProcess.execSync(command, { encoding: 'utf8' }); + } catch (_err) { + commandOut = ' '; + } + } + return commandOut; +}; + +/** + * A String constant containing the value `glibc`. + * @type {string} + * @public + */ +const GLIBC = 'glibc'; + +/** + * A Regexp constant to get the GLIBC Version. + * @type {string} + */ +const RE_GLIBC_VERSION = /LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i; + +/** + * A String constant containing the value `musl`. + * @type {string} + * @public + */ +const MUSL = 'musl'; + +const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-'); + +const familyFromReport = () => { + const report = getReport(); + if (report.header && report.header.glibcVersionRuntime) { + return GLIBC; + } + if (Array.isArray(report.sharedObjects)) { + if (report.sharedObjects.some(isFileMusl)) { + return MUSL; + } + } + return null; +}; + +const familyFromCommand = (out) => { + const [getconf, ldd1] = out.split(/[\r\n]+/); + if (getconf && getconf.includes(GLIBC)) { + return GLIBC; + } + if (ldd1 && ldd1.includes(MUSL)) { + return MUSL; + } + return null; +}; + +const familyFromInterpreterPath = (path) => { + if (path) { + if (path.includes('/ld-musl-')) { + return MUSL; + } else if (path.includes('/ld-linux-')) { + return GLIBC; + } + } + return null; +}; + +const getFamilyFromLddContent = (content) => { + content = content.toString(); + if (content.includes('musl')) { + return MUSL; + } + if (content.includes('GNU C Library')) { + return GLIBC; + } + return null; +}; + +const familyFromFilesystem = async () => { + if (cachedFamilyFilesystem !== undefined) { + return cachedFamilyFilesystem; + } + cachedFamilyFilesystem = null; + try { + const lddContent = await readFile(LDD_PATH); + cachedFamilyFilesystem = getFamilyFromLddContent(lddContent); + } catch (e) {} + return cachedFamilyFilesystem; +}; + +const familyFromFilesystemSync = () => { + if (cachedFamilyFilesystem !== undefined) { + return cachedFamilyFilesystem; + } + cachedFamilyFilesystem = null; + try { + const lddContent = readFileSync(LDD_PATH); + cachedFamilyFilesystem = getFamilyFromLddContent(lddContent); + } catch (e) {} + return cachedFamilyFilesystem; +}; + +const familyFromInterpreter = async () => { + if (cachedFamilyInterpreter !== undefined) { + return cachedFamilyInterpreter; + } + cachedFamilyInterpreter = null; + try { + const selfContent = await readFile(SELF_PATH); + const path = interpreterPath(selfContent); + cachedFamilyInterpreter = familyFromInterpreterPath(path); + } catch (e) {} + return cachedFamilyInterpreter; +}; + +const familyFromInterpreterSync = () => { + if (cachedFamilyInterpreter !== undefined) { + return cachedFamilyInterpreter; + } + cachedFamilyInterpreter = null; + try { + const selfContent = readFileSync(SELF_PATH); + const path = interpreterPath(selfContent); + cachedFamilyInterpreter = familyFromInterpreterPath(path); + } catch (e) {} + return cachedFamilyInterpreter; +}; + +/** + * Resolves with the libc family when it can be determined, `null` otherwise. + * @returns {Promise} + */ +const family = async () => { + let family = null; + if (isLinux()) { + family = await familyFromInterpreter(); + if (!family) { + family = await familyFromFilesystem(); + if (!family) { + family = familyFromReport(); + } + if (!family) { + const out = await safeCommand(); + family = familyFromCommand(out); + } + } + } + return family; +}; + +/** + * Returns the libc family when it can be determined, `null` otherwise. + * @returns {?string} + */ +const familySync = () => { + let family = null; + if (isLinux()) { + family = familyFromInterpreterSync(); + if (!family) { + family = familyFromFilesystemSync(); + if (!family) { + family = familyFromReport(); + } + if (!family) { + const out = safeCommandSync(); + family = familyFromCommand(out); + } + } + } + return family; +}; + +/** + * Resolves `true` only when the platform is Linux and the libc family is not `glibc`. + * @returns {Promise} + */ +const isNonGlibcLinux = async () => isLinux() && await family() !== GLIBC; + +/** + * Returns `true` only when the platform is Linux and the libc family is not `glibc`. + * @returns {boolean} + */ +const isNonGlibcLinuxSync = () => isLinux() && familySync() !== GLIBC; + +const versionFromFilesystem = async () => { + if (cachedVersionFilesystem !== undefined) { + return cachedVersionFilesystem; + } + cachedVersionFilesystem = null; + try { + const lddContent = await readFile(LDD_PATH); + const versionMatch = lddContent.match(RE_GLIBC_VERSION); + if (versionMatch) { + cachedVersionFilesystem = versionMatch[1]; + } + } catch (e) {} + return cachedVersionFilesystem; +}; + +const versionFromFilesystemSync = () => { + if (cachedVersionFilesystem !== undefined) { + return cachedVersionFilesystem; + } + cachedVersionFilesystem = null; + try { + const lddContent = readFileSync(LDD_PATH); + const versionMatch = lddContent.match(RE_GLIBC_VERSION); + if (versionMatch) { + cachedVersionFilesystem = versionMatch[1]; + } + } catch (e) {} + return cachedVersionFilesystem; +}; + +const versionFromReport = () => { + const report = getReport(); + if (report.header && report.header.glibcVersionRuntime) { + return report.header.glibcVersionRuntime; + } + return null; +}; + +const versionSuffix = (s) => s.trim().split(/\s+/)[1]; + +const versionFromCommand = (out) => { + const [getconf, ldd1, ldd2] = out.split(/[\r\n]+/); + if (getconf && getconf.includes(GLIBC)) { + return versionSuffix(getconf); + } + if (ldd1 && ldd2 && ldd1.includes(MUSL)) { + return versionSuffix(ldd2); + } + return null; +}; + +/** + * Resolves with the libc version when it can be determined, `null` otherwise. + * @returns {Promise} + */ +const version = async () => { + let version = null; + if (isLinux()) { + version = await versionFromFilesystem(); + if (!version) { + version = versionFromReport(); + } + if (!version) { + const out = await safeCommand(); + version = versionFromCommand(out); + } + } + return version; +}; + +/** + * Returns the libc version when it can be determined, `null` otherwise. + * @returns {?string} + */ +const versionSync = () => { + let version = null; + if (isLinux()) { + version = versionFromFilesystemSync(); + if (!version) { + version = versionFromReport(); + } + if (!version) { + const out = safeCommandSync(); + version = versionFromCommand(out); + } + } + return version; +}; + +module.exports = { + GLIBC, + MUSL, + family, + familySync, + isNonGlibcLinux, + isNonGlibcLinuxSync, + version, + versionSync +}; diff --git a/client/node_modules/detect-libc/lib/elf.js b/client/node_modules/detect-libc/lib/elf.js new file mode 100644 index 0000000..aa166aa --- /dev/null +++ b/client/node_modules/detect-libc/lib/elf.js @@ -0,0 +1,39 @@ +// Copyright 2017 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const interpreterPath = (elf) => { + if (elf.length < 64) { + return null; + } + if (elf.readUInt32BE(0) !== 0x7F454C46) { + // Unexpected magic bytes + return null; + } + if (elf.readUInt8(4) !== 2) { + // Not a 64-bit ELF + return null; + } + if (elf.readUInt8(5) !== 1) { + // Not little-endian + return null; + } + const offset = elf.readUInt32LE(32); + const size = elf.readUInt16LE(54); + const count = elf.readUInt16LE(56); + for (let i = 0; i < count; i++) { + const headerOffset = offset + (i * size); + const type = elf.readUInt32LE(headerOffset); + if (type === 3) { + const fileOffset = elf.readUInt32LE(headerOffset + 8); + const fileSize = elf.readUInt32LE(headerOffset + 32); + return elf.subarray(fileOffset, fileOffset + fileSize).toString().replace(/\0.*$/g, ''); + } + } + return null; +}; + +module.exports = { + interpreterPath +}; diff --git a/client/node_modules/detect-libc/lib/filesystem.js b/client/node_modules/detect-libc/lib/filesystem.js new file mode 100644 index 0000000..4c2443c --- /dev/null +++ b/client/node_modules/detect-libc/lib/filesystem.js @@ -0,0 +1,51 @@ +// Copyright 2017 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const fs = require('fs'); + +const LDD_PATH = '/usr/bin/ldd'; +const SELF_PATH = '/proc/self/exe'; +const MAX_LENGTH = 2048; + +/** + * Read the content of a file synchronous + * + * @param {string} path + * @returns {Buffer} + */ +const readFileSync = (path) => { + const fd = fs.openSync(path, 'r'); + const buffer = Buffer.alloc(MAX_LENGTH); + const bytesRead = fs.readSync(fd, buffer, 0, MAX_LENGTH, 0); + fs.close(fd, () => {}); + return buffer.subarray(0, bytesRead); +}; + +/** + * Read the content of a file + * + * @param {string} path + * @returns {Promise} + */ +const readFile = (path) => new Promise((resolve, reject) => { + fs.open(path, 'r', (err, fd) => { + if (err) { + reject(err); + } else { + const buffer = Buffer.alloc(MAX_LENGTH); + fs.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => { + resolve(buffer.subarray(0, bytesRead)); + fs.close(fd, () => {}); + }); + } + }); +}); + +module.exports = { + LDD_PATH, + SELF_PATH, + readFileSync, + readFile +}; diff --git a/client/node_modules/detect-libc/lib/process.js b/client/node_modules/detect-libc/lib/process.js new file mode 100644 index 0000000..ee78ad2 --- /dev/null +++ b/client/node_modules/detect-libc/lib/process.js @@ -0,0 +1,24 @@ +// Copyright 2017 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const isLinux = () => process.platform === 'linux'; + +let report = null; +const getReport = () => { + if (!report) { + /* istanbul ignore next */ + if (isLinux() && process.report) { + const orig = process.report.excludeNetwork; + process.report.excludeNetwork = true; + report = process.report.getReport(); + process.report.excludeNetwork = orig; + } else { + report = {}; + } + } + return report; +}; + +module.exports = { isLinux, getReport }; diff --git a/client/node_modules/detect-libc/package.json b/client/node_modules/detect-libc/package.json new file mode 100644 index 0000000..36d0f2b --- /dev/null +++ b/client/node_modules/detect-libc/package.json @@ -0,0 +1,44 @@ +{ + "name": "detect-libc", + "version": "2.1.2", + "description": "Node.js module to detect the C standard library (libc) implementation family and version", + "main": "lib/detect-libc.js", + "files": [ + "lib/", + "index.d.ts" + ], + "scripts": { + "test": "semistandard && nyc --reporter=text --check-coverage --branches=100 ava test/unit.js", + "changelog": "conventional-changelog -i CHANGELOG.md -s", + "bench": "node benchmark/detect-libc", + "bench:calls": "node benchmark/call-familySync.js && sleep 1 && node benchmark/call-isNonGlibcLinuxSync.js && sleep 1 && node benchmark/call-versionSync.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/lovell/detect-libc.git" + }, + "keywords": [ + "libc", + "glibc", + "musl" + ], + "author": "Lovell Fuller ", + "contributors": [ + "Niklas Salmoukas ", + "Vinícius Lourenço " + ], + "license": "Apache-2.0", + "devDependencies": { + "ava": "^2.4.0", + "benchmark": "^2.1.4", + "conventional-changelog-cli": "^5.0.0", + "eslint-config-standard": "^13.0.1", + "nyc": "^15.1.0", + "proxyquire": "^2.1.3", + "semistandard": "^14.2.3" + }, + "engines": { + "node": ">=8" + }, + "types": "index.d.ts" +} diff --git a/client/node_modules/enhanced-resolve/LICENSE b/client/node_modules/enhanced-resolve/LICENSE new file mode 100644 index 0000000..8c11fc7 --- /dev/null +++ b/client/node_modules/enhanced-resolve/LICENSE @@ -0,0 +1,20 @@ +Copyright JS Foundation and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/client/node_modules/enhanced-resolve/README.md b/client/node_modules/enhanced-resolve/README.md new file mode 100644 index 0000000..970deb8 --- /dev/null +++ b/client/node_modules/enhanced-resolve/README.md @@ -0,0 +1,784 @@ +# enhanced-resolve + +[![npm][npm]][npm-url] +[![Build Status][build-status]][build-status-url] +[![codecov][codecov-badge]][codecov-url] +[![Install Size][size]][size-url] +[![GitHub Discussions][discussion]][discussion-url] + +Offers an async require.resolve function. It's highly configurable. + +## Features + +- plugin system +- provide a custom filesystem +- sync and async node.js filesystems included + +## Getting Started + +### Install + +```sh +# npm +npm install enhanced-resolve +# or Yarn +yarn add enhanced-resolve +# or pnpm +pnpm add enhanced-resolve +``` + +### Resolve + +There is a Node.js API which allows to resolve requests according to the Node.js resolving rules. +Sync, async (callback) and promise APIs are offered. A `create` method allows to create a custom resolve function. + +```js +const resolve = require("enhanced-resolve"); + +resolve("/some/path/to/folder", "module/dir", (err, result) => { + result; // === "/some/path/node_modules/module/dir/index.js" +}); + +resolve.sync("/some/path/to/folder", "../../dir"); +// === "/some/path/dir/index.js" + +const result = await resolve.promise("/some/path/to/folder", "../../dir"); +// === "/some/path/dir/index.js" + +const myResolve = resolve.create({ + // or resolve.create.sync / resolve.create.promise + extensions: [".ts", ".js"], + // see more options below +}); + +myResolve("/some/path/to/folder", "ts-module", (err, result) => { + result; // === "/some/node_modules/ts-module/index.ts" +}); +``` + +### Public API + +All of the following are exposed from `require("enhanced-resolve")`. + +#### `resolve(context?, path, request, resolveContext?, callback)` + +Async Node-style resolver using the built-in defaults (`conditionNames: ["node"]`, `extensions: [".js", ".json", ".node"]`). `context` is optional; when omitted, a built-in Node context is used. + +```js +const resolve = require("enhanced-resolve"); + +resolve(__dirname, "./utils", (err, result) => { + // result === "/abs/path/to/utils.js" +}); +``` + +#### `resolve.sync(context?, path, request, resolveContext?) => string | false` + +Synchronous variant. Throws on failure, returns `false` when the resolve yields no result. + +```js +const file = resolve.sync(__dirname, "./utils"); +``` + +#### `resolve.promise(context?, path, request, resolveContext?) => Promise` + +Promise variant of `resolve`. + +```js +const file = await resolve.promise(__dirname, "./utils"); +``` + +#### `resolve.create(options) => ResolveFunctionAsync` + +Builds a customized async resolve function. Options are the same as for [`ResolverFactory.createResolver`](#resolver-options); `fileSystem` defaults to the built-in Node.js filesystem. + +```js +const resolveTs = resolve.create({ extensions: [".ts", ".tsx", ".js"] }); + +resolveTs(__dirname, "./component", (err, result) => { + // result === "/abs/path/to/component.tsx" +}); +``` + +#### `resolve.create.sync(options) => ResolveFunction` + +Sync variant of `resolve.create`. + +```js +const resolveTsSync = resolve.create.sync({ extensions: [".ts", ".js"] }); +const file = resolveTsSync(__dirname, "./component"); +``` + +#### `resolve.create.promise(options) => ResolveFunctionPromise` + +Promise variant of `resolve.create`. + +```js +const resolveTsPromise = resolve.create.promise({ extensions: [".ts", ".js"] }); +const file = await resolveTsPromise(__dirname, "./component"); +``` + +#### `ResolverFactory.createResolver(options) => Resolver` + +Lower-level factory. Returns a `Resolver` whose `resolve`, `resolveSync`, and `resolvePromise` methods accept `(context, path, request, resolveContext, [callback])`. Use this when you need a reusable resolver instance or access to its `hooks` (see the [Plugins](#plugins) section). `fileSystem` is required here — the high-level `resolve.create` defaults it for you. + +```js +const fs = require("fs"); +const { CachedInputFileSystem, ResolverFactory } = require("enhanced-resolve"); + +const resolver = ResolverFactory.createResolver({ + fileSystem: new CachedInputFileSystem(fs, 4000), + extensions: [".js", ".json"], +}); + +// callback +resolver.resolve({}, __dirname, "./utils", {}, (err, file) => { + // ... +}); + +// sync (requires a sync fileSystem) +const fileSync = resolver.resolveSync({}, __dirname, "./utils"); + +// promise +const filePromise = await resolver.resolvePromise({}, __dirname, "./utils", {}); +``` + +#### `CachedInputFileSystem(fileSystem, duration)` + +Wraps any Node-compatible `fs` to add an in-memory cache for `stat`, `readdir`, `readFile`, `readJson`, and `readlink`. `duration` is the cache TTL in milliseconds (typically `4000`). Call `.purge()` to invalidate, or `.purge(path)` / `.purge([path, ...])` to invalidate specific entries — do this whenever you know files changed (e.g. from a watcher). + +```js +const fs = require("fs"); +const { CachedInputFileSystem } = require("enhanced-resolve"); + +const cachedFs = new CachedInputFileSystem(fs, 4000); +// later, when files change: +cachedFs.purge("/abs/path/to/changed-file.js"); +``` + +#### Exported plugins & helpers + +For use with the `plugins` option or as standalone utilities: + +- `ResolverFactory` — see above. +- `CachedInputFileSystem` — see above. +- `CloneBasenamePlugin(source, target)` — joins the directory's basename onto the path. See [Built-in Plugins](#built-in-plugins). +- `LogInfoPlugin(source)` — logs pipeline state at a hook; enable by passing a `log` function on the `resolveContext`. +- `TsconfigPathsPlugin(options)` — applies `tsconfig.json` `paths` / `baseUrl` mappings; typically configured via the `tsconfig` resolver option instead. +- `forEachBail(array, iterator, callback)` — bail-style async iterator used internally; useful when authoring plugins that try several candidates in order. + +```js +const { LogInfoPlugin } = require("enhanced-resolve"); + +const resolver = ResolverFactory.createResolver({ + fileSystem: cachedFs, + extensions: [".js"], + plugins: [new LogInfoPlugin("described-resolve")], +}); + +resolver.resolve( + {}, + __dirname, + "./utils", + { log: (msg) => console.log(msg) }, + () => {}, +); +``` + +### Creating a Resolver + +The easiest way to create a resolver is to use the `createResolver` function on `ResolveFactory`, along with one of the supplied File System implementations. + +```js +const fs = require("fs"); +const { CachedInputFileSystem, ResolverFactory } = require("enhanced-resolve"); + +// create a resolver +const myResolver = ResolverFactory.createResolver({ + // Typical usage will consume the `fs` + `CachedInputFileSystem`, which wraps Node.js `fs` to add caching. + fileSystem: new CachedInputFileSystem(fs, 4000), + extensions: [".js", ".json"], + /* any other resolver options here. Options/defaults can be seen below */ +}); + +// resolve a file with the new resolver +const context = {}; +const lookupStartPath = "/Users/webpack/some/root/dir"; +const request = "./path/to-look-up.js"; +const resolveContext = {}; + +// callback +myResolver.resolve( + context, + lookupStartPath, + request, + resolveContext, + (err /* Error */, filepath /* string */) => { + // Do something with the path + }, +); + +// promise +try { + const filepath = await myResolver.resolvePromise( + context, + lookupStartPath, + request, + resolveContext, + ); + // Do something with the path +} catch (err) { + // handle resolve failure +} + +// sync (requires a sync fileSystem, e.g. the default Node.js one) +const filepath = myResolver.resolveSync(context, lookupStartPath, request); +``` + +#### Resolver Options + +| Field | Default | Description | +| ------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| alias | [] | A list of module alias configurations or an object which maps key to value | +| aliasFields | [] | A list of alias fields in description files | +| extensionAlias | {} | An object which maps extension to extension aliases | +| extensionAliasForExports | false | Also apply `extensionAlias` to paths resolved through the package.json `exports` field. Off by default (Node.js-aligned) | +| cachePredicate | function() { return true }; | A function which decides whether a request should be cached or not. An object is passed to the function with `path` and `request` properties. | +| cacheWithContext | true | If unsafe cache is enabled, includes `request.context` in the cache key | +| conditionNames | [] | A list of exports field condition names | +| descriptionFiles | ["package.json"] | A list of description files to read from | +| enforceExtension | false | Enforce that a extension from extensions must be used | +| exportsFields | ["exports"] | A list of exports fields in description files | +| extensions | [".js", ".json", ".node"] | A list of extensions which should be tried for files | +| fallback | [] | Same as `alias`, but only used if default resolving fails | +| fileSystem | | The file system which should be used | +| fullySpecified | false | Request passed to resolve is already fully specified and extensions or main files are not resolved for it (they are still resolved for internal requests) | +| mainFields | ["main"] | A list of main fields in description files | +| mainFiles | ["index"] | A list of main files in directories | +| modules | ["node_modules"] | A list of directories to resolve modules from, can be absolute path or folder name | +| plugins | [] | A list of additional resolve plugins which should be applied | +| resolver | undefined | A prepared Resolver to which the plugins are attached | +| resolveToContext | false | Resolve to a context instead of a file | +| preferRelative | false | Prefer to resolve module requests as relative request and fallback to resolving as module | +| preferAbsolute | false | Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots | +| restrictions | [] | A list of resolve restrictions | +| roots | [] | A list of root paths | +| symlinks | true | Whether to resolve symlinks to their symlinked location | +| tsconfig | false | TypeScript config for paths mapping. Can be `false` (disabled), `true` (use default `tsconfig.json`), a string path to `tsconfig.json`, or an object with `configFile`, `references`, and `baseUrl` options. Supports JSONC format (comments and trailing commas) like TypeScript compiler. | +| tsconfig.configFile | tsconfig.json | Path to the tsconfig.json file | +| tsconfig.references | [] | Project references. `'auto'` to load from tsconfig, or an array of paths to referenced projects | +| tsconfig.baseUrl | undefined | Override baseUrl from tsconfig.json. If provided, this value will be used instead of the baseUrl in the tsconfig file | +| unsafeCache | false | Use this cache object to unsafely cache the successful requests | + +#### Option Examples + +Small snippets for the non-obvious options. All options are passed to `resolve.create({ ... })` or `ResolverFactory.createResolver({ ... })`. + +**`alias`** — rewrite matching requests to a target path, module, or to `false` to ignore them. Accepts an object or an array of entries (array form lets you specify ordering / `onlyModule`). + +```js +const options = { + alias: { + "@": path.resolve(__dirname, "src"), // @/utils → src/utils + lodash$: "lodash-es", // exact "lodash", not "lodash/foo" + "ignored-module": false, // short-circuit to an empty module + }, +}; +``` + +**`aliasFields`** — read alias maps from fields in `package.json`. The `browser` field is the common case: + +```js +const options = { aliasFields: ["browser"] }; +``` + +**`extensionAlias`** — maps one request extension to a list of candidate extensions. Useful for TypeScript ESM where imports are written with `.js` but the source is `.ts`. Applies both to direct requests (e.g. `./foo.js`) and to paths produced by the package.json `imports` field (e.g. `#foo` → `./foo.js` → `./foo.ts`). By default it does **not** apply to paths produced by the `exports` field (to stay aligned with Node.js, which does not substitute extensions on package-exported paths) — see `extensionAliasForExports` below to opt in: + +```js +const options = { + extensionAlias: { + ".js": [".ts", ".js"], + ".mjs": [".mts", ".mjs"], + }, +}; +``` + +**`extensionAliasForExports`** — when `true`, also apply `extensionAlias` to paths resolved through the package.json `exports` field. Off by default to match Node.js. Turn it on if you want full alignment with TypeScript's resolver for packages that ship `.ts` sources alongside the compiled `.js` files they list in `exports` (e.g. monorepo source packages, or the `eslint-import-resolver-typescript` use case): + +```js +const options = { + extensionAlias: { ".js": [".ts", ".js"] }, + extensionAliasForExports: true, +}; +``` + +**`conditionNames` + `exportsFields`** — pick which conditions to match in the `exports` field of `package.json`: + +```js +const options = { + conditionNames: ["import", "node", "default"], + exportsFields: ["exports"], +}; +``` + +**`extensions`** — extensions to try for extensionless requests, in order: + +```js +const options = { extensions: [".ts", ".tsx", ".js", ".json"] }; +``` + +**`fallback`** — same shape as `alias`, but only consulted when the primary resolve fails. Handy for polyfills: + +```js +const options = { + fallback: { + crypto: require.resolve("crypto-browserify"), + stream: false, + }, +}; +``` + +**`modules`** — where to look for bare-module requests. Entries can be folder names (searched hierarchically up the tree) or absolute paths (searched directly): + +```js +const options = { modules: [path.resolve(__dirname, "src"), "node_modules"] }; +``` + +**`mainFields` / `mainFiles`** — fields in `package.json` to try for a package entry point, and filenames to try inside a directory: + +```js +const options = { + mainFields: ["browser", "module", "main"], + mainFiles: ["index"], +}; +``` + +**`roots` + `preferAbsolute`** — resolve server-relative URLs (starting with `/`) against one or more root directories. With `preferAbsolute: true`, absolute-path resolution is tried before the roots are consulted. + +```js +const options = { + roots: [path.resolve(__dirname, "public")], + preferAbsolute: false, +}; +``` + +**`restrictions`** — reject results that don't satisfy at least one restriction. Accepts strings (path prefixes) or `RegExp`s: + +```js +const options = { + restrictions: [path.resolve(__dirname, "src"), /\.(js|ts)$/], +}; +``` + +**`tsconfig`** — apply TypeScript `paths` / `baseUrl` mappings. Either pass `true` to load `./tsconfig.json`, a path string, or a configuration object: + +```js +const options = { + tsconfig: { + configFile: path.resolve(__dirname, "tsconfig.json"), + references: "auto", // honor project references declared in tsconfig + }, +}; +``` + +**`symlinks`** — resolve to the real path by following symlinks. Set to `false` to keep the symlinked path (common for monorepo / pnpm layouts where you want module identity tied to the workspace location): + +```js +const options = { symlinks: false }; +``` + +**`fullySpecified`** — require fully-specified requests (no extension inference, no `index` lookup) for non-internal requests. Matches Node.js ESM semantics: + +```js +const options = { fullySpecified: true }; +``` + +**`unsafeCache`** — pass an object to use as an in-memory cache of successful resolves. Set to `true` to let the resolver allocate its own: + +```js +const options = { + unsafeCache: {}, // or true + cacheWithContext: false, // skip context in the cache key — faster, but only safe if context doesn't change the result +}; +``` + +To observe whether a request was served from the cache, wrap the cache object in a `Proxy`. `UnsafeCachePlugin` reads entries with `cache[id]` (cache lookup) and writes them with `cache[id] = result` (cache store), so trapping `get` and `set` is enough to distinguish hits from misses: + +```js +const cache = {}; +const observedCache = new Proxy(cache, { + get(target, name, receiver) { + const hit = name in target; + console.log(hit ? `[cache hit] ${name}` : `[cache miss] ${name}`); + return Reflect.get(target, name, receiver); + }, + set(target, name, value, receiver) { + console.log(`[cache set] ${name}`); + return Reflect.set(target, name, value, receiver); + }, +}); + +const resolver = ResolverFactory.createResolver({ + fileSystem: new CachedInputFileSystem(fs, 4000), + extensions: [".js", ".json"], + unsafeCache: observedCache, +}); +``` + +The `name` argument is the cache id — a `JSON.stringify`'d object containing `type`, `context`, `path`, `query`, `fragment`, and `request` — so you can parse it to report on specific resolves. Only successful resolves go through the cache; failures never touch it. + +**`fileSystem`** — any `fs`-compatible implementation. Usually `new CachedInputFileSystem(fs, 4000)`; can be a virtual filesystem (e.g. `memfs`) for testing: + +```js +const options = { fileSystem: new CachedInputFileSystem(require("fs"), 4000) }; +``` + +**`plugins`** — additional plugin instances appended to the pipeline. See [Plugins](#plugins): + +```js +const options = { + plugins: [new TsconfigPathsPlugin({ configFile: "./tsconfig.json" })], +}; +``` + +## Plugins + +Similar to `webpack`, the core of `enhanced-resolve` functionality is implemented as individual plugins that are executed using [`tapable`](https://github.com/webpack/tapable). +These plugins can extend the functionality of the library, adding other ways for files/contexts to be resolved. + +A plugin should be a `class` (or its ES5 equivalent) with an `apply` method. The `apply` method will receive a `resolver` instance, that can be used to hook in to the event system. + +Plugins are executed in a pipeline, and register which event they should be executed before/after. `source` is the name of the event that starts the pipeline, and `target` is what event this plugin should fire, which is what continues the execution of the pipeline. For a full view of how these plugin events form a chain, see `lib/ResolverFactory.js`, in the `//// pipeline ////` section. + +### Built-in Plugins + +`enhanced-resolve` ships with the following plugins. Most of them are wired up automatically by `ResolverFactory` based on the [resolver options](#resolver-options); the ones exported from the package entry (`TsconfigPathsPlugin`, `CloneBasenamePlugin`, `LogInfoPlugin`) are the ones you're most likely to use explicitly. + +| Plugin | Purpose | +| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `AliasPlugin` | Replaces a matching request with one or more alternative targets. Powers the `alias` and `fallback` options. | +| `AliasFieldPlugin` | Applies aliasing based on a field in the description file (e.g. the `browser` field). Powers `aliasFields`. | +| `AppendPlugin` | Appends a string (typically an extension) to the current path. Used for `extensions`. | +| `CloneBasenamePlugin` | Joins the current directory basename onto the path (e.g. `/foo/bar` → `/foo/bar/bar`). Useful for directory-named main-file schemes. | +| `ConditionalPlugin` | Forwards the request only when it matches a given partial request shape. | +| `DescriptionFilePlugin` | Finds and loads the nearest description file (e.g. `package.json`) so other plugins can read its fields. Powers `descriptionFiles`. | +| `DirectoryExistsPlugin` | Only continues the pipeline if the current path is an existing directory. | +| `ExportsFieldPlugin` | Resolves requests through the `exports` field of a package's description file. Powers `exportsFields` and `conditionNames`. | +| `ExtensionAliasPlugin` | Maps one extension to a list of alternative extensions (e.g. `.js` → `.ts`, `.js`). Powers `extensionAlias`. | +| `FileExistsPlugin` | Only continues the pipeline if the current path is an existing file, and records the file as a dependency. | +| `ImportsFieldPlugin` | Resolves `#name` requests through the `imports` field of the enclosing package. | +| `JoinRequestPlugin` | Joins the current path with the current request into a new path. | +| `JoinRequestPartPlugin` | Splits a module request into module name + inner request, joining the inner request onto the path. | +| `LogInfoPlugin` | Emits verbose log output at a given pipeline step. Handy for debugging resolves via `resolveContext.log`. | +| `MainFieldPlugin` | Uses a field in the description file (e.g. `main`) to point to the entry file of a package. Powers `mainFields`. | +| `ModulesInHierarchicalDirectoriesPlugin` | Searches for a module by walking up parent directories (the standard `node_modules` lookup). Powers `modules`. | +| `ModulesInRootPlugin` | Searches for a module in a single absolute directory. Powers absolute-path entries in `modules`. | +| `NextPlugin` | Forwards the request from one hook to another without modification — glue between pipeline steps. | +| `ParsePlugin` | Parses a raw request string into its components (path, query, fragment, module flag, etc.). | +| `PnpPlugin` | Resolves module requests through a Yarn PnP API when one is available. | +| `RestrictionsPlugin` | Rejects results that don't match a list of path restrictions (strings or regular expressions). Powers `restrictions`. | +| `ResultPlugin` | Terminal plugin that fires the `result` hook — signals a successful resolve. | +| `RootsPlugin` | Resolves server-relative URL requests (starting with `/`) against one or more root directories. Powers `roots`. | +| `SelfReferencePlugin` | Resolves a package self-reference (e.g. `my-pkg/foo` from within `my-pkg`). | +| `SymlinkPlugin` | Real paths the resolved file by following symlinks. Can be disabled via the `symlinks` option. | +| `TryNextPlugin` | Forwards the request to the next hook with a log message. Useful for trying alternative resolutions. | +| `TsconfigPathsPlugin` | Rewrites requests using the `paths` and `baseUrl` from a `tsconfig.json`. Powers the `tsconfig` option. | +| `UnsafeCachePlugin` | Caches successful resolves in an in-memory map to speed up repeated requests. Powers `unsafeCache`. | +| `UseFilePlugin` | Joins a fixed filename onto the current path (e.g. `index`). Powers `mainFiles`. | + +#### Plugin wiring and goals + +One-line goal and default wiring (`source → target`) for each plugin. `*` means the plugin is tapped on several hooks — the common ones are listed. Plugins without a fixed wiring are user-tapped. + +- **`AliasPlugin`** — Goal: redirect requests matching a configured key to an alternative target. `raw-resolve` → `internal-resolve` for `alias`; `file` → `internal-resolve` as a last-chance remap; `described-resolve` → `internal-resolve` for `fallback`. +- **`AliasFieldPlugin`** — Goal: apply aliases declared in a description-file field like `browser`, so environment-specific substitutions happen without user config. `raw-resolve` / `file` → `internal-resolve`. +- **`AppendPlugin`** — Goal: try appending a fixed string (usually an extension) to the current path. `raw-file` → `file`, one instance per entry in `extensions`. +- **`CloneBasenamePlugin`** — Goal: join the directory's basename onto the path (e.g. `/foo/bar` → `/foo/bar/bar`) for directory-named-main layouts. User-wired via `plugins`. +- **`ConditionalPlugin`** — Goal: gate a forward on a partial match of the request shape (e.g. `{ module: true }`), used to fan-out at branching hooks. Tapped on `after-normal-resolve`, `resolve-as-module`, `described-relative`, and `raw-file`. +- **`DescriptionFilePlugin`** — Goal: locate and attach the nearest description file (usually `package.json`) so downstream plugins can read its fields. `parsed-resolve` → `described-resolve`, `relative` → `described-relative`, `undescribed-resolve-in-package` → `resolve-in-package`, `undescribed-existing-directory` → `existing-directory`, `undescribed-raw-file` → `raw-file`. +- **`DirectoryExistsPlugin`** — Goal: only continue the pipeline if the current path exists as a directory. `resolve-as-module` → `undescribed-resolve-in-package`, `directory` → `undescribed-existing-directory`. +- **`ExportsFieldPlugin`** — Goal: map a request through the `exports` field of a package's description file (with `conditionNames`). `resolve-in-package` → `relative`. +- **`ExtensionAliasPlugin`** — Goal: rewrite a request's extension to a list of candidate extensions (e.g. `.js` → `.ts`, `.js`) for TypeScript ESM and similar. `raw-resolve` → `normal-resolve` for direct requests; also `imports-field-relative` → `relative` so extension substitution applies to `imports`-field targets. +- **`FileExistsPlugin`** — Goal: confirm a candidate path exists as a file and record it as a file dependency. `final-file` → `existing-file`. +- **`ImportsFieldPlugin`** — Goal: resolve `#name` requests through the `imports` field of the enclosing package. `internal` → `imports-field-relative` (relative target) or `imports-resolve` (bare target). +- **`JoinRequestPlugin`** — Goal: join the current path with the current request into a single concrete path. `after-normal-resolve` → `relative` (three stage-offset copies for `preferRelative`, `preferAbsolute`, and default), `resolve-in-existing-directory` → `relative`. +- **`JoinRequestPartPlugin`** — Goal: split a module request into module name + inner request, joining the inner part onto the path. `module` → `resolve-as-module`. +- **`LogInfoPlugin`** — Goal: emit verbose log output at a chosen hook; enable by passing a `log` function on `resolveContext`. User-wired via `plugins`. +- **`MainFieldPlugin`** — Goal: follow a description-file field (e.g. `main`, `module`, `browser`) to the entry file of a package. `existing-directory` → `resolve-in-existing-directory`, one instance per entry in `mainFields`. +- **`ModulesInHierarchicalDirectoriesPlugin`** — Goal: search for a module by walking up parent directories (the standard `node_modules` lookup). `raw-module` → `module`; when PnP is enabled, `alternate-raw-module` → `module` too. +- **`ModulesInRootPlugin`** — Goal: search for a module in a single absolute directory (powers absolute-path entries in `modules`). `raw-module` → `module`. +- **`NextPlugin`** — Goal: glue — forward the current request unchanged from one hook to another. Used across the pipeline wherever two hooks should run sequentially. +- **`ParsePlugin`** — Goal: split the raw request string into path / query / fragment / `module` / `directory` / `internal` flags. `resolve` → `parsed-resolve`; also wired on `internal-resolve` and `imports-resolve`. +- **`PnpPlugin`** — Goal: resolve bare-module requests through Yarn's PnP API when available. `raw-module` → `undescribed-resolve-in-package` on hit, `alternate-raw-module` on miss. +- **`RestrictionsPlugin`** — Goal: reject resolved paths that don't satisfy at least one string prefix or RegExp. Tapped on `resolved`. +- **`ResultPlugin`** — Goal: terminal plugin — fires the `result` lifecycle hook and signals a successful resolve. Tapped on `resolved`. +- **`RootsPlugin`** — Goal: resolve server-relative URL requests (starting with `/`) against one or more root directories. `after-normal-resolve` → `relative`. +- **`SelfReferencePlugin`** — Goal: resolve a package self-reference (`my-pkg/foo` from inside `my-pkg`) via its own `exports`. `raw-module` → `resolve-as-module`. +- **`SymlinkPlugin`** — Goal: real-path the resolved file by following symlinks; can be disabled via `symlinks: false`. `existing-file` → `existing-file` (runs via a stage offset on the same hook). +- **`TryNextPlugin`** — Goal: forward the request to another hook with a log message, useful for trying an alternative candidate. `raw-file` → `file` (as the "no extension" attempt) and user-wired. +- **`TsconfigPathsPlugin`** — Goal: rewrite requests using the `paths` and `baseUrl` from a `tsconfig.json` (including project references). Taps `described-resolve` internally and forwards to `internal-resolve`; exported for direct use as well. +- **`UnsafeCachePlugin`** — Goal: cache successful resolves in an in-memory map for repeated requests. `described-resolve` → `raw-resolve` (only when `unsafeCache` is enabled). +- **`UseFilePlugin`** — Goal: join a fixed filename (e.g. `index`) onto the current path to try as an entry file. `existing-directory` / `undescribed-existing-directory` → `undescribed-raw-file`, one instance per entry in `mainFiles`. + +### Hooks + +A resolver exposes two kinds of [`tapable`](https://github.com/webpack/tapable) hooks: + +- **Lifecycle hooks** on `resolver.hooks` — fired by the resolver itself around each `resolve` call. Use these to observe, not to transform the request. +- **Pipeline hooks** — the named steps that plugins tap as `source` and forward to as `target`. Every pipeline hook is an `AsyncSeriesBailHook<[request, resolveContext], request | null>`: return `callback()` to pass on, `callback(err)` to fail, or `callback(null, request)` to short-circuit with a result. Obtain them with `resolver.ensureHook(name)` (creates if missing) or `resolver.getHook(name)` (throws if missing); names are kebab-case or camelCase and are interchangeable. + +#### Lifecycle hooks + +| Hook | Type | Fires when | +| ------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `resolveStep` | `SyncHook` | Every time the resolver hands a request to a pipeline hook. Arguments: `(hook, request)`. Ideal for tracing. | +| `noResolve` | `SyncHook` | When a top-level `resolve()` call can't produce a result. Arguments: `(request, error)`. | +| `resolve` | `AsyncSeriesBailHook` | Entry point of the pipeline (also listed below). Tap this to intercept requests before parsing. | +| `result` | `AsyncSeriesHook` | After a successful resolve, with the final request. Fired by `ResultPlugin`. Tap to observe/record results without short-circuiting. | + +#### Pipeline hooks + +Listed roughly in the order the default pipeline visits them. Full wiring lives in `lib/ResolverFactory.js` under `//// pipeline ////`. + +| Hook | Role | +| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `resolve` | Entry point. `ParsePlugin` parses the raw request (path, query, fragment, module flag) and forwards to `parsed-resolve`. | +| `internal-resolve` | Re-entry point used by internal rewrites (e.g. after an `alias` fires). Same role as `resolve`, but `fullySpecified` is forced off. | +| `imports-resolve` | Re-entry point for the target of an `imports` field match; prevents recursive `#` resolution per the Node.js ESM spec. | +| `parsed-resolve` | Request has been parsed. `DescriptionFilePlugin` attaches the nearest `package.json`, then forwards to `described-resolve`. | +| `described-resolve` | Description file is attached. Where `unsafeCache`, `fallback`, and most user plugins (including `MyLibSrcPlugin` below) hook in. | +| `raw-resolve` | After description. Where `alias`, `aliasFields`, `tsconfig` paths, and `extensionAlias` rewrites fire before default resolution. | +| `normal-resolve` | Default resolution starts. Branches into `relative` (for `./`, `../`, absolute), `raw-module` (bare modules), or `internal` (`#imports`). | +| `internal` | `#name` imports-field entry. `ImportsFieldPlugin` maps the specifier and forwards to `imports-field-relative` or `imports-resolve`. | +| `imports-field-relative` | Concrete path from an `imports`-field match, before the normal `relative` flow. `ExtensionAliasPlugin` taps here so `.js` → `.ts` also fires for `#name` targets. Forwards to `relative`. | +| `raw-module` | Bare-module lookup. `SelfReferencePlugin`, `ModulesInHierarchicalDirectoriesPlugin`, `ModulesInRootPlugin`, and `PnpPlugin` all tap here. | +| `alternate-raw-module` | Fallback module lookup used by `PnpPlugin` when PnP can't resolve and `node_modules` should be tried. | +| `module` | A candidate module directory was built. `JoinRequestPartPlugin` splits off the inner request and forwards to `resolve-as-module`. | +| `resolve-as-module` | Treat candidate as a package. `DirectoryExistsPlugin` gates on existence; short single-file modules may re-enter via `undescribed-raw-file`. | +| `undescribed-resolve-in-package` | Inside a located package directory, before its `package.json` has been read. Loads the description, forwards to `resolve-in-package`. | +| `resolve-in-package` | Inside a package with its description loaded. `ExportsFieldPlugin` matches `exports`, otherwise forwards to `resolve-in-existing-directory`. | +| `resolve-in-existing-directory` | Package directory confirmed; join the remaining request onto it and continue at `relative`. | +| `relative` | A concrete path on disk. `DescriptionFilePlugin` loads the nearest `package.json` and forwards to `described-relative`. | +| `described-relative` | Branches to `raw-file` (treat as file) and `directory` (treat as directory). `resolveToContext` skips the file branch. | +| `directory` | Candidate directory. `DirectoryExistsPlugin` gates on existence and forwards to `undescribed-existing-directory`. | +| `undescribed-existing-directory` | Existing directory, before its `package.json` has been read. `UseFilePlugin` tries `mainFiles` via `undescribed-raw-file`. | +| `existing-directory` | Existing directory with description loaded. `MainFieldPlugin` tries `mainFields`; `UseFilePlugin` falls back to `mainFiles`. | +| `undescribed-raw-file` | Candidate file path, before description is read. Loads description, then forwards to `raw-file`. | +| `raw-file` | Apply extension handling: `ConditionalPlugin` short-circuits when `fullySpecified`, `TryNextPlugin` + `AppendPlugin` try each extension. | +| `file` | A specific file path. Last place `alias` and `aliasFields` can redirect; forwards to `final-file`. | +| `final-file` | `FileExistsPlugin` checks the file is real and records it as a file dependency, then forwards to `existing-file`. | +| `existing-file` | Real file on disk. `SymlinkPlugin` real-paths symlinks (unless `symlinks: false`), then forwards to `resolved`. | +| `resolved` | Terminal hook. `RestrictionsPlugin` enforces `restrictions`; `ResultPlugin` fires the `result` lifecycle hook. | + +#### `before-` and `after-` prefixes + +`ensureHook("before-foo")` and `getHook("before-foo")` return the `foo` hook with `stage: -10`; `after-foo` returns it with `stage: 10`. Use this to tap earlier or later than the default stage without creating a separate hook. You'll see `after-parsed-resolve`, `after-normal-resolve`, `after-relative`, and `after-undescribed-resolve-in-package` used this way inside `ResolverFactory`. + +#### Request flow by request type + +The same 26 pipeline hooks serve every request, but different request shapes take different paths through them. Each `➝` below is one `doResolve` / `NextPlugin` / plugin forward; `resolveStep` fires on every arrow, so tapping it (see [Hook examples](#hook-examples)) prints these chains live. + +Relative path (`./utils` from `/src/index.js`) — the default "resolve on disk" path: + +```text +resolve (ParsePlugin) + ➝ parsed-resolve (DescriptionFilePlugin attaches nearest package.json) + ➝ described-resolve (NextPlugin; or UnsafeCachePlugin short-circuit) + ➝ raw-resolve (NextPlugin; alias/tsconfig would branch here) + ➝ normal-resolve (JoinRequestPlugin: path=/src/utils, request="") + ➝ relative (DescriptionFilePlugin loads /src/package.json) + ➝ described-relative (branches to file and directory candidates) + ├─ ➝ raw-file (ConditionalPlugin / TryNextPlugin) + │ ➝ file (AppendPlugin tried each extension, e.g. .js) + │ ➝ final-file (FileExistsPlugin confirms the file) + │ ➝ existing-file (SymlinkPlugin real-paths it) + │ ➝ resolved (RestrictionsPlugin → ResultPlugin) + └─ ➝ directory (DirectoryExistsPlugin; used when path is a dir) + ➝ undescribed-existing-directory + ➝ existing-directory (MainFieldPlugin tries "main", UseFilePlugin tries "index") + ➝ undescribed-raw-file ➝ raw-file ➝ … +``` + +Bare module (`lodash/merge`) — walks up `node_modules`, then treats the hit as a package: + +```text +resolve ➝ parsed-resolve ➝ described-resolve ➝ raw-resolve ➝ normal-resolve + ➝ raw-module (ConditionalPlugin {module:true}) + ➝ module (ModulesInHierarchicalDirectoriesPlugin walks + /src/node_modules, /node_modules, …) + ➝ resolve-as-module (JoinRequestPartPlugin splits "lodash" / "./merge") + ➝ undescribed-resolve-in-package (DirectoryExistsPlugin gates on lodash/ existing) + ➝ resolve-in-package (DescriptionFilePlugin loads lodash/package.json) + ├─ ➝ relative (ExportsFieldPlugin, if "exports" matches) + └─ ➝ resolve-in-existing-directory (otherwise; JoinRequestPlugin joins "./merge") + ➝ relative ➝ … (same tail as the relative flow above) +``` + +Internal import (`#util` from inside a package) — re-enters the pipeline after mapping: + +```text +resolve ➝ parsed-resolve ➝ described-resolve ➝ raw-resolve ➝ normal-resolve + ➝ internal (ConditionalPlugin {internal:true}) + ➝ imports-resolve (ImportsFieldPlugin mapped "#util" to a bare target) + ➝ parsed-resolve ➝ … (fresh pipeline run, internal:false so # isn't remapped) +``` + +When the `imports` field maps to a relative target, the branch instead goes: + +```text + ➝ internal + ➝ imports-field-relative (ImportsFieldPlugin mapped "#util" to "./util.js"; + ExtensionAliasPlugin can swap .js → .ts here) + ➝ relative ➝ … (same tail as the relative flow above) +``` + +Alias hit (`@/button` with `alias: { "@": "/src" }`) — rewrites then restarts: + +```text +resolve ➝ parsed-resolve ➝ described-resolve + ➝ raw-resolve + ➝ internal-resolve (AliasPlugin rewrote request → "/src/button") + ➝ parsed-resolve ➝ … (fullySpecified forced off; AliasPlugin won't re-fire for the rewritten form) +``` + +`exports`-field hit inside a package (`pkg/feature` matching `"./feature"` in `exports`): + +```text +… ➝ raw-module ➝ module ➝ resolve-as-module ➝ undescribed-resolve-in-package + ➝ resolve-in-package + ➝ relative (ExportsFieldPlugin jumped to the exports target; + main-field / main-file logic is skipped) + ➝ described-relative ➝ raw-file ➝ file ➝ final-file ➝ existing-file ➝ resolved +``` + +Failure — every candidate opts out (`callback()`) and no handler ever short-circuits with a result. `noResolve` fires once, for the top-level request: + +```text +… ➝ final-file + ✗ FileExistsPlugin: ENOENT (opts out; no extension candidates left) + ⇠ bail hooks unwind, each tapped handler has already tried its alternatives + ⇒ top-level resolve() returns no result + ⇒ resolver.hooks.noResolve(request, error) (ResultPlugin never fires) +``` + +#### Hook examples + +Trace every pipeline step and observe failures via the lifecycle hooks: + +```js +resolver.hooks.resolveStep.tap("Trace", (hook, request) => { + console.log(`[step] ${hook.name}: ${request.request} @ ${request.path}`); +}); +resolver.hooks.noResolve.tap("Trace", (request, error) => { + console.log(`[fail] ${request.request}: ${error.message}`); +}); +resolver.hooks.result.tapAsync("Trace", (request, _ctx, callback) => { + console.log(`[done] ${request.path}`); + callback(); +}); +``` + +Short-circuit at `file` to redirect any `.css` request to a stub without continuing the pipeline: + +```js +class StubCssPlugin { + apply(resolver) { + resolver + .getHook("file") + .tapAsync("StubCssPlugin", (request, _ctx, callback) => { + if (!request.path || !request.path.endsWith(".css")) return callback(); + callback(null, { ...request, path: require.resolve("./empty.css") }); + }); + } +} +``` + +Forward to a different hook with `doResolve` to restart resolution with a rewritten request — see `MyLibSrcPlugin` in [Writing a Custom Plugin](#writing-a-custom-plugin) for the canonical pattern (`getHook("described-resolve")` → `doResolve(ensureHook("resolve"), …)`). + +### Writing a Custom Plugin + +The example below adds a plugin that rewrites any request starting with `my-lib/` to `my-lib/src/`. It taps the `described-resolve` hook (after the description file has been located) and forwards the rewritten request to `resolve`, so the pipeline restarts with the new request. + +```js +const fs = require("fs"); +const { CachedInputFileSystem, ResolverFactory } = require("enhanced-resolve"); + +class MyLibSrcPlugin { + apply(resolver) { + const target = resolver.ensureHook("resolve"); + resolver + .getHook("described-resolve") + .tapAsync("MyLibSrcPlugin", (request, resolveContext, callback) => { + if (!request.request || !request.request.startsWith("my-lib/")) { + return callback(); + } + const newRequest = { + ...request, + request: request.request.replace(/^my-lib\//, "my-lib/src/"), + }; + resolver.doResolve( + target, + newRequest, + "rewrote my-lib → my-lib/src", + resolveContext, + callback, + ); + }); + } +} + +const myResolver = ResolverFactory.createResolver({ + fileSystem: new CachedInputFileSystem(fs, 4000), + extensions: [".js", ".json"], + plugins: [new MyLibSrcPlugin()], +}); +``` + +Tips for writing your own plugin: + +- Call `callback()` with no arguments to pass the request on to the next tapped handler at the same `source` hook. This is how you "opt out" when a request doesn't apply. +- Call `resolver.doResolve(target, newRequest, message, resolveContext, callback)` to continue the pipeline at a different hook with a (possibly modified) request. +- Return early with `callback(null, result)` to short-circuit with a specific result, or `callback(err)` to fail the resolve. +- See [Hooks](#hooks) for the full list of pipeline hooks, their order, and the `before-` / `after-` stage modifiers. `lib/ResolverFactory.js` has the exact wiring under `//// pipeline ////`. + +## Escaping + +It's allowed to escape `#` as `\0#` to avoid parsing it as fragment. + +enhanced-resolve will try to resolve requests containing `#` as path and as fragment, so it will automatically figure out if `./some#thing` means `.../some.js#thing` or `.../some#thing.js`. When a `#` is resolved as path it will be escaped in the result. Here: `.../some\0#thing.js`. + +## Tests + +```sh +npm run test +``` + +## Passing options from webpack + +If you are using `webpack`, and you want to pass custom options to `enhanced-resolve`, the options are passed from the `resolve` key of your webpack configuration e.g.: + +``` +resolve: { + extensions: ['.js', '.jsx'], + modules: [path.resolve(__dirname, 'src'), 'node_modules'], + plugins: [new DirectoryNamedWebpackPlugin()] + ... +}, +``` + +## License + +Copyright (c) 2012-2019 JS Foundation and other contributors + +MIT (http://www.opensource.org/licenses/mit-license.php) + +[npm]: https://img.shields.io/npm/v/enhanced-resolve.svg +[npm-url]: https://www.npmjs.com/package/enhanced-resolve +[build-status]: https://github.com/webpack/enhanced-resolve/actions/workflows/test.yml/badge.svg +[build-status-url]: https://github.com/webpack/enhanced-resolve/actions +[codecov-badge]: https://codecov.io/gh/webpack/enhanced-resolve/branch/main/graph/badge.svg?token=6B6NxtsZc3 +[codecov-url]: https://codecov.io/gh/webpack/enhanced-resolve +[size]: https://packagephobia.com/badge?p=enhanced-resolve +[size-url]: https://packagephobia.com/result?p=enhanced-resolve +[discussion]: https://img.shields.io/github/discussions/webpack/webpack +[discussion-url]: https://github.com/webpack/webpack/discussions diff --git a/client/node_modules/enhanced-resolve/lib/AliasFieldPlugin.js b/client/node_modules/enhanced-resolve/lib/AliasFieldPlugin.js new file mode 100644 index 0000000..0e80347 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/AliasFieldPlugin.js @@ -0,0 +1,123 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const DescriptionFileUtils = require("./DescriptionFileUtils"); +const getInnerRequest = require("./getInnerRequest"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonPrimitive} JsonPrimitive */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +// Sentinel stored in `_fieldDataCache` when a description file does not +// contain a usable alias field object. Lets us distinguish "not cached yet" +// from "no valid field" without calling back into `getField`. +const NO_FIELD_OBJECT = Symbol("NoFieldObject"); + +module.exports = class AliasFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | string[]} field field + * @param {string | ResolveStepHook} target target + */ + constructor(source, field, target) { + this.source = source; + this.field = field; + this.target = target; + // `this.field` is fixed for the plugin's lifetime, so caching + // per description-file content is safe. The cached value is either + // the resolved alias-map object or the `NO_FIELD_OBJECT` sentinel + // meaning "description file has no usable alias field". + /** @type {WeakMap} */ + this._fieldDataCache = new WeakMap(); + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("AliasFieldPlugin", (request, resolveContext, callback) => { + if (!request.descriptionFileData) return callback(); + const innerRequest = getInnerRequest(resolver, request); + if (!innerRequest) return callback(); + const { descriptionFileData } = request; + let fieldData = this._fieldDataCache.get(descriptionFileData); + if (fieldData === undefined) { + const raw = DescriptionFileUtils.getField( + descriptionFileData, + this.field, + ); + fieldData = + raw === null || typeof raw !== "object" + ? NO_FIELD_OBJECT + : /** @type {{ [k: string]: JsonPrimitive }} */ (raw); + this._fieldDataCache.set(descriptionFileData, fieldData); + } + if (fieldData === NO_FIELD_OBJECT) { + if (resolveContext.log) { + resolveContext.log( + `Field '${this.field}' doesn't contain a valid alias configuration`, + ); + } + return callback(); + } + /** @type {JsonPrimitive | undefined} */ + const data = Object.prototype.hasOwnProperty.call( + fieldData, + innerRequest, + ) + ? /** @type {{ [Key in string]: JsonPrimitive }} */ (fieldData)[ + innerRequest + ] + : innerRequest.startsWith("./") + ? /** @type {{ [Key in string]: JsonPrimitive }} */ (fieldData)[ + innerRequest.slice(2) + ] + : undefined; + if (data === innerRequest) return callback(); + if (data === undefined) return callback(); + if (data === false) { + /** @type {ResolveRequest} */ + const ignoreObj = { + ...request, + path: false, + }; + if (typeof resolveContext.yield === "function") { + resolveContext.yield(ignoreObj); + return callback(null, null); + } + return callback(null, ignoreObj); + } + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: /** @type {string} */ (request.descriptionFileRoot), + request: /** @type {string} */ (data), + fullySpecified: false, + }; + resolver.doResolve( + target, + obj, + `aliased from description file ${ + request.descriptionFilePath + } with mapping '${innerRequest}' to '${/** @type {string} */ data}'`, + resolveContext, + (err, result) => { + if (err) return callback(err); + + // Don't allow other aliasing or raw request + if (result === undefined) return callback(null, null); + callback(null, result); + }, + ); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/AliasPlugin.js b/client/node_modules/enhanced-resolve/lib/AliasPlugin.js new file mode 100644 index 0000000..608d270 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/AliasPlugin.js @@ -0,0 +1,63 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {string | string[] | false} Alias */ +/** @typedef {{ alias: Alias, name: string, onlyModule?: boolean }} AliasOption */ + +const { aliasResolveHandler, compileAliasOptions } = require("./AliasUtils"); + +/** + * When `alias` is given as an array, the targets are tried in priority + * order and the first matching one wins. Tried-and-failed higher-priority + * targets are recorded on `resolveContext.missingDependencies` (via the + * downstream `FileExistsPlugin`) so that a consumer's watcher can + * invalidate the resolve once one of them appears. The winning target is + * recorded on `resolveContext.fileDependencies`; its removal triggers + * re-resolution, at which point the fallback target is returned. + * + * Callers that cache successful resolves (e.g. webpack's `unsafeCache`) + * are responsible for invalidating those entries when the tracked + * dependencies change -- otherwise a stale path may survive across + * rebuilds even though this plugin itself would return the correct + * fallback on a fresh resolve. + */ +module.exports = class AliasPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {AliasOption | AliasOption[]} options options + * @param {string | ResolveStepHook} target target + */ + constructor(source, options, target) { + this.source = source; + this.options = Array.isArray(options) ? options : [options]; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const compiled = compileAliasOptions(resolver, this.options); + + resolver + .getHook(this.source) + .tapAsync("AliasPlugin", (request, resolveContext, callback) => { + aliasResolveHandler( + resolver, + compiled, + target, + request, + resolveContext, + callback, + ); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/AliasUtils.js b/client/node_modules/enhanced-resolve/lib/AliasUtils.js new file mode 100644 index 0000000..e4ab4cb --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/AliasUtils.js @@ -0,0 +1,333 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const forEachBail = require("./forEachBail"); +const { PathType, getType } = require("./util/path"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./Resolver").ResolveCallback} ResolveCallback */ +/** @typedef {string | string[] | false} Alias */ +/** @typedef {{ alias: Alias, name: string, onlyModule?: boolean }} AliasOption */ + +/** + * @typedef {object} CompiledAliasOption + * @property {string} name original alias name + * @property {string} nameWithSlash name + "/" — precomputed to avoid per-resolve concat + * @property {Alias} alias alias target(s) + * @property {boolean} onlyModule normalized onlyModule flag + * @property {string | null} absolutePath absolute form of `name` (with slash ending), null when not absolute + * @property {string | null} wildcardPrefix substring before the single "*" in `name`, null when no wildcard + * @property {string | null} wildcardSuffix substring after the single "*" in `name`, null when no wildcard + * @property {number} firstCharCode first character code of `name` — used as a cheap screen on the hot path. `-1` indicates "matches any first char" (empty wildcard prefix). + * @property {boolean} arrayAlias true when `alias` is an array — precomputed so the hot path skips `Array.isArray` + */ + +/** + * Bucketed view of compiled options used by `aliasResolveHandler` to avoid + * walking the full option list on every resolve. The `all` array preserves + * the legacy linear order (declaration order) for the fallback path. The + * `byFirstChar` map buckets options by the first char code of their `name` + * — each bucket preserves declaration order among its members. The + * `hasAnyFirstChar` flag is true when at least one option matches any + * first char (`firstCharCode === -1`), in which case resolve-time scans + * fall back to `all` to keep declaration-order semantics across buckets. + * The `useBuckets` flag is true only when bucketing would actually help — + * i.e. there are at least 2 distinct first chars AND no empty-prefix + * wildcard. When false, the resolve hot path skips the `Map.get` and + * iterates `all` directly with the per-option first-char-code screen + * (matching the pre-bucketing behavior). This avoids paying for `Map.get` + * on degenerate single-bucket lists like a long chain of aliases that + * all share one first char — the bucket lookup adds overhead without + * narrowing the candidate set, which showed up as a transient-memory + * regression on `pathological-deep-stack`. + * @typedef {object} CompiledAliasOptions + * @property {CompiledAliasOption[]} all declaration-ordered list + * @property {Map} byFirstChar bucketed by first char code + * @property {boolean} hasAnyFirstChar true when an empty-prefix wildcard is present + * @property {boolean} useBuckets true when the bucket fast-path should be used at resolve time + */ + +const EMPTY_LIST = /** @type {CompiledAliasOption[]} */ ([]); +const EMPTY_COMPILED_OPTIONS = /** @type {CompiledAliasOptions} */ ({ + all: EMPTY_LIST, + byFirstChar: new Map(), + hasAnyFirstChar: false, + useBuckets: false, +}); + +/** + * Precompute per-option strings used on every resolve so the hot path in + * `aliasResolveHandler` does no string concatenation / split work per entry. + * Called once per plugin apply — the returned structure is stable for the + * lifetime of the resolver. + * + * Beyond the per-option precompute step, this also partitions the list into + * a `byFirstChar` map so that, when no "empty-prefix" wildcards are + * present, the resolve-time scan only walks options whose `name` starts + * with the same char as the current request. For large alias lists (300+ + * entries) this turns an O(N) screen into O(K) where K is the bucket size + * for the request's first char. + * @param {Resolver} resolver resolver + * @param {AliasOption[]} options options + * @returns {CompiledAliasOptions} compiled options + */ +function compileAliasOptions(resolver, options) { + if (options.length === 0) return EMPTY_COMPILED_OPTIONS; + const all = /** @type {CompiledAliasOption[]} */ ( + Array.from({ length: options.length }) + ); + /** @type {Map} */ + const byFirstChar = new Map(); + let hasAnyFirstChar = false; + for (let i = 0; i < options.length; i++) { + const item = options[i]; + const { name } = item; + let absolutePath = null; + const type = getType(name); + if (type === PathType.AbsolutePosix || type === PathType.AbsoluteWin) { + absolutePath = resolver.join(name, "_").slice(0, -1); + } + const firstStar = name.indexOf("*"); + let wildcardPrefix = null; + let wildcardSuffix = null; + if (firstStar !== -1 && !name.includes("*", firstStar + 1)) { + wildcardPrefix = name.slice(0, firstStar); + wildcardSuffix = name.slice(firstStar + 1); + } + // firstCharCode: used by `aliasResolveHandler` to quickly skip aliases + // whose name can't possibly match the current innerRequest. For a plain + // alias (no wildcard) the first char of the name is also the first char + // of `nameWithSlash` and of `absolutePath` (since the latter is derived + // from name via `resolver.join(name, "_")`, which only appends). For a + // wildcard with a non-empty prefix, the first char of that prefix is + // also the first char of name. Only the `name === "*"` case (empty + // wildcard prefix) can match arbitrary first chars — encode that as -1. + let firstCharCode; + if (wildcardPrefix !== null && wildcardPrefix.length === 0) { + firstCharCode = -1; + } else { + firstCharCode = name.length > 0 ? name.charCodeAt(0) : -1; + } + const compiled = { + name, + nameWithSlash: `${name}/`, + alias: item.alias, + onlyModule: Boolean(item.onlyModule), + absolutePath, + wildcardPrefix, + wildcardSuffix, + firstCharCode, + arrayAlias: Array.isArray(item.alias), + }; + all[i] = compiled; + if (firstCharCode === -1) { + hasAnyFirstChar = true; + } else { + let bucket = byFirstChar.get(firstCharCode); + if (bucket === undefined) { + bucket = []; + byFirstChar.set(firstCharCode, bucket); + } + bucket.push(compiled); + } + } + // Only enable the bucket fast-path when it would actually help. With + // a single bucket (all aliases share one first char, e.g. a chain of + // `chain-0 -> chain-1 -> …` rewrites), the resolve-time `Map.get` + // does no discrimination — every request lands in that one bucket + // or in nothing — and the lookup is overhead compared to walking + // `all` with the per-option first-char-code screen. Requiring 2+ + // distinct first chars matches the cases where bucketing has + // measurable benefit (huge-alias-* / large-alias-list / stack-churn). + const useBuckets = !hasAnyFirstChar && byFirstChar.size >= 2; + return { all, byFirstChar, hasAnyFirstChar, useBuckets }; +} + +/** @typedef {(err?: null | Error, result?: null | ResolveRequest) => void} InnerCallback */ +/** + * @param {Resolver} resolver resolver + * @param {CompiledAliasOptions} options compiled options + * @param {ResolveStepHook} target target + * @param {ResolveRequest} request request + * @param {ResolveContext} resolveContext resolve context + * @param {InnerCallback} callback callback + * @returns {void} + */ +function aliasResolveHandler( + resolver, + options, + target, + request, + resolveContext, + callback, +) { + if (options.all.length === 0) return callback(); + const innerRequest = request.request || request.path; + if (!innerRequest) return callback(); + + // Precompute values used in the inner scan loop so we don't recompute + // them per option. This is meaningful when `options` has hundreds of + // entries (e.g. monorepos with generated alias lists) — see the + // `huge-alias-list` / `huge-alias-miss` benchmarks. + const innerFirstCharCode = innerRequest.charCodeAt(0); + const hasRequestString = Boolean(request.request); + + // Dispatch through the first-char-code bucket when it actually + // narrows the candidate set (`useBuckets` requires 2+ distinct + // first chars and no empty-prefix wildcard). When the field has + // only one first-char bucket — e.g. a long chain of `chain-N` + // aliases that all start with the same char — every request lands + // in that one bucket or nothing, so `Map.get` is overhead vs. just + // walking `all` with the per-option char-code screen. Walking + // `all` also matches the pre-bucketing behavior and keeps the + // `pathological-deep-stack` allocation profile flat. + let scan; + if (options.useBuckets) { + const bucket = options.byFirstChar.get(innerFirstCharCode); + if (bucket === undefined) return callback(); + scan = bucket; + } else { + scan = options.all; + } + + forEachBail( + scan, + (item, callback) => { + // Char-code screen left in for the fallback (`options.all`) path + // where the bucket dispatch above wasn't usable. In the bucket + // path this is always true and folds into a no-op. + const { firstCharCode } = item; + if (firstCharCode !== -1 && firstCharCode !== innerFirstCharCode) { + return callback(); + } + + /** @type {boolean} */ + let shouldStop = false; + + // For absolute-name aliases, accept the normalized + // `absolutePath` form as well as the raw `nameWithSlash`. + // `nameWithSlash` unconditionally appends `/`, so a raw + // windows request with native backslashes + // (e.g. `C:\\abs\\foo\\baz` against `name: "C:\\abs\\foo"`) + // otherwise fails `startsWith("C:\\abs\\foo/")` and is + // silently skipped. Mirroring the `absolutePath` check in + // both branches closes the gap without changing any + // existing matches. + const { absolutePath } = item; + const matchRequest = + innerRequest === item.name || + (!item.onlyModule && + ((hasRequestString && innerRequest.startsWith(item.nameWithSlash)) || + (absolutePath !== null && innerRequest.startsWith(absolutePath)))); + + const matchWildcard = !item.onlyModule && item.wildcardPrefix !== null; + + if (matchRequest || matchWildcard) { + /** + * @param {Alias} alias alias + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @returns {void} + */ + const resolveWithAlias = (alias, callback) => { + if (alias === false) { + /** @type {ResolveRequest} */ + const ignoreObj = { + ...request, + path: false, + }; + if (typeof resolveContext.yield === "function") { + resolveContext.yield(ignoreObj); + return callback(null, null); + } + return callback(null, ignoreObj); + } + + let newRequestStr; + + if ( + matchWildcard && + innerRequest.startsWith( + /** @type {string} */ (item.wildcardPrefix), + ) && + innerRequest.endsWith(/** @type {string} */ (item.wildcardSuffix)) + ) { + const match = innerRequest.slice( + /** @type {string} */ (item.wildcardPrefix).length, + innerRequest.length - + /** @type {string} */ (item.wildcardSuffix).length, + ); + newRequestStr = alias.toString().replace("*", match); + } + + if ( + matchRequest && + innerRequest !== alias && + !innerRequest.startsWith(`${alias}/`) + ) { + /** @type {string} */ + const remainingRequest = innerRequest.slice(item.name.length); + newRequestStr = alias + remainingRequest; + } + + if (newRequestStr !== undefined) { + shouldStop = true; + /** @type {ResolveRequest} */ + const obj = { + ...request, + request: newRequestStr, + fullySpecified: false, + }; + return resolver.doResolve( + target, + obj, + `aliased with mapping '${item.name}': '${alias}' to '${newRequestStr}'`, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + return callback(); + }, + ); + } + return callback(); + }; + + /** + * @param {(null | Error)=} err error + * @param {(null | ResolveRequest)=} result result + * @returns {void} + */ + const stoppingCallback = (err, result) => { + if (err) return callback(err); + + if (result) return callback(null, result); + // Don't allow other aliasing or raw request + if (shouldStop) return callback(null, null); + return callback(); + }; + + if (item.arrayAlias) { + return forEachBail( + /** @type {string[]} */ (item.alias), + resolveWithAlias, + stoppingCallback, + ); + } + return resolveWithAlias(item.alias, stoppingCallback); + } + + return callback(); + }, + callback, + ); +} + +module.exports.aliasResolveHandler = aliasResolveHandler; +module.exports.compileAliasOptions = compileAliasOptions; diff --git a/client/node_modules/enhanced-resolve/lib/AppendPlugin.js b/client/node_modules/enhanced-resolve/lib/AppendPlugin.js new file mode 100644 index 0000000..6763d52 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/AppendPlugin.js @@ -0,0 +1,49 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class AppendPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} appending appending + * @param {string | ResolveStepHook} target target + */ + constructor(source, appending, target) { + this.source = source; + this.appending = appending; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("AppendPlugin", (request, resolveContext, callback) => { + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: request.path + this.appending, + relativePath: + request.relativePath && request.relativePath + this.appending, + }; + resolver.doResolve( + target, + obj, + this.appending, + resolveContext, + callback, + ); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js b/client/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js new file mode 100644 index 0000000..17e66a9 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js @@ -0,0 +1,686 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +// eslint-disable-next-line n/prefer-global/process +const { nextTick } = require("process"); + +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").PathLike} PathLike */ +/** @typedef {import("./Resolver").PathOrFileDescriptor} PathOrFileDescriptor */ +/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ +/** @typedef {FileSystem & SyncFileSystem} BaseFileSystem */ + +/** + * @template T + * @typedef {import("./Resolver").FileSystemCallback} FileSystemCallback + */ + +/** + * @param {string} path path + * @returns {string} dirname + */ +const dirname = (path) => { + let idx = path.length - 1; + while (idx >= 0) { + const char = path.charCodeAt(idx); + // slash or backslash + if (char === 47 || char === 92) break; + idx--; + } + if (idx < 0) return ""; + return path.slice(0, idx); +}; + +/** + * @template T + * @param {FileSystemCallback[]} callbacks callbacks + * @param {Error | null} err error + * @param {T} result result + */ +const runCallbacks = (callbacks, err, result) => { + if (callbacks.length === 1) { + callbacks[0](err, result); + callbacks.length = 0; + return; + } + let error; + for (const callback of callbacks) { + try { + callback(err, result); + } catch (err) { + if (!error) error = err; + } + } + callbacks.length = 0; + if (error) throw error; +}; + +// eslint-disable-next-line jsdoc/reject-function-type +/** @typedef {Function} EXPECTED_FUNCTION */ +// eslint-disable-next-line jsdoc/reject-any-type +/** @typedef {any} EXPECTED_ANY */ + +class OperationMergerBackend { + /** + * @param {EXPECTED_FUNCTION | undefined} provider async method in filesystem + * @param {EXPECTED_FUNCTION | undefined} syncProvider sync method in filesystem + * @param {BaseFileSystem} providerContext call context for the provider methods + */ + constructor(provider, syncProvider, providerContext) { + this._provider = provider; + this._syncProvider = syncProvider; + this._providerContext = providerContext; + this._activeAsyncOperations = new Map(); + + this.provide = this._provider + ? // Comment to align jsdoc + /** + * @param {PathLike | PathOrFileDescriptor} path path + * @param {object | FileSystemCallback | undefined} options options + * @param {FileSystemCallback=} callback callback + * @returns {EXPECTED_ANY} result + */ + (path, options, callback) => { + if (typeof options === "function") { + callback = + /** @type {FileSystemCallback} */ + (options); + options = undefined; + } + if ( + typeof path !== "string" && + !Buffer.isBuffer(path) && + !(path instanceof URL) && + typeof path !== "number" + ) { + /** @type {EXPECTED_FUNCTION} */ + (callback)( + new TypeError("path must be a string, Buffer, URL or number"), + ); + return; + } + if (options) { + return /** @type {EXPECTED_FUNCTION} */ (this._provider).call( + this._providerContext, + path, + options, + callback, + ); + } + let callbacks = this._activeAsyncOperations.get(path); + if (callbacks) { + callbacks.push(callback); + return; + } + this._activeAsyncOperations.set(path, (callbacks = [callback])); + /** @type {EXPECTED_FUNCTION} */ + (provider)( + path, + /** + * @param {Error} err error + * @param {EXPECTED_ANY} result result + */ + (err, result) => { + this._activeAsyncOperations.delete(path); + runCallbacks(callbacks, err, result); + }, + ); + } + : null; + this.provideSync = this._syncProvider + ? // Comment to align jsdoc + /** + * @param {PathLike | PathOrFileDescriptor} path path + * @param {object=} options options + * @returns {EXPECTED_ANY} result + */ + (path, options) => + /** @type {EXPECTED_FUNCTION} */ (this._syncProvider).call( + this._providerContext, + path, + options, + ) + : null; + } + + purge() {} + + purgeParent() {} +} + +/* + +IDLE: + insert data: goto SYNC + +SYNC: + before provide: run ticks + event loop tick: goto ASYNC_ACTIVE + +ASYNC: + timeout: run tick, goto ASYNC_PASSIVE + +ASYNC_PASSIVE: + before provide: run ticks + +IDLE --[insert data]--> SYNC --[event loop tick]--> ASYNC_ACTIVE --[interval tick]-> ASYNC_PASSIVE + ^ | + +---------[insert data]-------+ +*/ + +const STORAGE_MODE_IDLE = 0; +const STORAGE_MODE_SYNC = 1; +const STORAGE_MODE_ASYNC = 2; + +/** + * @callback Provide + * @param {PathLike | PathOrFileDescriptor} path path + * @param {EXPECTED_ANY} options options + * @param {FileSystemCallback} callback callback + * @returns {void} + */ + +class CacheBackend { + /** + * @param {number} duration max cache duration of items + * @param {EXPECTED_FUNCTION | undefined} provider async method + * @param {EXPECTED_FUNCTION | undefined} syncProvider sync method + * @param {BaseFileSystem} providerContext call context for the provider methods + */ + constructor(duration, provider, syncProvider, providerContext) { + this._duration = duration; + this._provider = provider; + this._syncProvider = syncProvider; + this._providerContext = providerContext; + /** @type {Map[]>} */ + this._activeAsyncOperations = new Map(); + /** @type {Map }>} */ + this._data = new Map(); + /** @type {Set[]} */ + this._levels = []; + for (let i = 0; i < 10; i++) this._levels.push(new Set()); + if (duration !== Infinity) { + for (let i = 5000; i < duration; i += 500) { + this._levels.push(new Set()); + } + } + this._currentLevel = 0; + this._tickInterval = Math.floor(duration / this._levels.length); + /** @type {STORAGE_MODE_IDLE | STORAGE_MODE_SYNC | STORAGE_MODE_ASYNC} */ + this._mode = STORAGE_MODE_IDLE; + + /** @type {NodeJS.Timeout | undefined} */ + this._timeout = undefined; + /** @type {number | undefined} */ + this._nextDecay = undefined; + + // eslint-disable-next-line no-warning-comments + // @ts-ignore + this.provide = provider ? this.provide.bind(this) : null; + // eslint-disable-next-line no-warning-comments + // @ts-ignore + this.provideSync = syncProvider ? this.provideSync.bind(this) : null; + } + + /** + * @param {PathLike | PathOrFileDescriptor} path path + * @param {EXPECTED_ANY} options options + * @param {FileSystemCallback} callback callback + * @returns {void} + */ + provide(path, options, callback) { + if (typeof options === "function") { + callback = options; + options = undefined; + } + if ( + typeof path !== "string" && + !Buffer.isBuffer(path) && + !(path instanceof URL) && + typeof path !== "number" + ) { + callback(new TypeError("path must be a string, Buffer, URL or number")); + return; + } + const strPath = typeof path !== "string" ? path.toString() : path; + if (options) { + return /** @type {EXPECTED_FUNCTION} */ (this._provider).call( + this._providerContext, + path, + options, + callback, + ); + } + + // When in sync mode we can move to async mode + if (this._mode === STORAGE_MODE_SYNC) { + this._enterAsyncMode(); + } + + // Check in cache + const cacheEntry = this._data.get(strPath); + if (cacheEntry !== undefined) { + if (cacheEntry.err) return nextTick(callback, cacheEntry.err); + return nextTick(callback, null, cacheEntry.result); + } + + // Check if there is already the same operation running + let callbacks = this._activeAsyncOperations.get(strPath); + if (callbacks !== undefined) { + callbacks.push(callback); + return; + } + this._activeAsyncOperations.set(strPath, (callbacks = [callback])); + + // Run the operation + /** @type {EXPECTED_FUNCTION} */ + (this._provider).call( + this._providerContext, + path, + /** + * @param {Error | null} err error + * @param {EXPECTED_ANY=} result result + */ + (err, result) => { + this._activeAsyncOperations.delete(strPath); + this._storeResult(strPath, err, result); + + // Enter async mode if not yet done + this._enterAsyncMode(); + + runCallbacks( + /** @type {FileSystemCallback[]} */ (callbacks), + err, + result, + ); + }, + ); + } + + /** + * @param {PathLike | PathOrFileDescriptor} path path + * @param {EXPECTED_ANY} options options + * @returns {EXPECTED_ANY} result + */ + provideSync(path, options) { + if ( + typeof path !== "string" && + !Buffer.isBuffer(path) && + !(path instanceof URL) && + typeof path !== "number" + ) { + throw new TypeError("path must be a string"); + } + const strPath = typeof path !== "string" ? path.toString() : path; + if (options) { + return /** @type {EXPECTED_FUNCTION} */ (this._syncProvider).call( + this._providerContext, + path, + options, + ); + } + + // In sync mode we may have to decay some cache items + if (this._mode === STORAGE_MODE_SYNC) { + this._runDecays(); + } + + // Check in cache + const cacheEntry = this._data.get(strPath); + if (cacheEntry !== undefined) { + if (cacheEntry.err) throw cacheEntry.err; + return cacheEntry.result; + } + + // Get all active async operations + // This sync operation will also complete them + const callbacks = this._activeAsyncOperations.get(strPath); + this._activeAsyncOperations.delete(strPath); + + // Run the operation + // When in idle mode, we will enter sync mode + let result; + try { + result = /** @type {EXPECTED_FUNCTION} */ (this._syncProvider).call( + this._providerContext, + path, + ); + } catch (err) { + this._storeResult(strPath, /** @type {Error} */ (err), undefined); + this._enterSyncModeWhenIdle(); + if (callbacks) { + runCallbacks(callbacks, /** @type {Error} */ (err), undefined); + } + throw err; + } + this._storeResult(strPath, null, result); + this._enterSyncModeWhenIdle(); + if (callbacks) { + runCallbacks(callbacks, null, result); + } + return result; + } + + /** + * @param {(string | Buffer | URL | number | (string | URL | Buffer | number)[] | Set)=} what what to purge + */ + purge(what) { + if (!what) { + if (this._mode !== STORAGE_MODE_IDLE) { + this._data.clear(); + for (const level of this._levels) { + level.clear(); + } + this._enterIdleMode(); + } + } else if ( + typeof what === "string" || + Buffer.isBuffer(what) || + what instanceof URL || + typeof what === "number" + ) { + const strWhat = typeof what !== "string" ? what.toString() : what; + for (const [key, data] of this._data) { + if (key.startsWith(strWhat)) { + this._data.delete(key); + data.level.delete(key); + } + } + if (this._data.size === 0) { + this._enterIdleMode(); + } + } else { + for (const [key, data] of this._data) { + for (const item of what) { + const strItem = typeof item !== "string" ? item.toString() : item; + if (key.startsWith(strItem)) { + this._data.delete(key); + data.level.delete(key); + break; + } + } + } + if (this._data.size === 0) { + this._enterIdleMode(); + } + } + } + + /** + * @param {(string | Buffer | URL | number | (string | URL | Buffer | number)[] | Set)=} what what to purge + */ + purgeParent(what) { + if (!what) { + this.purge(); + } else if ( + typeof what === "string" || + Buffer.isBuffer(what) || + what instanceof URL || + typeof what === "number" + ) { + const strWhat = typeof what !== "string" ? what.toString() : what; + this.purge(dirname(strWhat)); + } else { + const set = new Set(); + for (const item of what) { + const strItem = typeof item !== "string" ? item.toString() : item; + set.add(dirname(strItem)); + } + this.purge(set); + } + } + + /** + * @param {string} path path + * @param {Error | null} err error + * @param {EXPECTED_ANY} result result + */ + _storeResult(path, err, result) { + if (this._data.has(path)) return; + const level = this._levels[this._currentLevel]; + this._data.set(path, { err, result, level }); + level.add(path); + } + + _decayLevel() { + const nextLevel = (this._currentLevel + 1) % this._levels.length; + const decay = this._levels[nextLevel]; + this._currentLevel = nextLevel; + for (const item of decay) { + this._data.delete(item); + } + decay.clear(); + if (this._data.size === 0) { + this._enterIdleMode(); + } else { + /** @type {number} */ + (this._nextDecay) += this._tickInterval; + } + } + + _runDecays() { + while ( + /** @type {number} */ (this._nextDecay) <= Date.now() && + this._mode !== STORAGE_MODE_IDLE + ) { + this._decayLevel(); + } + } + + _enterAsyncMode() { + let timeout = 0; + switch (this._mode) { + case STORAGE_MODE_ASYNC: + return; + case STORAGE_MODE_IDLE: + this._nextDecay = Date.now() + this._tickInterval; + timeout = this._tickInterval; + break; + case STORAGE_MODE_SYNC: + this._runDecays(); + // _runDecays may change the mode + if ( + /** @type {STORAGE_MODE_IDLE | STORAGE_MODE_SYNC | STORAGE_MODE_ASYNC} */ + (this._mode) === STORAGE_MODE_IDLE + ) { + return; + } + timeout = Math.max( + 0, + /** @type {number} */ (this._nextDecay) - Date.now(), + ); + break; + } + this._mode = STORAGE_MODE_ASYNC; + // When duration is Infinity, cache entries never expire, so there + // is no need to schedule a decay timer. + if (this._duration === Infinity) { + return; + } + const ref = setTimeout(() => { + this._mode = STORAGE_MODE_SYNC; + this._runDecays(); + }, timeout); + if (ref.unref) ref.unref(); + this._timeout = ref; + } + + _enterSyncModeWhenIdle() { + if (this._mode === STORAGE_MODE_IDLE) { + this._mode = STORAGE_MODE_SYNC; + this._nextDecay = Date.now() + this._tickInterval; + } + } + + _enterIdleMode() { + this._mode = STORAGE_MODE_IDLE; + this._nextDecay = undefined; + if (this._timeout) clearTimeout(this._timeout); + } +} + +/** + * @template {EXPECTED_FUNCTION} Provider + * @template {EXPECTED_FUNCTION} AsyncProvider + * @template FileSystem + * @param {number} duration duration in ms files are cached + * @param {Provider | undefined} provider provider + * @param {AsyncProvider | undefined} syncProvider sync provider + * @param {BaseFileSystem} providerContext provider context + * @returns {OperationMergerBackend | CacheBackend} backend + */ +const createBackend = (duration, provider, syncProvider, providerContext) => { + if (duration > 0) { + return new CacheBackend(duration, provider, syncProvider, providerContext); + } + return new OperationMergerBackend(provider, syncProvider, providerContext); +}; + +module.exports = class CachedInputFileSystem { + /** + * @param {BaseFileSystem} fileSystem file system + * @param {number} duration duration in ms files are cached + */ + constructor(fileSystem, duration) { + this.fileSystem = fileSystem; + + this._lstatBackend = createBackend( + duration, + this.fileSystem.lstat, + this.fileSystem.lstatSync, + this.fileSystem, + ); + const lstat = this._lstatBackend.provide; + this.lstat = /** @type {FileSystem["lstat"]} */ (lstat); + const lstatSync = this._lstatBackend.provideSync; + this.lstatSync = /** @type {SyncFileSystem["lstatSync"]} */ (lstatSync); + + this._statBackend = createBackend( + duration, + this.fileSystem.stat, + this.fileSystem.statSync, + this.fileSystem, + ); + const stat = this._statBackend.provide; + this.stat = /** @type {FileSystem["stat"]} */ (stat); + const statSync = this._statBackend.provideSync; + this.statSync = /** @type {SyncFileSystem["statSync"]} */ (statSync); + + this._readdirBackend = createBackend( + duration, + this.fileSystem.readdir, + this.fileSystem.readdirSync, + this.fileSystem, + ); + const readdir = this._readdirBackend.provide; + this.readdir = /** @type {FileSystem["readdir"]} */ (readdir); + const readdirSync = this._readdirBackend.provideSync; + this.readdirSync = /** @type {SyncFileSystem["readdirSync"]} */ ( + readdirSync + ); + + this._readFileBackend = createBackend( + duration, + this.fileSystem.readFile, + this.fileSystem.readFileSync, + this.fileSystem, + ); + const readFile = this._readFileBackend.provide; + this.readFile = /** @type {FileSystem["readFile"]} */ (readFile); + const readFileSync = this._readFileBackend.provideSync; + this.readFileSync = /** @type {SyncFileSystem["readFileSync"]} */ ( + readFileSync + ); + + this._readJsonBackend = createBackend( + duration, + // prettier-ignore + this.fileSystem.readJson || + (this.readFile && + ( + /** + * @param {string} path path + * @param {FileSystemCallback} callback callback + */ + (path, callback) => { + this.readFile(path, (err, buffer) => { + if (err) return callback(err); + if (!buffer || buffer.length === 0) + {return callback(new Error("No file content"));} + let data; + try { + data = JSON.parse(buffer.toString("utf8")); + } catch (err_) { + return callback(/** @type {Error} */ (err_)); + } + callback(null, data); + }); + }) + ), + // prettier-ignore + this.fileSystem.readJsonSync || + (this.readFileSync && + ( + /** + * @param {string} path path + * @returns {EXPECTED_ANY} result + */ + (path) => { + const buffer = this.readFileSync(path); + const data = JSON.parse(buffer.toString("utf8")); + return data; + } + )), + this.fileSystem, + ); + const readJson = this._readJsonBackend.provide; + this.readJson = /** @type {FileSystem["readJson"]} */ (readJson); + const readJsonSync = this._readJsonBackend.provideSync; + this.readJsonSync = /** @type {SyncFileSystem["readJsonSync"]} */ ( + readJsonSync + ); + + this._readlinkBackend = createBackend( + duration, + this.fileSystem.readlink, + this.fileSystem.readlinkSync, + this.fileSystem, + ); + const readlink = this._readlinkBackend.provide; + this.readlink = /** @type {FileSystem["readlink"]} */ (readlink); + const readlinkSync = this._readlinkBackend.provideSync; + this.readlinkSync = /** @type {SyncFileSystem["readlinkSync"]} */ ( + readlinkSync + ); + + this._realpathBackend = createBackend( + duration, + this.fileSystem.realpath, + this.fileSystem.realpathSync, + this.fileSystem, + ); + const realpath = this._realpathBackend.provide; + this.realpath = /** @type {FileSystem["realpath"]} */ (realpath); + const realpathSync = this._realpathBackend.provideSync; + this.realpathSync = /** @type {SyncFileSystem["realpathSync"]} */ ( + realpathSync + ); + } + + /** + * @param {(string | Buffer | URL | number | (string | URL | Buffer | number)[] | Set)=} what what to purge + */ + purge(what) { + this._statBackend.purge(what); + this._lstatBackend.purge(what); + this._readdirBackend.purgeParent(what); + this._readFileBackend.purge(what); + this._readlinkBackend.purge(what); + this._readJsonBackend.purge(what); + this._realpathBackend.purge(what); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/CloneBasenamePlugin.js b/client/node_modules/enhanced-resolve/lib/CloneBasenamePlugin.js new file mode 100644 index 0000000..f608036 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/CloneBasenamePlugin.js @@ -0,0 +1,51 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class CloneBasenamePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("CloneBasenamePlugin", (request, resolveContext, callback) => { + const requestPath = /** @type {string} */ (request.path); + const filename = resolver.basename(requestPath); + const filePath = resolver.join(requestPath, filename); + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: filePath, + relativePath: + request.relativePath && + resolver.join(request.relativePath, filename), + }; + resolver.doResolve( + target, + obj, + `using path: ${filePath}`, + resolveContext, + callback, + ); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/ConditionalPlugin.js b/client/node_modules/enhanced-resolve/lib/ConditionalPlugin.js new file mode 100644 index 0000000..99cc09d --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/ConditionalPlugin.js @@ -0,0 +1,59 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class ConditionalPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Partial} test compare object + * @param {string | null} message log message + * @param {boolean} allowAlternatives when false, do not continue with the current step when "test" matches + * @param {string | ResolveStepHook} target target + */ + constructor(source, test, message, allowAlternatives, target) { + this.source = source; + this.test = test; + this.message = message; + this.allowAlternatives = allowAlternatives; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const { test, message, allowAlternatives } = this; + const keys = /** @type {(keyof ResolveRequest)[]} */ (Object.keys(test)); + resolver + .getHook(this.source) + .tapAsync("ConditionalPlugin", (request, resolveContext, callback) => { + for (const prop of keys) { + if (request[prop] !== test[prop]) return callback(); + } + resolver.doResolve( + target, + request, + message, + resolveContext, + allowAlternatives + ? callback + : (err, result) => { + if (err) return callback(err); + + // Don't allow other alternatives + if (result === undefined) return callback(null, null); + callback(null, result); + }, + ); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js b/client/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js new file mode 100644 index 0000000..91a7f3b --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js @@ -0,0 +1,103 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const DescriptionFileUtils = require("./DescriptionFileUtils"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +const BACKSLASH_G = /\\/g; + +module.exports = class DescriptionFilePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string[]} filenames filenames + * @param {boolean} pathIsFile pathIsFile + * @param {string | ResolveStepHook} target target + */ + constructor(source, filenames, pathIsFile, target) { + this.source = source; + this.filenames = filenames; + this.pathIsFile = pathIsFile; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "DescriptionFilePlugin", + (request, resolveContext, callback) => { + const { path } = request; + if (!path) return callback(); + const directory = this.pathIsFile + ? DescriptionFileUtils.cdUp(path) + : path; + if (!directory) return callback(); + DescriptionFileUtils.loadDescriptionFile( + resolver, + directory, + this.filenames, + request.descriptionFilePath + ? { + path: request.descriptionFilePath, + content: request.descriptionFileData, + directory: + /** @type {string} */ + (request.descriptionFileRoot), + } + : undefined, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (!result) { + if (resolveContext.log) { + resolveContext.log( + `No description file found in ${directory} or above`, + ); + } + return callback(); + } + const rawRelative = path.slice(result.directory.length); + const relativePath = `.${ + rawRelative.includes("\\") + ? rawRelative.replace(BACKSLASH_G, "/") + : rawRelative + }`; + /** @type {ResolveRequest} */ + const obj = { + ...request, + descriptionFilePath: result.path, + descriptionFileData: result.content, + descriptionFileRoot: result.directory, + relativePath, + }; + resolver.doResolve( + target, + obj, + `using description file: ${result.path} (relative path: ${relativePath})`, + resolveContext, + (err, result) => { + if (err) return callback(err); + + // Don't allow other processing + if (result === undefined) return callback(null, null); + callback(null, result); + }, + ); + }, + ); + }, + ); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/DescriptionFileUtils.js b/client/node_modules/enhanced-resolve/lib/DescriptionFileUtils.js new file mode 100644 index 0000000..ecc9055 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/DescriptionFileUtils.js @@ -0,0 +1,231 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const forEachBail = require("./forEachBail"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonObject} JsonObject */ +/** @typedef {import("./Resolver").JsonValue} JsonValue */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ + +/** + * @typedef {object} DescriptionFileInfo + * @property {JsonObject=} content content + * @property {string} path path + * @property {string} directory directory + */ + +/** + * @callback ErrorFirstCallback + * @param {Error | null=} error + * @param {DescriptionFileInfo=} result + */ + +/** + * @typedef {object} Result + * @property {string} path path to description file + * @property {string} directory directory of description file + * @property {JsonObject} content content of description file + */ + +const CHAR_SLASH = 47; +const CHAR_BACKSLASH = 92; + +/** + * Walk up one directory. Called once per package-root candidate and once per + * `described-resolve` (to find the enclosing description file), so it's on + * the resolver's hot path. + * + * Previous implementation called `lastIndexOf("/")` and `lastIndexOf("\\")` + * separately and then picked the larger. For any non-trivial directory + * string on POSIX, `lastIndexOf("\\")` scans the full string just to return + * -1. A single reverse char-code scan does the same work in one pass. + * + * Any single-character directory is treated as a root — `directory.length + * <= 1` collapses the `"/"`, `"\\"` and `""` branches into one compare. + * Without the `"\\"` case, `cdUp("\\")` (reached from a UNC root or a DOS + * device path like `\\?\…`) would return itself via `slice(0, i || 1)` + * and trap `loadDescriptionFile` in an infinite loop. Once single-char + * roots are filtered up front, the reverse scan always produces a + * strictly shorter string. + * @param {string} directory directory + * @returns {string | null} parent directory or null + */ +function cdUp(directory) { + if (directory.length <= 1) return null; + for (let i = directory.length - 1; i >= 0; i--) { + const code = directory.charCodeAt(i); + if (code === CHAR_SLASH || code === CHAR_BACKSLASH) { + return directory.slice(0, i || 1); + } + } + return null; +} + +/** + * @param {Resolver} resolver resolver + * @param {string} directory directory + * @param {string[]} filenames filenames + * @param {DescriptionFileInfo | undefined} oldInfo oldInfo + * @param {ResolveContext} resolveContext resolveContext + * @param {ErrorFirstCallback} callback callback + */ +function loadDescriptionFile( + resolver, + directory, + filenames, + oldInfo, + resolveContext, + callback, +) { + // Hoist the per-filename iterator and the per-level done callback out + // of `findDescriptionFile`. They both close over `directory`, which we + // reassign as we walk up the tree, so the same closures keep working + // across every level — the previous implementation re-allocated both + // arrows on every recursion step, which adds up on deep walks (multiple + // `DescriptionFilePlugin` taps per resolve, each climbing several + // directories looking for `package.json`). + /** + * @param {string} filename filename + * @param {(err?: null | Error, result?: null | Result) => void} iterCallback callback + * @returns {void} + */ + const iterFilename = (filename, iterCallback) => { + const descriptionFilePath = resolver.join(directory, filename); + + /** + * @param {(null | Error)=} err error + * @param {JsonObject=} resolvedContent content + * @returns {void} + */ + function onJson(err, resolvedContent) { + if (err) { + if (resolveContext.log) { + resolveContext.log( + `${descriptionFilePath} (directory description file): ${err}`, + ); + } else { + err.message = `${descriptionFilePath} (directory description file): ${err}`; + } + return iterCallback(err); + } + iterCallback(null, { + content: /** @type {JsonObject} */ (resolvedContent), + directory, + path: descriptionFilePath, + }); + } + + if (resolver.fileSystem.readJson) { + resolver.fileSystem.readJson(descriptionFilePath, (err, content) => { + if (err) { + if ( + typeof (/** @type {NodeJS.ErrnoException} */ (err).code) !== + "undefined" + ) { + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(descriptionFilePath); + } + return iterCallback(); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(descriptionFilePath); + } + return onJson(err); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(descriptionFilePath); + } + onJson(null, content); + }); + } else { + resolver.fileSystem.readFile(descriptionFilePath, (err, content) => { + if (err) { + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(descriptionFilePath); + } + return iterCallback(); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(descriptionFilePath); + } + + /** @type {JsonObject | undefined} */ + let json; + + if (content) { + try { + json = JSON.parse(content.toString()); + } catch (/** @type {unknown} */ err_) { + return onJson(/** @type {Error} */ (err_)); + } + } else { + return onJson(new Error("No content in file")); + } + + onJson(null, json); + }); + } + }; + // Forward-declared so the helpers below can reference each other + // without falling foul of `no-use-before-define`. + /** @type {() => void} */ + let findDescriptionFile; + /** + * @param {(null | Error)=} err error + * @param {(null | Result)=} result result + * @returns {void} + */ + const onLevelDone = (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + const dir = cdUp(directory); + if (!dir) { + return callback(); + } + directory = dir; + return findDescriptionFile(); + }; + findDescriptionFile = () => { + if (oldInfo && oldInfo.directory === directory) { + // We already have info for this directory and can reuse it + return callback(null, oldInfo); + } + forEachBail(filenames, iterFilename, onLevelDone); + }; + findDescriptionFile(); +} + +/** + * @param {JsonObject} content content + * @param {string | string[]} field field + * @returns {JsonValue | undefined} field data + */ +function getField(content, field) { + if (!content) return undefined; + if (Array.isArray(field)) { + /** @type {JsonValue} */ + let current = content; + for (let j = 0; j < field.length; j++) { + if (current === null || typeof current !== "object") { + current = null; + break; + } + current = /** @type {JsonValue} */ ( + /** @type {JsonObject} */ + (current)[field[j]] + ); + } + return current; + } + return content[field]; +} + +module.exports.cdUp = cdUp; +module.exports.getField = getField; +module.exports.loadDescriptionFile = loadDescriptionFile; diff --git a/client/node_modules/enhanced-resolve/lib/DirectoryExistsPlugin.js b/client/node_modules/enhanced-resolve/lib/DirectoryExistsPlugin.js new file mode 100644 index 0000000..04069e4 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/DirectoryExistsPlugin.js @@ -0,0 +1,68 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class DirectoryExistsPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "DirectoryExistsPlugin", + (request, resolveContext, callback) => { + const fs = resolver.fileSystem; + const directory = request.path; + if (!directory) return callback(); + fs.stat(directory, (err, stat) => { + // Combine the two miss branches: a stat failure and a + // "not a directory" result share the same handling — record + // the path on `missingDependencies`, log the right reason, + // then bail. The error-message ternary picks the wording + // that matched the failing condition. + if (err || !stat || !stat.isDirectory()) { + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(directory); + } + if (resolveContext.log) { + resolveContext.log( + err || !stat + ? `${directory} doesn't exist` + : `${directory} is not a directory`, + ); + } + return callback(); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(directory); + } + resolver.doResolve( + target, + request, + `existing directory ${directory}`, + resolveContext, + callback, + ); + }); + }, + ); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/ExportsFieldPlugin.js b/client/node_modules/enhanced-resolve/lib/ExportsFieldPlugin.js new file mode 100644 index 0000000..8a5ce43 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/ExportsFieldPlugin.js @@ -0,0 +1,232 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const DescriptionFileUtils = require("./DescriptionFileUtils"); +const forEachBail = require("./forEachBail"); +const { processExportsField } = require("./util/entrypoints"); +const { parseIdentifier } = require("./util/identifier"); +const { + deprecatedInvalidSegmentRegEx, + invalidSegmentRegEx, +} = require("./util/path"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonObject} JsonObject */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./util/entrypoints").ExportsField} ExportsField */ +/** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */ + +module.exports = class ExportsFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Set} conditionNames condition names + * @param {string | string[]} fieldNamePath name path + * @param {string | ResolveStepHook} target target + */ + constructor(source, conditionNames, fieldNamePath, target) { + this.source = source; + this.target = target; + this.conditionNames = conditionNames; + this.fieldName = fieldNamePath; + // `null` is cached for description files that have no exports field, + // so subsequent resolves against the same package.json skip the + // `DescriptionFileUtils.getField` walk entirely. + /** @type {WeakMap} */ + this._fieldProcessorCache = new WeakMap(); + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ExportsFieldPlugin", (request, resolveContext, callback) => { + // When there is no description file, abort + if (!request.descriptionFileData) return callback(); + if ( + // When the description file is inherited from parent, abort + // (There is no description file inside of this package) + request.relativePath !== "." || + request.request === undefined + ) { + return callback(); + } + + const { descriptionFileData } = request; + const remainingRequest = + request.query || request.fragment + ? (request.request === "." ? "./" : request.request) + + request.query + + request.fragment + : request.request; + + /** @type {string[]} */ + let paths; + /** @type {string | null} */ + let usedField; + + try { + // Look up the cached processor first. On a cache hit we + // avoid re-walking the description file for the exports + // field — and `null` is cached for description files that + // have no exports field at all, so those skip the read + // entirely. `processExportsField` can throw on a malformed + // `exports` map (e.g. a key without a leading `.`), so + // building the processor must stay inside this try/catch. + let fieldProcessor = + this._fieldProcessorCache.get(descriptionFileData); + if ( + fieldProcessor === undefined && + !this._fieldProcessorCache.has(descriptionFileData) + ) { + const exportsField = + /** @type {ExportsField | null | undefined} */ + ( + DescriptionFileUtils.getField( + descriptionFileData, + this.fieldName, + ) + ); + fieldProcessor = exportsField + ? processExportsField(exportsField) + : null; + this._fieldProcessorCache.set(descriptionFileData, fieldProcessor); + } + if (!fieldProcessor) return callback(); + + if (request.directory) { + return callback( + new Error( + `Resolving to directories is not possible with the exports field (request was ${remainingRequest}/)`, + ), + ); + } + + [paths, usedField] = fieldProcessor( + remainingRequest, + this.conditionNames, + ); + } catch (/** @type {unknown} */ err) { + if (resolveContext.log) { + resolveContext.log( + `Exports field in ${request.descriptionFilePath} can't be processed: ${err}`, + ); + } + return callback(/** @type {Error} */ (err)); + } + + if (paths.length === 0) { + const conditions = [...this.conditionNames]; + const conditionsStr = + conditions.length === 1 + ? `the condition "${conditions[0]}"` + : `the conditions ${JSON.stringify(conditions)}`; + return callback( + new Error( + `"${remainingRequest}" is not exported under ${conditionsStr} from package ${request.descriptionFileRoot} (see exports field in ${request.descriptionFilePath})`, + ), + ); + } + + forEachBail( + paths, + /** + * @param {string} path path + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @param {number} i index + * @returns {void} + */ + (path, callback, i) => { + const parsedIdentifier = parseIdentifier(path); + + if (!parsedIdentifier) return callback(); + + const [relativePath, query, fragment] = parsedIdentifier; + + if (!relativePath.startsWith("./")) { + if (paths.length === i) { + return callback( + new Error( + `Invalid "exports" target "${path}" defined for "${usedField}" in the package config ${request.descriptionFilePath}, targets must start with "./"`, + ), + ); + } + + return callback(); + } + + const withoutDotSlash = relativePath.slice(2); + if ( + invalidSegmentRegEx.test(withoutDotSlash) && + deprecatedInvalidSegmentRegEx.test(withoutDotSlash) + ) { + if (paths.length === i) { + return callback( + new Error( + `Invalid "exports" target "${path}" defined for "${usedField}" in the package config ${request.descriptionFilePath}, targets must start with "./"`, + ), + ); + } + + return callback(); + } + + /** @type {ResolveRequest} */ + const obj = { + ...request, + request: undefined, + path: resolver.join( + /** @type {string} */ (request.descriptionFileRoot), + relativePath, + ), + relativePath, + query, + fragment, + }; + + resolver.doResolve( + target, + obj, + `using exports field: ${path}`, + resolveContext, + (err, result) => { + if (err) return callback(err); + // Don't allow to continue - https://github.com/webpack/enhanced-resolve/issues/400 + if (result === undefined) return callback(null, null); + callback(null, result); + }, + ); + }, + /** + * @param {(null | Error)=} err error + * @param {(null | ResolveRequest)=} result result + * @returns {void} + */ + (err, result) => { + if (err) return callback(err); + // When an exports field match was found but the target file doesn't exist, + // return an error to prevent fallback to parent node_modules directories. + // Per the Node.js ESM spec, a matched exports entry that fails to resolve + // is a hard error, not a signal to continue searching up the directory tree. + // See: https://github.com/webpack/enhanced-resolve/issues/399 + if (!result) { + return callback( + new Error( + `Package path ${remainingRequest} is exported from package ${request.descriptionFileRoot}, but no valid target file was found (see exports field in ${request.descriptionFilePath})`, + ), + ); + } + callback(null, result); + }, + ); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/ExtensionAliasPlugin.js b/client/node_modules/enhanced-resolve/lib/ExtensionAliasPlugin.js new file mode 100644 index 0000000..c153632 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/ExtensionAliasPlugin.js @@ -0,0 +1,129 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const forEachBail = require("./forEachBail"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {{ alias: string | string[], extension: string }} ExtensionAliasOption */ + +module.exports = class ExtensionAliasPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {ExtensionAliasOption} options options + * @param {string | ResolveStepHook} target target + */ + constructor(source, options, target) { + this.source = source; + this.options = options; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const { extension, alias } = this.options; + resolver + .getHook(this.source) + .tapAsync("ExtensionAliasPlugin", (request, resolveContext, callback) => { + // Two modes of operation: + // - "request" mode: original request specifier still carries the + // extension (e.g. user wrote `./foo.js`). We swap the extension + // on `request.request` and re-resolve. + // - "path" mode: the specifier has already been joined into an + // absolute `request.path` (e.g. produced by the imports field). + // We swap the extension on `request.path` and `request.relativePath`. + const useRequest = request.request !== undefined; + const source = useRequest + ? /** @type {string} */ (request.request) + : request.path; + if (!source || !source.endsWith(extension)) return callback(); + const isAliasString = typeof alias === "string"; + // Hoist the base (everything before the old extension) out of the + // per-alias `resolve` callback. For an array `alias`, the callback + // runs once per candidate extension; the base does not change + // between iterations, so there's no reason to recompute it. + const sourceBase = source.slice(0, -extension.length); + const relativePathBase = + !useRequest && + request.relativePath && + request.relativePath.endsWith(extension) + ? request.relativePath.slice(0, -extension.length) + : null; + /** + * @param {string} alias extension alias + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @param {number=} index index + * @returns {void} + */ + const resolve = (alias, callback, index) => { + const newValue = `${sourceBase}${alias}`; + const nextRequest = useRequest + ? { + ...request, + request: newValue, + fullySpecified: true, + } + : { + ...request, + path: newValue, + relativePath: + relativePathBase !== null + ? `${relativePathBase}${alias}` + : request.relativePath, + fullySpecified: true, + }; + + return resolver.doResolve( + target, + nextRequest, + `aliased from extension alias with mapping '${extension}' to '${alias}'`, + resolveContext, + (err, result) => { + // Throw error if we are on the last alias (for multiple aliases) and it failed, always throw if we are not an array or we have only one alias + if (!isAliasString && index) { + if (index !== this.options.alias.length) { + if (resolveContext.log) { + resolveContext.log( + `Failed to alias from extension alias with mapping '${extension}' to '${alias}' for '${newValue}': ${err}`, + ); + } + + return callback(null, result); + } + + return callback(err, result); + } + callback(err, result); + }, + ); + }; + /** + * @param {(null | Error)=} err error + * @param {(null | ResolveRequest)=} result result + * @returns {void} + */ + const stoppingCallback = (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + // Don't allow other aliasing or raw request + return callback(null, null); + }; + if (isAliasString) { + resolve(alias, stoppingCallback); + } else if (alias.length > 1) { + forEachBail(alias, resolve, stoppingCallback); + } else { + resolve(alias[0], stoppingCallback); + } + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/FileExistsPlugin.js b/client/node_modules/enhanced-resolve/lib/FileExistsPlugin.js new file mode 100644 index 0000000..c6343c8 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/FileExistsPlugin.js @@ -0,0 +1,65 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class FileExistsPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const fs = resolver.fileSystem; + resolver + .getHook(this.source) + .tapAsync("FileExistsPlugin", (request, resolveContext, callback) => { + const file = request.path; + if (!file) return callback(); + fs.stat(file, (err, stat) => { + // Combine the two miss branches: a stat failure and a + // "not a file" result share the same handling — record the + // path on `missingDependencies`, log the right reason, then + // bail. The error-message ternary picks the wording that + // matched the failing condition. + if (err || !stat || !stat.isFile()) { + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(file); + } + if (resolveContext.log) { + resolveContext.log( + err || !stat + ? `${file} doesn't exist` + : `${file} is not a file`, + ); + } + return callback(); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(file); + } + resolver.doResolve( + target, + request, + `existing file: ${file}`, + resolveContext, + callback, + ); + }); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/ImportsFieldPlugin.js b/client/node_modules/enhanced-resolve/lib/ImportsFieldPlugin.js new file mode 100644 index 0000000..c3e57c5 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/ImportsFieldPlugin.js @@ -0,0 +1,233 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const DescriptionFileUtils = require("./DescriptionFileUtils"); +const forEachBail = require("./forEachBail"); +const { processImportsField } = require("./util/entrypoints"); +const { parseIdentifier } = require("./util/identifier"); +const { invalidSegmentRegEx } = require("./util/path"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonObject} JsonObject */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */ +/** @typedef {import("./util/entrypoints").ImportsField} ImportsField */ + +const dotCode = ".".charCodeAt(0); + +module.exports = class ImportsFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Set} conditionNames condition names + * @param {string | string[]} fieldNamePath name path + * @param {string | ResolveStepHook} targetFile target file + * @param {string | ResolveStepHook} targetPackage target package + */ + constructor( + source, + conditionNames, + fieldNamePath, + targetFile, + targetPackage, + ) { + this.source = source; + this.targetFile = targetFile; + this.targetPackage = targetPackage; + this.conditionNames = conditionNames; + this.fieldName = fieldNamePath; + // `null` is cached for description files that have no imports field, + // so subsequent resolves against the same package.json skip the + // `DescriptionFileUtils.getField` walk entirely. + /** @type {WeakMap} */ + this._fieldProcessorCache = new WeakMap(); + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const targetFile = resolver.ensureHook(this.targetFile); + const targetPackage = resolver.ensureHook(this.targetPackage); + + resolver + .getHook(this.source) + .tapAsync("ImportsFieldPlugin", (request, resolveContext, callback) => { + // When there is no description file, abort + if (!request.descriptionFileData || request.request === undefined) { + return callback(); + } + + const { descriptionFileData } = request; + // Skip the concat when there's nothing to append — the common + // case has empty query/fragment, so this avoids an allocation + // per resolve. Mirrors the pattern in ExportsFieldPlugin. + const remainingRequest = + request.query || request.fragment + ? request.request + request.query + request.fragment + : request.request; + + /** @type {string[]} */ + let paths; + /** @type {string | null} */ + let usedField; + + try { + // Look up the cached processor first. On a cache hit we + // avoid re-walking the description file for the imports + // field — and `null` is cached for description files that + // have no imports field at all, so those skip the read + // entirely. `processImportsField` can throw on a + // malformed `imports` map, so building the processor must + // stay inside this try/catch. + let fieldProcessor = + this._fieldProcessorCache.get(descriptionFileData); + if ( + fieldProcessor === undefined && + !this._fieldProcessorCache.has(descriptionFileData) + ) { + const importsField = + /** @type {ImportsField | null | undefined} */ + ( + DescriptionFileUtils.getField( + descriptionFileData, + this.fieldName, + ) + ); + fieldProcessor = importsField + ? processImportsField(importsField) + : null; + this._fieldProcessorCache.set(descriptionFileData, fieldProcessor); + } + if (!fieldProcessor) return callback(); + + if (request.directory) { + return callback( + new Error( + `Resolving to directories is not possible with the imports field (request was ${remainingRequest}/)`, + ), + ); + } + + [paths, usedField] = fieldProcessor( + remainingRequest, + this.conditionNames, + ); + } catch (/** @type {unknown} */ err) { + if (resolveContext.log) { + resolveContext.log( + `Imports field in ${request.descriptionFilePath} can't be processed: ${err}`, + ); + } + return callback(/** @type {Error} */ (err)); + } + + if (paths.length === 0) { + return callback( + new Error( + `Package import ${remainingRequest} is not imported from package ${request.descriptionFileRoot} (see imports field in ${request.descriptionFilePath})`, + ), + ); + } + + forEachBail( + paths, + /** + * @param {string} path path + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @param {number} i index + * @returns {void} + */ + (path, callback, i) => { + const parsedIdentifier = parseIdentifier(path); + + if (!parsedIdentifier) return callback(); + + const [path_, query, fragment] = parsedIdentifier; + + switch (path_.charCodeAt(0)) { + // should be relative + case dotCode: { + const withoutDotSlash = path_.slice(2); + if (invalidSegmentRegEx.test(withoutDotSlash)) { + if (paths.length === i) { + return callback( + new Error( + `Invalid "imports" target "${path}" defined for "${usedField}" in the package config ${request.descriptionFilePath}, targets must start with "./"`, + ), + ); + } + + return callback(); + } + + /** @type {ResolveRequest} */ + const obj = { + ...request, + request: undefined, + path: resolver.join( + /** @type {string} */ (request.descriptionFileRoot), + path_, + ), + relativePath: path_, + query, + fragment, + }; + + resolver.doResolve( + targetFile, + obj, + `using imports field: ${path}`, + resolveContext, + (err, result) => { + if (err) return callback(err); + // Don't allow to continue - https://github.com/webpack/enhanced-resolve/issues/400 + if (result === undefined) return callback(null, null); + callback(null, result); + }, + ); + break; + } + + // package resolving + default: { + /** @type {ResolveRequest} */ + const obj = { + ...request, + request: path_, + relativePath: path_, + fullySpecified: true, + query, + fragment, + }; + + resolver.doResolve( + targetPackage, + obj, + `using imports field: ${path}`, + resolveContext, + (err, result) => { + if (err) return callback(err); + // Don't allow to continue - https://github.com/webpack/enhanced-resolve/issues/400 + if (result === undefined) return callback(null, null); + callback(null, result); + }, + ); + } + } + }, + /** + * @param {null | Error=} err error + * @param {null | ResolveRequest=} result result + * @returns {void} + */ + (err, result) => callback(err, result || null), + ); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/JoinRequestPartPlugin.js b/client/node_modules/enhanced-resolve/lib/JoinRequestPartPlugin.js new file mode 100644 index 0000000..a171b98 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/JoinRequestPartPlugin.js @@ -0,0 +1,75 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +const namespaceStartCharCode = "@".charCodeAt(0); + +module.exports = class JoinRequestPartPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "JoinRequestPartPlugin", + (request, resolveContext, callback) => { + const req = request.request || ""; + let i = req.indexOf("/", 3); + + if (i >= 0 && req.charCodeAt(2) === namespaceStartCharCode) { + i = req.indexOf("/", i + 1); + } + + /** @type {string} */ + let moduleName; + /** @type {string} */ + let remainingRequest; + /** @type {boolean} */ + let fullySpecified; + if (i < 0) { + moduleName = req; + remainingRequest = "."; + fullySpecified = false; + } else { + moduleName = req.slice(0, i); + remainingRequest = `.${req.slice(i)}`; + fullySpecified = /** @type {boolean} */ (request.fullySpecified); + } + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: resolver.join( + /** @type {string} */ + (request.path), + moduleName, + ), + relativePath: + request.relativePath && + resolver.join(request.relativePath, moduleName), + request: remainingRequest, + fullySpecified, + }; + resolver.doResolve(target, obj, null, resolveContext, callback); + }, + ); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/JoinRequestPlugin.js b/client/node_modules/enhanced-resolve/lib/JoinRequestPlugin.js new file mode 100644 index 0000000..108958e --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/JoinRequestPlugin.js @@ -0,0 +1,45 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class JoinRequestPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("JoinRequestPlugin", (request, resolveContext, callback) => { + const requestPath = /** @type {string} */ (request.path); + const requestRequest = /** @type {string} */ (request.request); + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: resolver.join(requestPath, requestRequest), + relativePath: + request.relativePath && + resolver.join(request.relativePath, requestRequest), + request: undefined, + }; + resolver.doResolve(target, obj, null, resolveContext, callback); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/LogInfoPlugin.js b/client/node_modules/enhanced-resolve/lib/LogInfoPlugin.js new file mode 100644 index 0000000..5dbb688 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/LogInfoPlugin.js @@ -0,0 +1,58 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class LogInfoPlugin { + /** + * @param {string | ResolveStepHook} source source + */ + constructor(source) { + this.source = source; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const { source } = this; + resolver + .getHook(this.source) + .tapAsync("LogInfoPlugin", (request, resolveContext, callback) => { + if (!resolveContext.log) return callback(); + const { log } = resolveContext; + const prefix = `[${source}] `; + if (request.path) { + log(`${prefix}Resolving in directory: ${request.path}`); + } + if (request.request) { + log(`${prefix}Resolving request: ${request.request}`); + } + if (request.module) log(`${prefix}Request is an module request.`); + if (request.directory) log(`${prefix}Request is a directory request.`); + if (request.query) { + log(`${prefix}Resolving request query: ${request.query}`); + } + if (request.fragment) { + log(`${prefix}Resolving request fragment: ${request.fragment}`); + } + if (request.descriptionFilePath) { + log( + `${prefix}Has description data from ${request.descriptionFilePath}`, + ); + } + if (request.relativePath) { + log( + `${prefix}Relative path from description file is: ${request.relativePath}`, + ); + } + callback(); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/MainFieldPlugin.js b/client/node_modules/enhanced-resolve/lib/MainFieldPlugin.js new file mode 100644 index 0000000..7616b9e --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/MainFieldPlugin.js @@ -0,0 +1,97 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const DescriptionFileUtils = require("./DescriptionFileUtils"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonObject} JsonObject */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +/** @typedef {{ name: string | string[], forceRelative: boolean }} MainFieldOptions */ + +const alreadyTriedMainField = Symbol("alreadyTriedMainField"); + +// Sentinel cached for description files where the main field resolves to a +// value we cannot use (missing, non-string, ".", "./"). Cheaper to store and +// check than to re-walk the description file on every resolve. +const NO_MAIN = Symbol("NoMain"); + +module.exports = class MainFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {MainFieldOptions} options options + * @param {string | ResolveStepHook} target target + */ + constructor(source, options, target) { + this.source = source; + this.options = options; + this.target = target; + // Cache the resolved `mainModule` per description-file content. The + // options (`name`, `forceRelative`) are fixed for this plugin + // instance, so caching against content alone is safe. Stores either + // the ready-to-use request string or the `NO_MAIN` sentinel. + /** @type {WeakMap} */ + this._mainModuleCache = new WeakMap(); + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("MainFieldPlugin", (request, resolveContext, callback) => { + if ( + request.path !== request.descriptionFileRoot || + /** @type {ResolveRequest & { [alreadyTriedMainField]?: string }} */ + (request)[alreadyTriedMainField] === request.descriptionFilePath || + !request.descriptionFilePath + ) { + return callback(); + } + const descFileData = /** @type {JsonObject} */ ( + request.descriptionFileData + ); + let mainModule = this._mainModuleCache.get(descFileData); + if (mainModule === undefined) { + let raw = + /** @type {string | null | undefined} */ + (DescriptionFileUtils.getField(descFileData, this.options.name)); + if (!raw || typeof raw !== "string" || raw === "." || raw === "./") { + this._mainModuleCache.set(descFileData, NO_MAIN); + return callback(); + } + if (this.options.forceRelative && !/^\.\.?\//.test(raw)) { + raw = `./${raw}`; + } + mainModule = raw; + this._mainModuleCache.set(descFileData, mainModule); + } else if (mainModule === NO_MAIN) { + return callback(); + } + const filename = resolver.basename(request.descriptionFilePath); + /** @type {ResolveRequest & { [alreadyTriedMainField]?: string }} */ + const obj = { + ...request, + request: mainModule, + module: false, + directory: mainModule.endsWith("/"), + [alreadyTriedMainField]: request.descriptionFilePath, + }; + return resolver.doResolve( + target, + obj, + `use ${mainModule} from ${this.options.name} in ${filename}`, + resolveContext, + callback, + ); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/ModulesInHierachicDirectoriesPlugin.js b/client/node_modules/enhanced-resolve/lib/ModulesInHierachicDirectoriesPlugin.js new file mode 100644 index 0000000..06065e8 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/ModulesInHierachicDirectoriesPlugin.js @@ -0,0 +1,9 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +// TODO remove in next major +module.exports = require("./ModulesInHierarchicalDirectoriesPlugin"); diff --git a/client/node_modules/enhanced-resolve/lib/ModulesInHierarchicalDirectoriesPlugin.js b/client/node_modules/enhanced-resolve/lib/ModulesInHierarchicalDirectoriesPlugin.js new file mode 100644 index 0000000..4f19fc3 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/ModulesInHierarchicalDirectoriesPlugin.js @@ -0,0 +1,47 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { modulesResolveHandler } = require("./ModulesUtils"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class ModulesInHierarchicalDirectoriesPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | string[]} directories directories + * @param {string | ResolveStepHook} target target + */ + constructor(source, directories, target) { + this.source = source; + this.directories = /** @type {string[]} */ [...directories]; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "ModulesInHierarchicalDirectoriesPlugin", + (request, resolveContext, callback) => { + modulesResolveHandler( + resolver, + this.directories, + target, + request, + resolveContext, + callback, + ); + }, + ); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/ModulesInRootPlugin.js b/client/node_modules/enhanced-resolve/lib/ModulesInRootPlugin.js new file mode 100644 index 0000000..7797a11 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/ModulesInRootPlugin.js @@ -0,0 +1,49 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class ModulesInRootPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} path path + * @param {string | ResolveStepHook} target target + */ + constructor(source, path, target) { + this.source = source; + this.path = path; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ModulesInRootPlugin", (request, resolveContext, callback) => { + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: this.path, + request: `./${request.request}`, + module: false, + }; + resolver.doResolve( + target, + obj, + `looking for modules in ${this.path}`, + resolveContext, + callback, + ); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/ModulesUtils.js b/client/node_modules/enhanced-resolve/lib/ModulesUtils.js new file mode 100644 index 0000000..3de32da --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/ModulesUtils.js @@ -0,0 +1,132 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const forEachBail = require("./forEachBail"); +const { getPathsCached } = require("./getPaths"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {(err?: null | Error, result?: null | ResolveRequest) => void} InnerCallback */ + +/** + * Per-(directories-array) cache of the flat `addrs` list produced for a given + * `request.path`. For a fixed directories configuration the fan-out of + * `ancestor × directory` is deterministic per request.path, and many resolves + * share the same starting directory (sibling files in one project, loops over + * a batch of imports, etc.) — caching avoids the `getPaths` regex split plus + * `len(paths) × len(directories)` join calls per resolve. + * + * The outer map is keyed on the directories array reference (plugin-owned, + * stable for the lifetime of the resolver), and the inner map on the + * starting `request.path`. Kept private to this module (rather than hung off + * `resolver.pathCache`) so the pathCache's hidden-class shape is unchanged — + * that avoids perturbing the interpreter-mode IC state for the + * `resolver.pathCache.{join,dirname,basename}.fn(...)` accesses that run on + * every resolve, which the CodSpeed instruction-count harness is sensitive to. + * @type {WeakMap>} + */ +const _addrsCacheByDirs = new WeakMap(); + +/** + * @param {Resolver} resolver resolver + * @param {string[]} directories directories + * @param {ResolveStepHook} target target + * @param {ResolveRequest} request request + * @param {ResolveContext} resolveContext resolve context + * @param {InnerCallback} callback callback + * @returns {void} + */ +function modulesResolveHandler( + resolver, + directories, + target, + request, + resolveContext, + callback, +) { + const fs = resolver.fileSystem; + const requestPath = /** @type {string} */ (request.path); + // Compute-or-reuse the flat `addrs` list. Inlined (rather than a helper + // function) so the cache-hit path — which is the vast majority of + // invocations — stays a single WeakMap + Map lookup with no function-call + // overhead. See `_addrsCacheByDirs` above for caching rationale. + let addrs; + let perPath = _addrsCacheByDirs.get(directories); + if (perPath === undefined) { + perPath = new Map(); + _addrsCacheByDirs.set(directories, perPath); + } else { + addrs = perPath.get(requestPath); + } + if (addrs === undefined) { + const { paths } = getPathsCached(fs, requestPath); + const pathsLen = paths.length; + const dirsLen = directories.length; + // Pre-size the flat array rather than going through `map().reduce()` + // with intermediate arrays + spreads. + // eslint-disable-next-line unicorn/no-new-array + addrs = new Array(pathsLen * dirsLen); + let idx = 0; + const joinFn = resolver.pathCache.join.fn; + for (let pi = 0; pi < pathsLen; pi++) { + const pathItem = paths[pi]; + for (let di = 0; di < dirsLen; di++) { + addrs[idx++] = joinFn(pathItem, directories[di]); + } + } + perPath.set(requestPath, addrs); + } + // Hoist the dot-prefixed request out of the per-addr iterator. `addrs` + // can have up to `paths.length × directories.length` entries (e.g. 36 + // for an 8-deep source dir × 4-module config), and concatenating the + // same `./${request.request}` string on every iteration is wasted + // work — it's constant for the whole fan-out. + const relRequest = `./${request.request}`; + forEachBail( + addrs, + /** + * @param {string} addr addr + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @returns {void} + */ + (addr, callback) => { + fs.stat(addr, (err, stat) => { + if (!err && stat && stat.isDirectory()) { + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: addr, + request: relRequest, + module: false, + }; + const message = `looking for modules in ${addr}`; + return resolver.doResolve( + target, + obj, + message, + resolveContext, + callback, + ); + } + if (resolveContext.log) { + resolveContext.log(`${addr} doesn't exist or is not a directory`); + } + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(addr); + } + return callback(); + }); + }, + callback, + ); +} + +module.exports = { + modulesResolveHandler, +}; diff --git a/client/node_modules/enhanced-resolve/lib/NextPlugin.js b/client/node_modules/enhanced-resolve/lib/NextPlugin.js new file mode 100644 index 0000000..e59c56b --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/NextPlugin.js @@ -0,0 +1,33 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class NextPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("NextPlugin", (request, resolveContext, callback) => { + resolver.doResolve(target, request, null, resolveContext, callback); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/ParsePlugin.js b/client/node_modules/enhanced-resolve/lib/ParsePlugin.js new file mode 100644 index 0000000..c96c210 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/ParsePlugin.js @@ -0,0 +1,77 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class ParsePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Partial} requestOptions request options + * @param {string | ResolveStepHook} target target + */ + constructor(source, requestOptions, target) { + this.source = source; + this.requestOptions = requestOptions; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ParsePlugin", (request, resolveContext, callback) => { + const parsed = resolver.parse(/** @type {string} */ (request.request)); + /** @type {ResolveRequest} */ + const obj = { ...request, ...parsed, ...this.requestOptions }; + if (request.query && !parsed.query) { + obj.query = request.query; + } + if (request.fragment && !parsed.fragment) { + obj.fragment = request.fragment; + } + if (parsed && resolveContext.log) { + if (parsed.module) resolveContext.log("Parsed request is a module"); + if (parsed.directory) { + resolveContext.log("Parsed request is a directory"); + } + } + // There is an edge-case where a request with # can be a path or a fragment -> try both + if (obj.request && !obj.query && obj.fragment) { + const directory = obj.fragment.endsWith("/"); + /** @type {ResolveRequest} */ + const alternative = { + ...obj, + directory, + request: + obj.request + + (obj.directory ? "/" : "") + + (directory ? obj.fragment.slice(0, -1) : obj.fragment), + fragment: "", + }; + resolver.doResolve( + target, + alternative, + null, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + resolver.doResolve(target, obj, null, resolveContext, callback); + }, + ); + return; + } + resolver.doResolve(target, obj, null, resolveContext, callback); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/PnpPlugin.js b/client/node_modules/enhanced-resolve/lib/PnpPlugin.js new file mode 100644 index 0000000..42b230e --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/PnpPlugin.js @@ -0,0 +1,134 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Maël Nison @arcanis +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** + * @typedef {object} PnpApiImpl + * @property {(packageName: string, issuer: string, options: { considerBuiltins: boolean }) => string | null} resolveToUnqualified resolve to unqualified + */ + +module.exports = class PnpPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {PnpApiImpl} pnpApi pnpApi + * @param {string | ResolveStepHook} target target + * @param {string | ResolveStepHook} alternateTarget alternateTarget + */ + constructor(source, pnpApi, target, alternateTarget) { + this.source = source; + this.pnpApi = pnpApi; + this.target = target; + this.alternateTarget = alternateTarget; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + /** @type {ResolveStepHook} */ + const target = resolver.ensureHook(this.target); + const alternateTarget = resolver.ensureHook(this.alternateTarget); + resolver + .getHook(this.source) + .tapAsync("PnpPlugin", (request, resolveContext, callback) => { + const req = request.request; + if (!req) return callback(); + + // The trailing slash indicates to PnP that this value is a folder rather than a file + const issuer = `${request.path}/`; + + const packageMatch = /^(@[^/]+\/)?[^/]+/.exec(req); + if (!packageMatch) return callback(); + + const [packageName] = packageMatch; + const innerRequest = `.${req.slice(packageName.length)}`; + + /** @type {string | undefined | null} */ + let resolution; + /** @type {string | undefined | null} */ + let apiResolution; + try { + resolution = this.pnpApi.resolveToUnqualified(packageName, issuer, { + considerBuiltins: false, + }); + + if (resolution === null) { + // This is either not a PnP managed issuer or it's a Node builtin + // Try to continue resolving with our alternatives + resolver.doResolve( + alternateTarget, + request, + "issuer is not managed by a pnpapi", + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + // Skip alternatives + return callback(null, null); + }, + ); + return; + } + + if (resolveContext.fileDependencies) { + apiResolution = this.pnpApi.resolveToUnqualified("pnpapi", issuer, { + considerBuiltins: false, + }); + } + } catch (/** @type {unknown} */ error) { + if ( + /** @type {Error & { code: string }} */ + (error).code === "MODULE_NOT_FOUND" && + /** @type {Error & { pnpCode: string }} */ + (error).pnpCode === "UNDECLARED_DEPENDENCY" + ) { + // This is not a PnP managed dependency. + // Try to continue resolving with our alternatives + if (resolveContext.log) { + resolveContext.log("request is not managed by the pnpapi"); + for (const line of /** @type {Error} */ (error).message + .split("\n") + .filter(Boolean)) { + resolveContext.log(` ${line}`); + } + } + return callback(); + } + return callback(/** @type {Error} */ (error)); + } + + if (resolution === packageName) return callback(); + + if (apiResolution && resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(apiResolution); + } + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: resolution, + request: innerRequest, + ignoreSymlinks: true, + fullySpecified: request.fullySpecified && innerRequest !== ".", + }; + resolver.doResolve( + target, + obj, + `resolved by pnp to ${resolution}`, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + // Skip alternatives + return callback(null, null); + }, + ); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/Resolver.js b/client/node_modules/enhanced-resolve/lib/Resolver.js new file mode 100644 index 0000000..d8b45e5 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/Resolver.js @@ -0,0 +1,1226 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { AsyncSeriesBailHook, AsyncSeriesHook, SyncHook } = require("tapable"); +const createInnerContext = require("./createInnerContext"); +const { parseIdentifier } = require("./util/identifier"); +const { + PathType, + createCachedBasename, + createCachedDirname, + createCachedJoin, + getType, + normalize, +} = require("./util/path"); + +/* eslint-disable jsdoc/check-alignment */ +// TODO in the next major release use only `Promise.withResolvers()` +const _withResolvers = + // eslint-disable-next-line n/no-unsupported-features/es-syntax + Promise.withResolvers + ? /** + * @param {Resolver} self resolver + * @param {Context} context context information object + * @param {string} path context path + * @param {string} request request string + * @param {ResolveContext} resolveContext resolve context + * @returns {Promise} result + */ + (self, context, path, request, resolveContext) => { + // eslint-disable-next-line n/no-unsupported-features/es-syntax + const { promise, resolve, reject } = Promise.withResolvers(); + self.resolve(context, path, request, resolveContext, (err, res) => { + if (err) reject(err); + else resolve(/** @type {string | false} */ (res)); + }); + return promise; + } + : /** + * @param {Resolver} self resolver + * @param {Context} context context information object + * @param {string} path context path + * @param {string} request request string + * @param {ResolveContext} resolveContext resolve context + * @returns {Promise} result + */ + (self, context, path, request, resolveContext) => + new Promise((resolve, reject) => { + self.resolve(context, path, request, resolveContext, (err, res) => { + if (err) reject(err); + else resolve(/** @type {string | false} */ (res)); + }); + }); +/* eslint-enable jsdoc/check-alignment */ + +/** @typedef {import("./AliasUtils").AliasOption} AliasOption */ +/** @typedef {import("./util/path").CachedJoin} CachedJoin */ +/** @typedef {import("./util/path").CachedDirname} CachedDirname */ +/** @typedef {import("./util/path").CachedBasename} CachedBasename */ + +/** + * @typedef {object} JoinCacheEntry + * @property {CachedJoin["fn"]} fn cached join function + * @property {CachedJoin["cache"]} cache the underlying cache map + */ + +/** + * @typedef {object} DirnameCacheEntry + * @property {CachedDirname["fn"]} fn cached dirname function + * @property {CachedDirname["cache"]} cache the underlying cache map + */ + +/** + * @typedef {object} BasenameCacheEntry + * @property {CachedBasename["fn"]} fn cached dirname function + * @property {CachedBasename["cache"]} cache the underlying cache map + */ + +/** + * @typedef {object} PathCacheFunctions + * @property {JoinCacheEntry} join cached join + * @property {DirnameCacheEntry} dirname cached dirname + * @property {BasenameCacheEntry} basename cached basename + */ + +/** @type {WeakMap} */ +const _pathCacheByFs = new WeakMap(); + +const HASH_ESCAPE_RE = /#/g; + +/** @typedef {import("./ResolverFactory").ResolveOptions} ResolveOptions */ + +/** + * @typedef {object} KnownContext + * @property {string[]=} environments environments + */ + +// eslint-disable-next-line jsdoc/reject-any-type +/** @typedef {KnownContext & Record} Context */ + +/** @typedef {Error & { details?: string }} ErrorWithDetail */ + +/** @typedef {(err: ErrorWithDetail | null, res?: string | false, req?: ResolveRequest) => void} ResolveCallback */ + +/** + * @typedef {object} PossibleFileSystemError + * @property {string=} code code + * @property {number=} errno number + * @property {string=} path path + * @property {string=} syscall syscall + */ + +/** + * @template T + * @callback FileSystemCallback + * @param {PossibleFileSystemError & Error | null} err + * @param {T=} result + */ + +/** + * @typedef {string | Buffer | URL} PathLike + */ + +/** + * @typedef {PathLike | number} PathOrFileDescriptor + */ + +/** + * @typedef {object} ObjectEncodingOptions + * @property {BufferEncoding | null | undefined=} encoding encoding + */ + +/** + * @typedef {ObjectEncodingOptions | BufferEncoding | undefined | null} EncodingOption + */ + +/** @typedef {(err: NodeJS.ErrnoException | null, result?: string) => void} StringCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: Buffer) => void} BufferCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: (string | Buffer)) => void} StringOrBufferCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: IStats) => void} StatsCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: IBigIntStats) => void} BigIntStatsCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: (IStats | IBigIntStats)) => void} StatsOrBigIntStatsCallback */ +/** @typedef {(err: NodeJS.ErrnoException | Error | null, result?: JsonObject) => void} ReadJsonCallback */ + +/** + * @template T + * @typedef {object} IStatsBase + * @property {() => boolean} isFile is file + * @property {() => boolean} isDirectory is directory + * @property {() => boolean} isBlockDevice is block device + * @property {() => boolean} isCharacterDevice is character device + * @property {() => boolean} isSymbolicLink is symbolic link + * @property {() => boolean} isFIFO is FIFO + * @property {() => boolean} isSocket is socket + * @property {T} dev dev + * @property {T} ino ino + * @property {T} mode mode + * @property {T} nlink nlink + * @property {T} uid uid + * @property {T} gid gid + * @property {T} rdev rdev + * @property {T} size size + * @property {T} blksize blksize + * @property {T} blocks blocks + * @property {T} atimeMs atime ms + * @property {T} mtimeMs mtime ms + * @property {T} ctimeMs ctime ms + * @property {T} birthtimeMs birthtime ms + * @property {Date} atime atime + * @property {Date} mtime mtime + * @property {Date} ctime ctime + * @property {Date} birthtime birthtime + */ + +/** + * @typedef {IStatsBase} IStats + */ + +/** + * @typedef {IStatsBase & { atimeNs: bigint, mtimeNs: bigint, ctimeNs: bigint, birthtimeNs: bigint }} IBigIntStats + */ + +/** + * @template {string | Buffer} [T=string] + * @typedef {object} Dirent + * @property {() => boolean} isFile true when is file, otherwise false + * @property {() => boolean} isDirectory true when is directory, otherwise false + * @property {() => boolean} isBlockDevice true when is block device, otherwise false + * @property {() => boolean} isCharacterDevice true when is character device, otherwise false + * @property {() => boolean} isSymbolicLink true when is symbolic link, otherwise false + * @property {() => boolean} isFIFO true when is FIFO, otherwise false + * @property {() => boolean} isSocket true when is socket, otherwise false + * @property {T} name name + * @property {string} parentPath path + * @property {string=} path path + */ + +/** + * @typedef {object} StatOptions + * @property {(boolean | undefined)=} bigint need bigint values + */ + +/** + * @typedef {object} StatSyncOptions + * @property {(boolean | undefined)=} bigint need bigint values + * @property {(boolean | undefined)=} throwIfNoEntry throw if no entry + */ + +/** + * @typedef {{ + * (path: PathOrFileDescriptor, options: ({ encoding?: null | undefined, flag?: string | undefined } & import("events").Abortable) | undefined | null, callback: BufferCallback): void, + * (path: PathOrFileDescriptor, options: ({ encoding: BufferEncoding, flag?: string | undefined } & import("events").Abortable) | BufferEncoding, callback: StringCallback): void, + * (path: PathOrFileDescriptor, options: (ObjectEncodingOptions & { flag?: string | undefined } & import("events").Abortable) | BufferEncoding | undefined | null, callback: StringOrBufferCallback): void, + * (path: PathOrFileDescriptor, callback: BufferCallback): void, + * }} ReadFile + */ + +/** + * @typedef {"buffer" | { encoding: "buffer" }} BufferEncodingOption + */ + +/** + * @typedef {{ + * (path: PathOrFileDescriptor, options?: { encoding?: null | undefined, flag?: string | undefined } | null): Buffer, + * (path: PathOrFileDescriptor, options: { encoding: BufferEncoding, flag?: string | undefined } | BufferEncoding): string, + * (path: PathOrFileDescriptor, options?: (ObjectEncodingOptions & { flag?: string | undefined }) | BufferEncoding | null): string | Buffer, + * }} ReadFileSync + */ + +/** + * @typedef {{ + * (path: PathLike, options: { encoding: BufferEncoding | null, withFileTypes?: false | undefined, recursive?: boolean | undefined } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void): void, + * (path: PathLike, options: { encoding: "buffer", withFileTypes?: false | undefined, recursive?: boolean | undefined } | "buffer", callback: (err: NodeJS.ErrnoException | null, files?: Buffer[]) => void): void, + * (path: PathLike, options: (ObjectEncodingOptions & { withFileTypes?: false | undefined, recursive?: boolean | undefined }) | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files?: string[] | Buffer[]) => void): void, + * (path: PathLike, callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void): void, + * (path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true, recursive?: boolean | undefined }, callback: (err: NodeJS.ErrnoException | null, files?: Dirent[]) => void): void, + * (path: PathLike, options: { encoding: "buffer", withFileTypes: true, recursive?: boolean | undefined }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void): void, + * }} Readdir + */ + +/** + * @typedef {{ + * (path: PathLike, options?: { encoding: BufferEncoding | null, withFileTypes?: false | undefined, recursive?: boolean | undefined } | BufferEncoding | null): string[], + * (path: PathLike, options: { encoding: "buffer", withFileTypes?: false | undefined, recursive?: boolean | undefined } | "buffer"): Buffer[], + * (path: PathLike, options?: (ObjectEncodingOptions & { withFileTypes?: false | undefined, recursive?: boolean | undefined }) | BufferEncoding | null): string[] | Buffer[], + * (path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true, recursive?: boolean | undefined }): Dirent[], + * (path: PathLike, options: { encoding: "buffer", withFileTypes: true, recursive?: boolean | undefined }): Dirent[], + * }} ReaddirSync + */ + +/** + * @typedef {(pathOrFileDescription: PathOrFileDescriptor, callback: ReadJsonCallback) => void} ReadJson + */ + +/** + * @typedef {(pathOrFileDescription: PathOrFileDescriptor) => JsonObject} ReadJsonSync + */ + +/** + * @typedef {{ + * (path: PathLike, options: EncodingOption, callback: StringCallback): void, + * (path: PathLike, options: BufferEncodingOption, callback: BufferCallback): void, + * (path: PathLike, options: EncodingOption, callback: StringOrBufferCallback): void, + * (path: PathLike, callback: StringCallback): void, + * }} Readlink + */ + +/** + * @typedef {{ + * (path: PathLike, options?: EncodingOption): string, + * (path: PathLike, options: BufferEncodingOption): Buffer, + * (path: PathLike, options?: EncodingOption): string | Buffer, + * }} ReadlinkSync + */ + +/** + * @typedef {{ + * (path: PathLike, callback: StatsCallback): void, + * (path: PathLike, options: (StatOptions & { bigint?: false | undefined }) | undefined, callback: StatsCallback): void, + * (path: PathLike, options: StatOptions & { bigint: true }, callback: BigIntStatsCallback): void, + * (path: PathLike, options: StatOptions | undefined, callback: StatsOrBigIntStatsCallback): void, + * }} LStat + */ + +/** + * @typedef {{ + * (path: PathLike, options?: undefined): IStats, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined, + * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined }): IStats, + * (path: PathLike, options: StatSyncOptions & { bigint: true }): IBigIntStats, + * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: false | undefined }): IStats | IBigIntStats, + * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined, + * }} LStatSync + */ + +/** + * @typedef {{ + * (path: PathLike, callback: StatsCallback): void, + * (path: PathLike, options: (StatOptions & { bigint?: false | undefined }) | undefined, callback: StatsCallback): void, + * (path: PathLike, options: StatOptions & { bigint: true }, callback: BigIntStatsCallback): void, + * (path: PathLike, options: StatOptions | undefined, callback: StatsOrBigIntStatsCallback): void, + * }} Stat + */ + +/** + * @typedef {{ + * (path: PathLike, options?: undefined): IStats, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined, + * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined }): IStats, + * (path: PathLike, options: StatSyncOptions & { bigint: true }): IBigIntStats, + * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: false | undefined }): IStats | IBigIntStats, + * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined, + * }} StatSync + */ + +/** + * @typedef {{ + * (path: PathLike, options: EncodingOption, callback: StringCallback): void, + * (path: PathLike, options: BufferEncodingOption, callback: BufferCallback): void, + * (path: PathLike, options: EncodingOption, callback: StringOrBufferCallback): void, + * (path: PathLike, callback: StringCallback): void, + * }} RealPath + */ + +/** + * @typedef {{ + * (path: PathLike, options?: EncodingOption): string, + * (path: PathLike, options: BufferEncodingOption): Buffer, + * (path: PathLike, options?: EncodingOption): string | Buffer, + * }} RealPathSync + */ + +/** + * @typedef {object} FileSystem + * @property {ReadFile} readFile read file method + * @property {Readdir} readdir readdir method + * @property {ReadJson=} readJson read json method + * @property {Readlink} readlink read link method + * @property {LStat=} lstat lstat method + * @property {Stat} stat stat method + * @property {RealPath=} realpath realpath method + */ + +/** + * @typedef {object} SyncFileSystem + * @property {ReadFileSync} readFileSync read file sync method + * @property {ReaddirSync} readdirSync read dir sync method + * @property {ReadJsonSync=} readJsonSync read json sync method + * @property {ReadlinkSync} readlinkSync read link sync method + * @property {LStatSync=} lstatSync lstat sync method + * @property {StatSync} statSync stat sync method + * @property {RealPathSync=} realpathSync real path sync method + */ + +/** + * @typedef {object} ParsedIdentifier + * @property {string} request request + * @property {string} query query + * @property {string} fragment fragment + * @property {boolean} directory is directory + * @property {boolean} module is module + * @property {boolean} file is file + * @property {boolean} internal is internal + */ + +/** @typedef {string | number | boolean | null} JsonPrimitive */ +/** @typedef {JsonValue[]} JsonArray */ +/** @typedef {JsonPrimitive | JsonObject | JsonArray} JsonValue */ +/** @typedef {{ [Key in string]?: JsonValue | undefined }} JsonObject */ + +/** + * @typedef {object} TsconfigPathsMap + * @property {TsconfigPathsData} main main tsconfig paths data + * @property {string} mainContext main tsconfig base URL (absolute path) + * @property {{ [baseUrl: string]: TsconfigPathsData }} refs referenced tsconfig paths data mapped by baseUrl + * @property {{ [context: string]: TsconfigPathsData }} allContexts all contexts (main + refs) for quick lookup + * @property {string[]} contextList precomputed `Object.keys(allContexts)` — read-only; used on the `_selectPathsDataForContext` hot path + * @property {Set} fileDependencies file dependencies + */ + +/** + * @typedef {object} TsconfigPathsData + * @property {import("./AliasUtils").CompiledAliasOptions} alias tsconfig file data + * @property {string[]} modules tsconfig file data + */ + +/** + * @typedef {object} BaseResolveRequest + * @property {string | false} path path + * @property {Context=} context content + * @property {string=} descriptionFilePath description file path + * @property {string=} descriptionFileRoot description file root + * @property {JsonObject=} descriptionFileData description file data + * @property {TsconfigPathsMap | null | undefined=} tsconfigPathsMap tsconfig paths map + * @property {string=} relativePath relative path + * @property {boolean=} ignoreSymlinks true when need to ignore symlinks, otherwise false + * @property {boolean=} fullySpecified true when full specified, otherwise false + * @property {string=} __innerRequest inner request for internal usage + * @property {string=} __innerRequest_request inner request for internal usage + * @property {string=} __innerRequest_relativePath inner relative path for internal usage + */ + +/** @typedef {BaseResolveRequest & Partial} ResolveRequest */ + +/** + * @template T + * @typedef {{ add: (item: T) => void }} WriteOnlySet + */ + +/** @typedef {(request: ResolveRequest) => void} ResolveContextYield */ + +/** + * Singly-linked stack entry that also exposes a Set-like API + * (`has`, `size`, iteration). Each `doResolve` call prepends a new + * `StackEntry` that points at the previous tip via `.parent`, so pushing + * is O(1) in time and memory. Recursion detection walks the linked list + * (O(n)) but the stack is typically shallow, so this is cheaper overall + * than cloning a `Set` per call. + */ +class StackEntry { + /** + * @param {ResolveStepHook} hook hook + * @param {ResolveRequest} request request + * @param {StackEntry=} parent previous tip + * @param {Set=} preSeeded entries pre-seeded via the legacy `Set` API + */ + constructor(hook, request, parent, preSeeded) { + this.name = hook.name; + this.path = request.path; + this.request = request.request || ""; + this.query = request.query || ""; + this.fragment = request.fragment || ""; + this.directory = Boolean(request.directory); + this.module = Boolean(request.module); + /** @type {StackEntry | undefined} */ + this.parent = parent; + /** + * Strings seeded by callers that still pass `stack: new Set([...])`. + * Propagated through the chain so deeper `doResolve` calls still see + * them during recursion checks. `undefined` in the common case so + * there is no extra work on the hot path. + * @type {Set | undefined} + */ + this.preSeeded = preSeeded; + } + + /** + * Walk the linked list looking for an entry with the same request shape. + * Set-compatible: callers that used `stack.has(entry)` keep working. + * + * NOTE: kept monomorphic on purpose. An earlier draft accepted a string + * query too (so pre-5.21 plugins keeping their own `Set` of + * seen entries could probe the live stack with the formatted form), + * but adding the second shape regressed `doResolve`'s heap profile by + * ~1 MiB / 200 resolves on stack-churn — V8 keeps a polymorphic + * call-site state for `parent.has(stackEntry)` once `has` has two + * argument shapes. Plugins that need string membership can reach for + * `[...stack].find(e => e.includes(formattedString))` via the + * `String`-method proxies on `StackEntry` instead. + * @param {StackEntry} query entry to look for + * @returns {boolean} whether the stack already contains an equivalent entry + */ + has(query) { + /** @type {StackEntry | undefined} */ + let node = this; + while (node) { + if ( + node.name === query.name && + node.path === query.path && + node.request === query.request && + node.query === query.query && + node.fragment === query.fragment && + node.directory === query.directory && + node.module === query.module + ) { + return true; + } + node = node.parent; + } + return this.preSeeded !== undefined && this.preSeeded.has(query.toString()); + } + + /** + * Number of entries on the stack (oldest-to-newest length). + * @returns {number} size + */ + get size() { + let count = this.preSeeded ? this.preSeeded.size : 0; + /** @type {StackEntry | undefined} */ + let node = this; + while (node) { + count++; + node = node.parent; + } + return count; + } + + /** + * Iterate entries from oldest (root) to newest (tip), matching how a + * `Set` that was populated in insertion order would iterate. Pre-seeded + * legacy `Set` entries come first so error-message output stays + * ordered oldest-to-newest. + * + * Yields each entry as its formatted `toString()` form. Plugins written + * against the pre-5.21 `Set` shape — e.g. + * `[...resolveContext.stack].find(a => a.includes("module:"))` — keep + * working unchanged because each yielded value is a plain string with + * all of `String.prototype` available natively. Resolves that never + * iterate the stack pay nothing; iteration costs one `toString()` + * allocation per stack frame. + * @returns {IterableIterator} iterator + */ + *[Symbol.iterator]() { + if (this.preSeeded !== undefined) { + for (const entry of this.preSeeded) yield entry; + } + /** @type {StackEntry[]} */ + const entries = []; + /** @type {StackEntry | undefined} */ + let node = this; + while (node) { + entries.push(node); + node = node.parent; + } + for (let i = entries.length - 1; i >= 0; i--) yield entries[i].toString(); + } + + /** + * Human-readable form used in recursion error messages, logs, and the + * iterator above. Not memoized: caching would require an extra slot on + * every `StackEntry`, which costs heap even on resolves that never look + * at the formatted form. + * @returns {string} formatted entry + */ + toString() { + return `${this.name}: (${this.path}) ${this.request}${this.query}${ + this.fragment + }${this.directory ? " directory" : ""}${this.module ? " module" : ""}`; + } +} + +/** + * Resolve context + * @typedef {object} ResolveContext + * @property {WriteOnlySet=} contextDependencies directories that was found on file system + * @property {WriteOnlySet=} fileDependencies files that was found on file system + * @property {WriteOnlySet=} missingDependencies dependencies that was not found on file system + * @property {StackEntry | Set=} stack tip of the resolver call stack (a singly-linked list with Set-like API). For instance, `resolve → parsedResolve → describedResolve`. Accepts a legacy `Set` for back-compat with older callers; it is normalized internally without a hot-path branch. + * @property {((str: string) => void)=} log log function + * @property {ResolveContextYield=} yield yield result, if provided plugins can return several results + */ + +/** @typedef {AsyncSeriesBailHook<[ResolveRequest, ResolveContext], ResolveRequest | null>} ResolveStepHook */ + +/** + * @typedef {object} KnownHooks + * @property {SyncHook<[ResolveStepHook, ResolveRequest], void>} resolveStep resolve step hook + * @property {SyncHook<[ResolveRequest, Error]>} noResolve no resolve hook + * @property {ResolveStepHook} resolve resolve hook + * @property {AsyncSeriesHook<[ResolveRequest, ResolveContext]>} result result hook + */ + +/** + * @typedef {{ [key: string]: ResolveStepHook }} EnsuredHooks + */ + +/** + * @param {string} str input string + * @returns {string} in camel case + */ +function toCamelCase(str) { + return str.replace(/-([a-z])/g, (str) => str.slice(1).toUpperCase()); +} + +class Resolver { + /** + * @param {ResolveStepHook} hook hook + * @param {ResolveRequest} request request + * @param {StackEntry=} parent previous tip of the stack + * @param {Set=} preSeeded entries pre-seeded via the legacy `Set` API + * @returns {StackEntry} stack entry + */ + static createStackEntry(hook, request, parent, preSeeded) { + return new StackEntry(hook, request, parent, preSeeded); + } + + /** + * @param {FileSystem} fileSystem a filesystem + * @param {ResolveOptions} options options + */ + constructor(fileSystem, options) { + /** @type {FileSystem} */ + this.fileSystem = fileSystem; + /** @type {ResolveOptions} */ + this.options = options; + let pathCache = _pathCacheByFs.get(fileSystem); + if (!pathCache) { + pathCache = { + join: createCachedJoin(), + dirname: createCachedDirname(), + basename: createCachedBasename(), + }; + _pathCacheByFs.set(fileSystem, pathCache); + } + /** @type {PathCacheFunctions} */ + this.pathCache = pathCache; + /** @type {KnownHooks} */ + this.hooks = { + resolveStep: new SyncHook(["hook", "request"], "resolveStep"), + noResolve: new SyncHook(["request", "error"], "noResolve"), + resolve: new AsyncSeriesBailHook( + ["request", "resolveContext"], + "resolve", + ), + result: new AsyncSeriesHook(["result", "resolveContext"], "result"), + }; + } + + /** + * @param {string | ResolveStepHook} name hook name or hook itself + * @returns {ResolveStepHook} the hook + */ + ensureHook(name) { + if (typeof name !== "string") { + return name; + } + name = toCamelCase(name); + if (name.startsWith("before")) { + return /** @type {ResolveStepHook} */ ( + this.ensureHook(name[6].toLowerCase() + name.slice(7)).withOptions({ + stage: -10, + }) + ); + } + if (name.startsWith("after")) { + return /** @type {ResolveStepHook} */ ( + this.ensureHook(name[5].toLowerCase() + name.slice(6)).withOptions({ + stage: 10, + }) + ); + } + /** @type {ResolveStepHook} */ + const hook = /** @type {KnownHooks & EnsuredHooks} */ (this.hooks)[name]; + if (!hook) { + /** @type {KnownHooks & EnsuredHooks} */ + (this.hooks)[name] = new AsyncSeriesBailHook( + ["request", "resolveContext"], + name, + ); + + return /** @type {KnownHooks & EnsuredHooks} */ (this.hooks)[name]; + } + return hook; + } + + /** + * @param {string | ResolveStepHook} name hook name or hook itself + * @returns {ResolveStepHook} the hook + */ + getHook(name) { + if (typeof name !== "string") { + return name; + } + name = toCamelCase(name); + if (name.startsWith("before")) { + return /** @type {ResolveStepHook} */ ( + this.getHook(name[6].toLowerCase() + name.slice(7)).withOptions({ + stage: -10, + }) + ); + } + if (name.startsWith("after")) { + return /** @type {ResolveStepHook} */ ( + this.getHook(name[5].toLowerCase() + name.slice(6)).withOptions({ + stage: 10, + }) + ); + } + /** @type {ResolveStepHook} */ + const hook = /** @type {KnownHooks & EnsuredHooks} */ (this.hooks)[name]; + if (!hook) { + throw new Error(`Hook ${name} doesn't exist`); + } + return hook; + } + + /** + * @overload + * @param {string} path context path + * @param {string} request request string + * @param {ResolveContext=} resolveContext resolve context + * @returns {string | false} result + */ + /** + * @overload + * @param {Context} context context information object + * @param {string} path context path + * @param {string} request request string + * @param {ResolveContext=} resolveContext resolve context + * @returns {string | false} result + */ + /** + * @param {Context | string} context context information object or context path when no context is provided + * @param {string | ResolveContext=} path context path or resolve context when no context is provided + * @param {string | ResolveContext=} request request string or resolve context when no context is provided + * @param {ResolveContext=} resolveContext resolve context + * @returns {string | false} result + */ + resolveSync(context, path, request, resolveContext) { + /** @type {Error | null | undefined} */ + let err; + /** @type {string | false | undefined} */ + let result; + let sync = false; + // `|| {}` so the underlying `resolve()` hits its 5-arg fast path + // (skips the overload-shifting prologue) regardless of whether the + // caller supplied a resolveContext. + this.resolve( + /** @type {Context} */ (context), + /** @type {string} */ (path), + /** @type {string} */ (request), + /** @type {ResolveContext} */ (resolveContext) || {}, + (_err, r) => { + err = _err; + result = r; + sync = true; + }, + ); + if (!sync) { + throw new Error( + "Cannot 'resolveSync' because the fileSystem is not sync. Use 'resolve'!", + ); + } + if (err) throw err; + if (result === undefined) throw new Error("No result"); + return result; + } + + /** + * @overload + * @param {string} path context path + * @param {string} request request string + * @param {ResolveContext=} resolveContext resolve context + * @returns {Promise} result + */ + /** + * @overload + * @param {Context} context context information object + * @param {string} path context path + * @param {string} request request string + * @param {ResolveContext=} resolveContext resolve context + * @returns {Promise} result + */ + /** + * @param {Context | string} context context information object or context path when no context is provided + * @param {string | ResolveContext=} path context path or resolve context when no context is provided + * @param {string | ResolveContext=} request request string or resolve context when no context is provided + * @param {ResolveContext=} resolveContext resolve context + * @returns {Promise} result + */ + resolvePromise(context, path, request, resolveContext) { + // `|| {}` ensures the 5-arg fast path inside `resolve()` is reached + // even when the caller doesn't pass a resolveContext. + return _withResolvers( + this, + /** @type {Context} */ (context), + /** @type {string} */ (path), + /** @type {string} */ (request), + /** @type {ResolveContext} */ (resolveContext) || {}, + ); + } + + /** + * @overload + * @param {string} path context path + * @param {string} request request string + * @param {ResolveCallback} callback callback function + * @returns {void} + */ + /** + * @overload + * @param {string} path context path + * @param {string} request request string + * @param {ResolveContext} resolveContext resolve context + * @param {ResolveCallback} callback callback function + * @returns {void} + */ + /** + * @overload + * @param {Context} context context information object + * @param {string} path context path + * @param {string} request request string + * @param {ResolveCallback} callback callback function + * @returns {void} + */ + /** + * @overload + * @param {Context} context context information object + * @param {string} path context path + * @param {string} request request string + * @param {ResolveContext} resolveContext resolve context + * @param {ResolveCallback} callback callback function + * @returns {void} + */ + /** + * @param {Context | string} context context information object or context path when no context is provided + * @param {string | ResolveContext | ResolveCallback=} path context path or (when no context) resolve context or callback + * @param {string | ResolveContext | ResolveCallback=} request request string or (when no context) resolve context or callback + * @param {ResolveContext | ResolveCallback=} resolveContext resolve context or callback when no resolve context is provided + * @param {ResolveCallback=} callback callback function + * @returns {void} + */ + resolve(context, path, request, resolveContext, callback) { + // Fast path for the common 5-arg call (`resolver.resolve(ctx, from, + // req, resolveCtx, cb)`) — every call from `resolveSync` / + // `resolvePromise` plus the vast majority of direct API callers. + // PR #536 added runtime overload-shifting to support optional + // `context` / `resolveContext`; that adds several `typeof` checks + // per resolve which show up as a measurable instruction-count + // regression on every benchmark that calls into this method. Skip + // the shifting entirely when all 5 args are already well-typed. + if ( + typeof callback === "function" && + typeof context === "object" && + context !== null && + typeof resolveContext === "object" && + resolveContext !== null + ) { + // proceed straight to per-arg validation below + } else { + // Slow path: shift positional args based on what was supplied. + // Shift when context is omitted (first positional arg is the path string). + if (typeof context === "string") { + // Keep an already-supplied callback (resolveSync / resolvePromise + // always pass one in the 5th position). + if (typeof callback !== "function") { + callback = /** @type {ResolveCallback | undefined} */ ( + resolveContext + ); + } + resolveContext = + /** @type {ResolveContext | ResolveCallback | undefined} */ (request); + request = /** @type {string} */ (path); + path = context; + context = {}; + } + // 4-arg form: the resolveContext slot holds the callback. + if (typeof resolveContext === "function") { + callback = resolveContext; + resolveContext = {}; + } else if (!resolveContext || typeof resolveContext !== "object") { + resolveContext = {}; + } + if (typeof callback !== "function") { + throw new TypeError("callback argument is not a function"); + } + if (!context || typeof context !== "object") { + context = {}; + } + } + if (typeof path !== "string") { + return callback(new Error("path argument is not a string")); + } + if (typeof request !== "string") { + return callback(new Error("request argument is not a string")); + } + + /** @type {ResolveRequest} */ + const obj = { + context, + path, + request, + }; + + /** @type {ResolveContextYield | undefined} */ + let yield_; + let yieldCalled = false; + /** @type {ResolveContextYield | undefined} */ + let finishYield; + if (typeof resolveContext.yield === "function") { + const old = resolveContext.yield; + /** + * @param {ResolveRequest} obj object + */ + yield_ = (obj) => { + old(obj); + yieldCalled = true; + }; + /** + * @param {ResolveRequest} result result + * @returns {void} + */ + finishYield = (result) => { + if (result) { + /** @type {ResolveContextYield} */ (yield_)(result); + } + callback(null); + }; + } + + const message = `resolve '${request}' in '${path}'`; + + /** + * @param {ResolveRequest} result result + * @returns {void} + */ + const finishResolved = (result) => { + const resultPath = result.path; + if (resultPath === false) return callback(null, false, result); + const escapedPath = resultPath.includes("#") + ? resultPath.replace(HASH_ESCAPE_RE, "\0#") + : resultPath; + const resultQuery = result.query; + let escapedQuery; + if (resultQuery) { + escapedQuery = resultQuery.includes("#") + ? resultQuery.replace(HASH_ESCAPE_RE, "\0#") + : resultQuery; + } else { + escapedQuery = ""; + } + return callback( + null, + `${escapedPath}${escapedQuery}${result.fragment || ""}`, + result, + ); + }; + + /** + * @param {string[]} log logs + * @returns {void} + */ + const finishWithoutResolve = (log) => { + /** + * @type {ErrorWithDetail} + */ + const error = new Error(`Can't ${message}`); + error.details = log.join("\n"); + this.hooks.noResolve.call(obj, error); + return callback(error); + }; + + if (resolveContext.log) { + // We need log anyway to capture it in case of an error + const parentLog = resolveContext.log; + /** @type {string[]} */ + const log = []; + return this.doResolve( + this.hooks.resolve, + obj, + message, + { + log: (msg) => { + parentLog(msg); + log.push(msg); + }, + yield: yield_, + fileDependencies: resolveContext.fileDependencies, + contextDependencies: resolveContext.contextDependencies, + missingDependencies: resolveContext.missingDependencies, + stack: resolveContext.stack, + }, + (err, result) => { + if (err) return callback(err); + + if (yieldCalled || (result && yield_)) { + return /** @type {ResolveContextYield} */ (finishYield)( + /** @type {ResolveRequest} */ (result), + ); + } + + if (result) return finishResolved(result); + + return finishWithoutResolve(log); + }, + ); + } + // Try to resolve assuming there is no error + // We don't log stuff in this case + return this.doResolve( + this.hooks.resolve, + obj, + message, + { + log: undefined, + yield: yield_, + fileDependencies: resolveContext.fileDependencies, + contextDependencies: resolveContext.contextDependencies, + missingDependencies: resolveContext.missingDependencies, + stack: resolveContext.stack, + }, + (err, result) => { + if (err) return callback(err); + + if (yieldCalled || (result && yield_)) { + return /** @type {ResolveContextYield} */ (finishYield)( + /** @type {ResolveRequest} */ (result), + ); + } + + if (result) return finishResolved(result); + + // log is missing for the error details + // so we redo the resolving for the log info + // this is more expensive to the success case + // is assumed by default + /** @type {string[]} */ + const log = []; + + return this.doResolve( + this.hooks.resolve, + obj, + message, + { + log: (msg) => log.push(msg), + yield: yield_, + stack: resolveContext.stack, + }, + (err, result) => { + if (err) return callback(err); + + // In a case that there is a race condition and yield will be called + if (yieldCalled || (result && yield_)) { + return /** @type {ResolveContextYield} */ (finishYield)( + /** @type {ResolveRequest} */ (result), + ); + } + + return finishWithoutResolve(log); + }, + ); + }, + ); + } + + /** + * @param {ResolveStepHook} hook hook + * @param {ResolveRequest} request request + * @param {null | string} message string + * @param {ResolveContext} resolveContext resolver context + * @param {(err?: null | Error, result?: ResolveRequest) => void} callback callback + * @returns {void} + */ + doResolve(hook, request, message, resolveContext, callback) { + const rawStack = resolveContext.stack; + /** @type {StackEntry | undefined} */ + let parent; + /** @type {Set | undefined} */ + let preSeeded; + if (rawStack instanceof StackEntry) { + parent = rawStack; + preSeeded = rawStack.preSeeded; + } else if (rawStack) { + // TODO in the next major remove `Set` support in favor of `StackEntry` + // Legacy `stack: new Set()` API: don't link the Set into + // the parent chain (it would pollute iteration and field-compare + // walks). Carry the strings on the StackEntry itself instead so + // deeper `doResolve` calls keep seeing pre-seeded entries. + preSeeded = /** @type {Set} */ (rawStack); + } + // Prepend a new linked-list node. O(1) allocation, no Set clone. + const stackEntry = Resolver.createStackEntry( + hook, + request, + parent, + preSeeded, + ); + + // When `parent` exists, its `has()` already consults `preSeeded` + // (inherited from the same chain), so we only need the direct Set + // lookup on the very first `doResolve` call (no parent yet). + if ( + parent !== undefined + ? parent.has(stackEntry) + : preSeeded !== undefined && preSeeded.has(stackEntry.toString()) + ) { + /** + * Prevent recursion + * @type {Error & { recursion?: boolean }} + */ + const recursionError = new Error( + `Recursion in resolving\nStack:\n ${[...stackEntry].join("\n ")}`, + ); + recursionError.recursion = true; + if (resolveContext.log) { + resolveContext.log("abort resolving because of recursion"); + } + return callback(recursionError); + } + this.hooks.resolveStep.call(hook, request); + + if (hook.isUsed()) { + // Pass `resolveContext` and the override fields (stack, message) + // directly instead of constructing an intermediate options-object + // literal — `createInnerContext` reads from the parent and + // allocates exactly one inner context per step. See the comment + // on `createInnerContext` itself for the allocation rationale. + const innerContext = createInnerContext( + resolveContext, + stackEntry, + message, + ); + return hook.callAsync(request, innerContext, (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + callback(); + }); + } + callback(); + } + + /** + * @param {string} identifier identifier + * @returns {ParsedIdentifier} parsed identifier + */ + parse(identifier) { + /** @type {ParsedIdentifier} */ + const part = { + request: "", + query: "", + fragment: "", + module: false, + directory: false, + file: false, + internal: false, + }; + + const parsedIdentifier = parseIdentifier(identifier); + + if (!parsedIdentifier) return part; + + [part.request, part.query, part.fragment] = parsedIdentifier; + + if (part.request.length > 0) { + // `getType` looks at the prefix of its input and the prefix is + // identical between `identifier` and `part.request` in every + // non-`\0`-escape case (slicing off `?query` / `#fragment` doesn't + // touch the head). `parseIdentifier`'s common fast path returns + // the same `identifier` reference as `parsedIdentifier[0]`, so a + // pointer-equality check detects the case where we can compute + // `getType` once and use it for both `module` and `internal`. The + // `\0#…` escape path produces a fresh `part.request` and falls + // through to the second `getType(identifier)` call to preserve + // the original `internal` flag. + const requestType = getType(part.request); + part.module = requestType === PathType.Normal; + part.internal = + identifier === part.request + ? requestType === PathType.Internal + : getType(identifier) === PathType.Internal; + // `isDirectory` is just `endsWith("/")` — inline so `parse()` + // doesn't pay for the extra method dispatch on every resolve. + part.directory = part.request.endsWith("/"); + if (part.directory) { + part.request = part.request.slice(0, -1); + } + } + + return part; + } + + /** + * @param {string} path path + * @returns {boolean} true, if the path is a module + */ + isModule(path) { + return getType(path) === PathType.Normal; + } + + /** + * @param {string} path path + * @returns {boolean} true, if the path is private + */ + isPrivate(path) { + return getType(path) === PathType.Internal; + } + + /** + * @param {string} path a path + * @returns {boolean} true, if the path is a directory path + */ + isDirectory(path) { + return path.endsWith("/"); + } + + /** + * @param {string} path path + * @returns {string} normalized path + */ + normalize(path) { + return normalize(path); + } + + /** + * @param {string} path path + * @param {string} request request + * @returns {string} joined path + */ + join(path, request) { + return this.pathCache.join.fn(path, request); + } + + /** + * @param {string} path path + * @returns {string} parent directory + */ + dirname(path) { + return this.pathCache.dirname.fn(path); + } + + /** + * @param {string} path the path to evaluate + * @param {string=} suffix an extension to remove from the result + * @returns {string} the last portion of a path + */ + basename(path, suffix) { + return this.pathCache.basename.fn(path, suffix); + } +} + +module.exports = Resolver; diff --git a/client/node_modules/enhanced-resolve/lib/ResolverFactory.js b/client/node_modules/enhanced-resolve/lib/ResolverFactory.js new file mode 100644 index 0000000..2de8264 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/ResolverFactory.js @@ -0,0 +1,790 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +// eslint-disable-next-line n/prefer-global/process +const { versions } = require("process"); + +const AliasFieldPlugin = require("./AliasFieldPlugin"); +const AliasPlugin = require("./AliasPlugin"); +const AppendPlugin = require("./AppendPlugin"); +const ConditionalPlugin = require("./ConditionalPlugin"); +const DescriptionFilePlugin = require("./DescriptionFilePlugin"); +const DirectoryExistsPlugin = require("./DirectoryExistsPlugin"); +const ExportsFieldPlugin = require("./ExportsFieldPlugin"); +const ExtensionAliasPlugin = require("./ExtensionAliasPlugin"); +const FileExistsPlugin = require("./FileExistsPlugin"); +const ImportsFieldPlugin = require("./ImportsFieldPlugin"); +const JoinRequestPartPlugin = require("./JoinRequestPartPlugin"); +const JoinRequestPlugin = require("./JoinRequestPlugin"); +const MainFieldPlugin = require("./MainFieldPlugin"); +const ModulesInHierarchicalDirectoriesPlugin = require("./ModulesInHierarchicalDirectoriesPlugin"); +const ModulesInRootPlugin = require("./ModulesInRootPlugin"); +const NextPlugin = require("./NextPlugin"); +const ParsePlugin = require("./ParsePlugin"); +const PnpPlugin = require("./PnpPlugin"); +const Resolver = require("./Resolver"); +const RestrictionsPlugin = require("./RestrictionsPlugin"); +const ResultPlugin = require("./ResultPlugin"); +const RootsPlugin = require("./RootsPlugin"); +const SelfReferencePlugin = require("./SelfReferencePlugin"); +const SymlinkPlugin = require("./SymlinkPlugin"); +const SyncAsyncFileSystemDecorator = require("./SyncAsyncFileSystemDecorator"); +const TryNextPlugin = require("./TryNextPlugin"); +const TsconfigPathsPlugin = require("./TsconfigPathsPlugin"); +const UnsafeCachePlugin = require("./UnsafeCachePlugin"); +const UseFilePlugin = require("./UseFilePlugin"); +const { PathType, getType } = require("./util/path"); + +/** @typedef {import("./AliasPlugin").AliasOption} AliasOptionEntry */ +/** @typedef {import("./ExtensionAliasPlugin").ExtensionAliasOption} ExtensionAliasOption */ +/** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */ +/** @typedef {import("./Resolver").EnsuredHooks} EnsuredHooks */ +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").KnownHooks} KnownHooks */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ +/** @typedef {import("./UnsafeCachePlugin").Cache} Cache */ + +/** @typedef {string | string[] | false} AliasOptionNewRequest */ +/** @typedef {{ [k: string]: AliasOptionNewRequest }} AliasOptions */ +/** @typedef {{ [k: string]: string | string[] }} ExtensionAliasOptions */ +/** @typedef {false | 0 | "" | null | undefined} Falsy */ +/** @typedef {{ apply: (resolver: Resolver) => void } | ((this: Resolver, resolver: Resolver) => void) | Falsy} Plugin */ + +/** + * @typedef {object} TsconfigOptions + * @property {string=} configFile A relative path to the tsconfig file based on cwd, or an absolute path of tsconfig file + * @property {string[] | "auto"=} references References to other tsconfig files. 'auto' inherits from TypeScript config, or an array of relative/absolute paths + * @property {string=} baseUrl Override baseUrl from tsconfig.json. If provided, this value will be used instead of the baseUrl in the tsconfig file + */ + +/** + * @typedef {object} UserResolveOptions + * @property {(AliasOptions | AliasOptionEntry[])=} alias A list of module alias configurations or an object which maps key to value + * @property {(AliasOptions | AliasOptionEntry[])=} fallback A list of module alias configurations or an object which maps key to value, applied only after modules option + * @property {ExtensionAliasOptions=} extensionAlias An object which maps extension to extension aliases + * @property {boolean=} extensionAliasForExports Also apply `extensionAlias` to paths resolved through the package.json `exports` field. Off by default (Node.js-aligned); when enabled, matches TypeScript's behavior for packages that ship TS sources alongside compiled JS. + * @property {(string | string[])[]=} aliasFields A list of alias fields in description files + * @property {((predicate: ResolveRequest) => boolean)=} cachePredicate A function which decides whether a request should be cached or not. An object is passed with at least `path` and `request` properties. + * @property {boolean=} cacheWithContext Whether or not the unsafeCache should include request context as part of the cache key. + * @property {string[]=} descriptionFiles A list of description files to read from + * @property {string[]=} conditionNames A list of exports field condition names. + * @property {boolean=} enforceExtension Enforce that a extension from extensions must be used + * @property {(string | string[])[]=} exportsFields A list of exports fields in description files + * @property {(string | string[])[]=} importsFields A list of imports fields in description files + * @property {string[]=} extensions A list of extensions which should be tried for files + * @property {FileSystem} fileSystem The file system which should be used + * @property {(Cache | boolean)=} unsafeCache Use this cache object to unsafely cache the successful requests + * @property {boolean=} symlinks Resolve symlinks to their symlinked location + * @property {Resolver=} resolver A prepared Resolver to which the plugins are attached + * @property {string[] | string=} modules A list of directories to resolve modules from, can be absolute path or folder name + * @property {(string | string[] | { name: string | string[], forceRelative: boolean })[]=} mainFields A list of main fields in description files + * @property {string[]=} mainFiles A list of main files in directories + * @property {Plugin[]=} plugins A list of additional resolve plugins which should be applied + * @property {PnpApi | null=} pnpApi A PnP API that should be used - null is "never", undefined is "auto" + * @property {string[]=} roots A list of root paths + * @property {boolean=} fullySpecified The request is already fully specified and no extensions or directories are resolved for it + * @property {boolean=} resolveToContext Resolve to a context instead of a file + * @property {(string | RegExp)[]=} restrictions A list of resolve restrictions + * @property {boolean=} useSyncFileSystemCalls Use only the sync constraints of the file system calls + * @property {boolean=} preferRelative Prefer to resolve module requests as relative requests before falling back to modules + * @property {boolean=} preferAbsolute Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots + * @property {string | boolean | TsconfigOptions=} tsconfig TypeScript config file path or config object with configFile and references + */ + +/** + * @typedef {object} ResolveOptions + * @property {AliasOptionEntry[]} alias alias + * @property {AliasOptionEntry[]} fallback fallback + * @property {Set} aliasFields alias fields + * @property {ExtensionAliasOption[]} extensionAlias extension alias + * @property {boolean} extensionAliasForExports apply extension alias to exports field targets + * @property {(predicate: ResolveRequest) => boolean} cachePredicate cache predicate + * @property {boolean} cacheWithContext cache with context + * @property {Set} conditionNames A list of exports field condition names. + * @property {string[]} descriptionFiles description files + * @property {boolean} enforceExtension enforce extension + * @property {Set} exportsFields exports fields + * @property {Set} importsFields imports fields + * @property {Set} extensions extensions + * @property {FileSystem} fileSystem fileSystem + * @property {Cache | false} unsafeCache unsafe cache + * @property {boolean} symlinks symlinks + * @property {Resolver=} resolver resolver + * @property {(string | string[])[]} modules modules + * @property {{ name: string[], forceRelative: boolean }[]} mainFields main fields + * @property {Set} mainFiles main files + * @property {Plugin[]} plugins plugins + * @property {PnpApi | null} pnpApi pnp API + * @property {Set} roots roots + * @property {boolean} fullySpecified fully specified + * @property {boolean} resolveToContext resolve to context + * @property {Set} restrictions restrictions + * @property {boolean} preferRelative prefer relative + * @property {boolean} preferAbsolute prefer absolute + * @property {string | boolean | TsconfigOptions} tsconfig tsconfig file path or config object + */ + +/** + * @param {PnpApi | null=} option option + * @returns {PnpApi | null} processed option + */ +function processPnpApiOption(option) { + if ( + option === undefined && + /** @type {NodeJS.ProcessVersions & { pnp: string }} */ versions.pnp + ) { + const _findPnpApi = + /** @type {(issuer: string) => PnpApi | null}} */ + ( + // @ts-expect-error maybe nothing + require("module").findPnpApi + ); + + if (_findPnpApi) { + return { + resolveToUnqualified(request, issuer, opts) { + const pnpapi = _findPnpApi(issuer); + + if (!pnpapi) { + // Issuer isn't managed by PnP + return null; + } + + return pnpapi.resolveToUnqualified(request, issuer, opts); + }, + }; + } + } + + return option || null; +} + +/** + * @param {AliasOptions | AliasOptionEntry[] | undefined} alias alias + * @returns {AliasOptionEntry[]} normalized aliases + */ +function normalizeAlias(alias) { + return typeof alias === "object" && !Array.isArray(alias) && alias !== null + ? Object.keys(alias).map((key) => { + /** @type {AliasOptionEntry} */ + const obj = { name: key, onlyModule: false, alias: alias[key] }; + + if (/\$$/.test(key)) { + obj.onlyModule = true; + obj.name = key.slice(0, -1); + } + + return obj; + }) + : /** @type {AliasOptionEntry[]} */ (alias) || []; +} + +/** + * Merging filtered elements + * @param {string[]} array source array + * @param {(item: string) => boolean} filter predicate + * @returns {(string | string[])[]} merge result + */ +function mergeFilteredToArray(array, filter) { + /** @type {(string | string[])[]} */ + const result = []; + const set = new Set(array); + + for (const item of set) { + if (filter(item)) { + const lastElement = + result.length > 0 ? result[result.length - 1] : undefined; + if (Array.isArray(lastElement)) { + lastElement.push(item); + } else { + result.push([item]); + } + } else { + result.push(item); + } + } + + return result; +} + +/** + * @param {UserResolveOptions} options input options + * @returns {ResolveOptions} output options + */ +function createOptions(options) { + const mainFieldsSet = new Set(options.mainFields || ["main"]); + /** @type {ResolveOptions["mainFields"]} */ + const mainFields = []; + + for (const item of mainFieldsSet) { + if (typeof item === "string") { + mainFields.push({ + name: [item], + forceRelative: true, + }); + } else if (Array.isArray(item)) { + mainFields.push({ + name: item, + forceRelative: true, + }); + } else { + mainFields.push({ + name: Array.isArray(item.name) ? item.name : [item.name], + forceRelative: item.forceRelative, + }); + } + } + + return { + alias: normalizeAlias(options.alias), + fallback: normalizeAlias(options.fallback), + aliasFields: new Set(options.aliasFields), + cachePredicate: + options.cachePredicate || + function trueFn() { + return true; + }, + cacheWithContext: + typeof options.cacheWithContext !== "undefined" + ? options.cacheWithContext + : true, + exportsFields: new Set(options.exportsFields || ["exports"]), + importsFields: new Set(options.importsFields || ["imports"]), + conditionNames: new Set(options.conditionNames), + descriptionFiles: [ + ...new Set(options.descriptionFiles || ["package.json"]), + ], + enforceExtension: + options.enforceExtension === undefined + ? Boolean(options.extensions && options.extensions.includes("")) + : options.enforceExtension, + extensions: new Set(options.extensions || [".js", ".json", ".node"]), + extensionAlias: options.extensionAlias + ? Object.keys(options.extensionAlias).map((k) => ({ + extension: k, + alias: /** @type {ExtensionAliasOptions} */ (options.extensionAlias)[ + k + ], + })) + : [], + extensionAliasForExports: options.extensionAliasForExports || false, + fileSystem: options.useSyncFileSystemCalls + ? new SyncAsyncFileSystemDecorator( + /** @type {SyncFileSystem} */ ( + /** @type {unknown} */ (options.fileSystem) + ), + ) + : options.fileSystem, + unsafeCache: + options.unsafeCache && typeof options.unsafeCache !== "object" + ? /** @type {Cache} */ ({}) + : options.unsafeCache || false, + symlinks: typeof options.symlinks !== "undefined" ? options.symlinks : true, + resolver: options.resolver, + modules: mergeFilteredToArray( + Array.isArray(options.modules) + ? options.modules + : options.modules + ? [options.modules] + : ["node_modules"], + (item) => { + const type = getType(item); + return type === PathType.Normal || type === PathType.Relative; + }, + ), + mainFields, + mainFiles: new Set(options.mainFiles || ["index"]), + plugins: options.plugins || [], + pnpApi: processPnpApiOption(options.pnpApi), + roots: new Set(options.roots || undefined), + fullySpecified: options.fullySpecified || false, + resolveToContext: options.resolveToContext || false, + preferRelative: options.preferRelative || false, + preferAbsolute: options.preferAbsolute || false, + restrictions: new Set(options.restrictions), + tsconfig: + typeof options.tsconfig === "undefined" ? false : options.tsconfig, + }; +} + +/** + * @param {UserResolveOptions} options resolve options + * @returns {Resolver} created resolver + */ +module.exports.createResolver = function createResolver(options) { + const normalizedOptions = createOptions(options); + + const { + alias, + fallback, + aliasFields, + extensionAliasForExports, + cachePredicate, + cacheWithContext, + conditionNames, + descriptionFiles, + enforceExtension, + exportsFields, + extensionAlias, + importsFields, + extensions, + fileSystem, + fullySpecified, + mainFields, + mainFiles, + modules, + plugins: userPlugins, + pnpApi, + resolveToContext, + preferRelative, + preferAbsolute, + symlinks, + unsafeCache, + resolver: customResolver, + restrictions, + roots, + tsconfig, + } = normalizedOptions; + + const plugins = [...userPlugins]; + + const resolver = + customResolver || new Resolver(fileSystem, normalizedOptions); + + // // pipeline //// + + resolver.ensureHook("resolve"); + resolver.ensureHook("internalResolve"); + resolver.ensureHook("newInternalResolve"); + resolver.ensureHook("importsResolve"); + resolver.ensureHook("parsedResolve"); + resolver.ensureHook("describedResolve"); + resolver.ensureHook("rawResolve"); + resolver.ensureHook("normalResolve"); + resolver.ensureHook("internal"); + resolver.ensureHook("rawModule"); + resolver.ensureHook("alternateRawModule"); + resolver.ensureHook("module"); + resolver.ensureHook("resolveAsModule"); + resolver.ensureHook("undescribedResolveInPackage"); + resolver.ensureHook("resolveInPackage"); + resolver.ensureHook("resolveInExistingDirectory"); + resolver.ensureHook("importsFieldRelative"); + if (extensionAliasForExports) { + resolver.ensureHook("exportsFieldRelative"); + } + resolver.ensureHook("relative"); + resolver.ensureHook("describedRelative"); + resolver.ensureHook("directory"); + resolver.ensureHook("undescribedExistingDirectory"); + resolver.ensureHook("existingDirectory"); + resolver.ensureHook("undescribedRawFile"); + resolver.ensureHook("rawFile"); + resolver.ensureHook("file"); + resolver.ensureHook("finalFile"); + resolver.ensureHook("existingFile"); + resolver.ensureHook("resolved"); + + // TODO remove in next major + // cspell:word Interal + // Backward-compat + // @ts-expect-error + resolver.hooks.newInteralResolve = resolver.hooks.newInternalResolve; + + // resolve + for (const { source, resolveOptions } of [ + { source: "resolve", resolveOptions: { fullySpecified } }, + { source: "internal-resolve", resolveOptions: { fullySpecified: false } }, + // Entry point for non-relative targets from the imports field. + // Sets internal: false to prevent re-entering imports resolution, + // aligning with the Node.js ESM spec where PACKAGE_IMPORTS_RESOLVE + // does not recursively resolve # specifiers. + // https://nodejs.org/api/esm.html#resolution-algorithm-specification + { + source: "imports-resolve", + resolveOptions: { fullySpecified: false, internal: false }, + }, + ]) { + plugins.push(new ParsePlugin(source, resolveOptions, "parsed-resolve")); + } + + // parsed-resolve + plugins.push( + new DescriptionFilePlugin( + "parsed-resolve", + descriptionFiles, + false, + "described-resolve", + ), + ); + plugins.push(new NextPlugin("after-parsed-resolve", "described-resolve")); + + // described-resolve + if (unsafeCache) { + plugins.push( + new UnsafeCachePlugin( + "described-resolve", + cachePredicate, + /** @type {import("./UnsafeCachePlugin").Cache} */ (unsafeCache), + cacheWithContext, + "raw-resolve", + ), + ); + } else { + plugins.push(new NextPlugin("described-resolve", "raw-resolve")); + } + if (fallback.length > 0) { + plugins.push( + new AliasPlugin("described-resolve", fallback, "internal-resolve"), + ); + } + // raw-resolve + if (alias.length > 0) { + plugins.push(new AliasPlugin("raw-resolve", alias, "internal-resolve")); + } + if (tsconfig) { + plugins.push(new TsconfigPathsPlugin(tsconfig)); + } + for (const item of aliasFields) { + plugins.push(new AliasFieldPlugin("raw-resolve", item, "internal-resolve")); + } + for (const item of extensionAlias) { + plugins.push( + new ExtensionAliasPlugin("raw-resolve", item, "normal-resolve"), + ); + } + plugins.push(new NextPlugin("raw-resolve", "normal-resolve")); + + // normal-resolve + if (preferRelative) { + plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); + } + plugins.push( + new ConditionalPlugin( + "after-normal-resolve", + { module: true }, + "resolve as module", + false, + "raw-module", + ), + ); + plugins.push( + new ConditionalPlugin( + "after-normal-resolve", + { internal: true }, + "resolve as internal import", + false, + "internal", + ), + ); + if (preferAbsolute) { + plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); + } + if (roots.size > 0) { + plugins.push(new RootsPlugin("after-normal-resolve", roots, "relative")); + } + if (!preferRelative && !preferAbsolute) { + plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); + } + + // internal + for (const importsField of importsFields) { + plugins.push( + new ImportsFieldPlugin( + "internal", + conditionNames, + importsField, + "imports-field-relative", + "imports-resolve", + ), + ); + } + // imports-field-relative: apply extensionAlias to paths produced by the + // imports field (TypeScript-style extension substitution for self-package + // imports like `#foo` -> `./foo.js` -> `./foo.ts`). Unlike the exports + // field, the imports field is internal to the package, so applying the + // consumer's extension aliases does not expose files the package author + // did not intend to export. See issue #413. + for (const item of extensionAlias) { + plugins.push( + new ExtensionAliasPlugin("imports-field-relative", item, "relative"), + ); + } + plugins.push(new NextPlugin("imports-field-relative", "relative")); + + // raw-module + for (const exportsField of exportsFields) { + plugins.push( + new SelfReferencePlugin("raw-module", exportsField, "resolve-as-module"), + ); + } + for (const item of modules) { + if (Array.isArray(item)) { + if (item.includes("node_modules") && pnpApi) { + plugins.push( + new ModulesInHierarchicalDirectoriesPlugin( + "raw-module", + item.filter((i) => i !== "node_modules"), + "module", + ), + ); + plugins.push( + new PnpPlugin( + "raw-module", + pnpApi, + "undescribed-resolve-in-package", + "alternate-raw-module", + ), + ); + + plugins.push( + new ModulesInHierarchicalDirectoriesPlugin( + "alternate-raw-module", + ["node_modules"], + "module", + ), + ); + } else { + plugins.push( + new ModulesInHierarchicalDirectoriesPlugin( + "raw-module", + item, + "module", + ), + ); + } + } else { + plugins.push(new ModulesInRootPlugin("raw-module", item, "module")); + } + } + + // module + plugins.push(new JoinRequestPartPlugin("module", "resolve-as-module")); + + // resolve-as-module + if (!resolveToContext) { + plugins.push( + new ConditionalPlugin( + "resolve-as-module", + { directory: false, request: "." }, + "single file module", + true, + "undescribed-raw-file", + ), + ); + } + plugins.push( + new DirectoryExistsPlugin( + "resolve-as-module", + "undescribed-resolve-in-package", + ), + ); + + // undescribed-resolve-in-package + plugins.push( + new DescriptionFilePlugin( + "undescribed-resolve-in-package", + descriptionFiles, + false, + "resolve-in-package", + ), + ); + plugins.push( + new NextPlugin( + "after-undescribed-resolve-in-package", + "resolve-in-package", + ), + ); + + // resolve-in-package + const exportsFieldTarget = extensionAliasForExports + ? "exports-field-relative" + : "relative"; + for (const exportsField of exportsFields) { + plugins.push( + new ExportsFieldPlugin( + "resolve-in-package", + conditionNames, + exportsField, + exportsFieldTarget, + ), + ); + } + plugins.push( + new NextPlugin("resolve-in-package", "resolve-in-existing-directory"), + ); + + // exports-field-relative (opt-in via `extensionAliasForExports`): + // apply `extensionAlias` to paths produced by the exports field. This is + // off by default to match Node.js (which does not substitute extensions on + // bare-module targets), and on opt-in aligns with TypeScript for packages + // that ship TS sources alongside the compiled JS they list in `exports`. + if (extensionAliasForExports) { + for (const item of extensionAlias) { + plugins.push( + new ExtensionAliasPlugin("exports-field-relative", item, "relative"), + ); + } + plugins.push(new NextPlugin("exports-field-relative", "relative")); + } + + // resolve-in-existing-directory + plugins.push( + new JoinRequestPlugin("resolve-in-existing-directory", "relative"), + ); + + // relative + plugins.push( + new DescriptionFilePlugin( + "relative", + descriptionFiles, + true, + "described-relative", + ), + ); + plugins.push(new NextPlugin("after-relative", "described-relative")); + + // described-relative + if (resolveToContext) { + plugins.push(new NextPlugin("described-relative", "directory")); + } else { + plugins.push( + new ConditionalPlugin( + "described-relative", + { directory: false }, + null, + true, + "raw-file", + ), + ); + plugins.push( + new ConditionalPlugin( + "described-relative", + { fullySpecified: false }, + "as directory", + true, + "directory", + ), + ); + } + + // directory + plugins.push( + new DirectoryExistsPlugin("directory", "undescribed-existing-directory"), + ); + + if (resolveToContext) { + // undescribed-existing-directory + plugins.push(new NextPlugin("undescribed-existing-directory", "resolved")); + } else { + // undescribed-existing-directory + plugins.push( + new DescriptionFilePlugin( + "undescribed-existing-directory", + descriptionFiles, + false, + "existing-directory", + ), + ); + for (const item of mainFiles) { + plugins.push( + new UseFilePlugin( + "undescribed-existing-directory", + item, + "undescribed-raw-file", + ), + ); + } + + // described-existing-directory + for (const item of mainFields) { + plugins.push( + new MainFieldPlugin( + "existing-directory", + item, + "resolve-in-existing-directory", + ), + ); + } + for (const item of mainFiles) { + plugins.push( + new UseFilePlugin("existing-directory", item, "undescribed-raw-file"), + ); + } + + // undescribed-raw-file + plugins.push( + new DescriptionFilePlugin( + "undescribed-raw-file", + descriptionFiles, + true, + "raw-file", + ), + ); + plugins.push(new NextPlugin("after-undescribed-raw-file", "raw-file")); + + // raw-file + plugins.push( + new ConditionalPlugin( + "raw-file", + { fullySpecified: true }, + null, + false, + "file", + ), + ); + if (!enforceExtension) { + plugins.push(new TryNextPlugin("raw-file", "no extension", "file")); + } + for (const item of extensions) { + plugins.push(new AppendPlugin("raw-file", item, "file")); + } + + // file + if (alias.length > 0) { + plugins.push(new AliasPlugin("file", alias, "internal-resolve")); + } + for (const item of aliasFields) { + plugins.push(new AliasFieldPlugin("file", item, "internal-resolve")); + } + plugins.push(new NextPlugin("file", "final-file")); + + // final-file + plugins.push(new FileExistsPlugin("final-file", "existing-file")); + + // existing-file + if (symlinks) { + plugins.push(new SymlinkPlugin("existing-file", "existing-file")); + } + plugins.push(new NextPlugin("existing-file", "resolved")); + } + + const { resolved } = + /** @type {KnownHooks & EnsuredHooks} */ + (resolver.hooks); + + // resolved + if (restrictions.size > 0) { + plugins.push(new RestrictionsPlugin(resolved, restrictions)); + } + + plugins.push(new ResultPlugin(resolved)); + + // // RESOLVER //// + + for (const plugin of plugins) { + if (typeof plugin === "function") { + /** @type {(this: Resolver, resolver: Resolver) => void} */ + (plugin).call(resolver, resolver); + } else if (plugin) { + plugin.apply(resolver); + } + } + + return resolver; +}; diff --git a/client/node_modules/enhanced-resolve/lib/RestrictionsPlugin.js b/client/node_modules/enhanced-resolve/lib/RestrictionsPlugin.js new file mode 100644 index 0000000..6faaa26 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/RestrictionsPlugin.js @@ -0,0 +1,70 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +const slashCode = "/".charCodeAt(0); +const backslashCode = "\\".charCodeAt(0); + +/** + * @param {string} path path + * @param {string} parent parent path + * @returns {boolean} true, if path is inside of parent + */ +const isInside = (path, parent) => { + if (!path.startsWith(parent)) return false; + if (path.length === parent.length) return true; + const charCode = path.charCodeAt(parent.length); + return charCode === slashCode || charCode === backslashCode; +}; + +module.exports = class RestrictionsPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Set} restrictions restrictions + */ + constructor(source, restrictions) { + this.source = source; + this.restrictions = restrictions; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + resolver + .getHook(this.source) + .tapAsync("RestrictionsPlugin", (request, resolveContext, callback) => { + if (typeof request.path === "string") { + const { path } = request; + for (const rule of this.restrictions) { + if (typeof rule === "string") { + if (!isInside(path, rule)) { + if (resolveContext.log) { + resolveContext.log( + `${path} is not inside of the restriction ${rule}`, + ); + } + return callback(null, null); + } + } else if (!rule.test(path)) { + if (resolveContext.log) { + resolveContext.log( + `${path} doesn't match the restriction ${rule}`, + ); + } + return callback(null, null); + } + } + } + + callback(); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/ResultPlugin.js b/client/node_modules/enhanced-resolve/lib/ResultPlugin.js new file mode 100644 index 0000000..57dbddd --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/ResultPlugin.js @@ -0,0 +1,43 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class ResultPlugin { + /** + * @param {ResolveStepHook} source source + */ + constructor(source) { + this.source = source; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + this.source.tapAsync( + "ResultPlugin", + (request, resolverContext, callback) => { + const obj = { ...request }; + if (resolverContext.log) { + resolverContext.log(`reporting result ${obj.path}`); + } + resolver.hooks.result.callAsync(obj, resolverContext, (err) => { + if (err) return callback(err); + if (typeof resolverContext.yield === "function") { + resolverContext.yield(obj); + callback(null, null); + } else { + callback(null, obj); + } + }); + }, + ); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/RootsPlugin.js b/client/node_modules/enhanced-resolve/lib/RootsPlugin.js new file mode 100644 index 0000000..539e08b --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/RootsPlugin.js @@ -0,0 +1,69 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const forEachBail = require("./forEachBail"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +class RootsPlugin { + /** + * @param {string | ResolveStepHook} source source hook + * @param {Set} roots roots + * @param {string | ResolveStepHook} target target hook + */ + constructor(source, roots, target) { + this.roots = [...roots]; + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + + resolver + .getHook(this.source) + .tapAsync("RootsPlugin", (request, resolveContext, callback) => { + const req = request.request; + if (!req) return callback(); + if (!req.startsWith("/")) return callback(); + + forEachBail( + this.roots, + /** + * @param {string} root root + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @returns {void} + */ + (root, callback) => { + const path = resolver.join(root, req.slice(1)); + /** @type {ResolveRequest} */ + const obj = { + ...request, + path, + relativePath: request.relativePath && path, + }; + resolver.doResolve( + target, + obj, + `root path ${root}`, + resolveContext, + callback, + ); + }, + callback, + ); + }); + } +} + +module.exports = RootsPlugin; diff --git a/client/node_modules/enhanced-resolve/lib/SelfReferencePlugin.js b/client/node_modules/enhanced-resolve/lib/SelfReferencePlugin.js new file mode 100644 index 0000000..b1ee64b --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/SelfReferencePlugin.js @@ -0,0 +1,106 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const DescriptionFileUtils = require("./DescriptionFileUtils"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonObject} JsonObject */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +const slashCode = "/".charCodeAt(0); + +// Sentinel stored in `_nameCache` when the description file either has no +// exports field (so self-reference can't apply) or no string `name`. +const NO_SELF_REF = Symbol("NoSelfRef"); + +module.exports = class SelfReferencePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | string[]} fieldNamePath name path + * @param {string | ResolveStepHook} target target + */ + constructor(source, fieldNamePath, target) { + this.source = source; + this.target = target; + this.fieldName = fieldNamePath; + // Self-reference needs both an exports field and a `"name"` string. + // Both are stable per description-file content, so cache the decision + // in one WeakMap: the resolved name when self-reference is possible, + // or `NO_SELF_REF` when it isn't. This skips the two per-resolve + // `DescriptionFileUtils.getField` walks for hot packages. + /** @type {WeakMap} */ + this._nameCache = new WeakMap(); + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("SelfReferencePlugin", (request, resolveContext, callback) => { + if (!request.descriptionFileData) return callback(); + + const req = request.request; + if (!req) return callback(); + + const { descriptionFileData } = request; + let name = this._nameCache.get(descriptionFileData); + if (name === undefined) { + // Feature is only enabled when an exports field is present + const exportsField = DescriptionFileUtils.getField( + descriptionFileData, + this.fieldName, + ); + if (!exportsField) { + this._nameCache.set(descriptionFileData, NO_SELF_REF); + return callback(); + } + const rawName = DescriptionFileUtils.getField( + descriptionFileData, + "name", + ); + if (typeof rawName !== "string") { + this._nameCache.set(descriptionFileData, NO_SELF_REF); + return callback(); + } + name = rawName; + this._nameCache.set(descriptionFileData, name); + } else if (name === NO_SELF_REF) { + return callback(); + } + + if ( + req.startsWith(name) && + (req.length === name.length || + req.charCodeAt(name.length) === slashCode) + ) { + const remainingRequest = `.${req.slice(name.length)}`; + /** @type {ResolveRequest} */ + const obj = { + ...request, + request: remainingRequest, + path: /** @type {string} */ (request.descriptionFileRoot), + relativePath: ".", + }; + + resolver.doResolve( + target, + obj, + "self reference", + resolveContext, + callback, + ); + } else { + return callback(); + } + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/SymlinkPlugin.js b/client/node_modules/enhanced-resolve/lib/SymlinkPlugin.js new file mode 100644 index 0000000..04779a6 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/SymlinkPlugin.js @@ -0,0 +1,121 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const forEachBail = require("./forEachBail"); +const { getPathsCached } = require("./getPaths"); +const { PathType, getType } = require("./util/path"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class SymlinkPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const fs = resolver.fileSystem; + resolver + .getHook(this.source) + .tapAsync("SymlinkPlugin", (request, resolveContext, callback) => { + if (request.ignoreSymlinks) return callback(); + const pathsResult = getPathsCached( + fs, + /** @type {string} */ (request.path), + ); + const { paths, segments } = pathsResult; + // `pathsResult.segments` is shared across callers via the cache. + // The only place we need to mutate is `pathSegments[idx] = result` + // when `fs.readlink` succeeds — which is rare (the vast majority + // of paths contain no symlinks, e.g. every resolve on + // `cache-predicate`'s no-symlink fixture). Defer the copy until + // we actually see a symlink so the common no-symlink path stays + // allocation-free. + /** @type {string[] | null} */ + let pathSegments = null; + + let containsSymlink = false; + let idx = -1; + forEachBail( + paths, + /** + * @param {string} path path + * @param {(err?: null | Error, result?: null | number) => void} callback callback + * @returns {void} + */ + (path, callback) => { + idx++; + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(path); + } + fs.readlink(path, (err, result) => { + if (!err && result) { + // First symlink seen — take our own copy now, so + // the cached `segments` array stays pristine for + // sibling resolves. + if (pathSegments === null) { + pathSegments = [...segments]; + } + pathSegments[idx] = /** @type {string} */ (result); + containsSymlink = true; + // Shortcut when absolute symlink found + const resultType = getType(result.toString()); + if ( + resultType === PathType.AbsoluteWin || + resultType === PathType.AbsolutePosix + ) { + return callback(null, idx); + } + } + callback(); + }); + }, + /** + * @param {null | Error=} err error + * @param {null | number=} idx result + * @returns {void} + */ + (err, idx) => { + if (!containsSymlink) return callback(); + // `containsSymlink === true` implies we took a copy in + // `pathSegments` already, so it's non-null. The copy is + // our own, so `slice` to trim is fine and spreading to + // "unshare" is no longer necessary. + const own = /** @type {string[]} */ (pathSegments); + const resultSegments = + typeof idx === "number" ? own.slice(0, idx + 1) : own; + const result = resultSegments.reduceRight((a, b) => + resolver.join(a, b), + ); + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: result, + }; + resolver.doResolve( + target, + obj, + `resolved symlink to ${result}`, + resolveContext, + callback, + ); + }, + ); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/SyncAsyncFileSystemDecorator.js b/client/node_modules/enhanced-resolve/lib/SyncAsyncFileSystemDecorator.js new file mode 100644 index 0000000..2a526d2 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/SyncAsyncFileSystemDecorator.js @@ -0,0 +1,258 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").StringCallback} StringCallback */ +/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ + +// eslint-disable-next-line jsdoc/reject-function-type +/** @typedef {Function} SyncOrAsyncFunction */ +// eslint-disable-next-line jsdoc/reject-any-type +/** @typedef {any} ResultOfSyncOrAsyncFunction */ + +/** + * @param {SyncFileSystem} fs file system implementation + * @constructor + */ +function SyncAsyncFileSystemDecorator(fs) { + this.fs = fs; + + this.lstat = undefined; + this.lstatSync = undefined; + const { lstatSync } = fs; + if (lstatSync) { + this.lstat = + /** @type {FileSystem["lstat"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? lstatSync.call(fs, arg, options) + : lstatSync.call(fs, arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + ); + } + + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.lstatSync = + /** @type {SyncFileSystem["lstatSync"]} */ + ((arg, options) => lstatSync.call(fs, arg, options)); + } + + this.stat = + /** @type {FileSystem["stat"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? fs.statSync(arg, options) + : fs.statSync(arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + ); + } + + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.statSync = + /** @type {SyncFileSystem["statSync"]} */ + ((arg, options) => fs.statSync(arg, options)); + + this.readdir = + /** @type {FileSystem["readdir"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? fs.readdirSync( + arg, + /** @type {Exclude[1], (err: NodeJS.ErrnoException | null, files: string[]) => void>} */ + (options), + ) + : fs.readdirSync(arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + [], + ); + } + + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.readdirSync = + /** @type {SyncFileSystem["readdirSync"]} */ + ( + (arg, options) => + fs.readdirSync( + arg, + /** @type {Parameters[1]} */ (options), + ) + ); + + this.readFile = + /** @type {FileSystem["readFile"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? fs.readFileSync(arg, options) + : fs.readFileSync(arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + ); + } + + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.readFileSync = + /** @type {SyncFileSystem["readFileSync"]} */ + ((arg, options) => fs.readFileSync(arg, options)); + + this.readlink = + /** @type {FileSystem["readlink"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? fs.readlinkSync( + arg, + /** @type {Exclude[1], StringCallback>} */ + (options), + ) + : fs.readlinkSync(arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + ); + } + + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.readlinkSync = + /** @type {SyncFileSystem["readlinkSync"]} */ + ( + (arg, options) => + fs.readlinkSync( + arg, + /** @type {Parameters[1]} */ ( + options + ), + ) + ); + + this.readJson = undefined; + this.readJsonSync = undefined; + const { readJsonSync } = fs; + if (readJsonSync) { + this.readJson = + /** @type {FileSystem["readJson"]} */ + ( + (arg, callback) => { + let result; + try { + result = readJsonSync.call(fs, arg); + } catch (err) { + return callback( + /** @type {NodeJS.ErrnoException | Error | null} */ (err), + ); + } + + callback(null, result); + } + ); + this.readJsonSync = + /** @type {SyncFileSystem["readJsonSync"]} */ + ((arg) => readJsonSync.call(fs, arg)); + } + + this.realpath = undefined; + this.realpathSync = undefined; + const { realpathSync } = fs; + if (realpathSync) { + this.realpath = + /** @type {FileSystem["realpath"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? realpathSync.call( + fs, + arg, + /** @type {Exclude>[1], StringCallback>} */ + (options), + ) + : realpathSync.call(fs, arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + ); + } + + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.realpathSync = + /** @type {SyncFileSystem["realpathSync"]} */ + ( + (arg, options) => + realpathSync.call( + fs, + arg, + /** @type {Parameters>[1]} */ + (options), + ) + ); + } +} + +module.exports = SyncAsyncFileSystemDecorator; diff --git a/client/node_modules/enhanced-resolve/lib/TryNextPlugin.js b/client/node_modules/enhanced-resolve/lib/TryNextPlugin.js new file mode 100644 index 0000000..4b46787 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/TryNextPlugin.js @@ -0,0 +1,41 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class TryNextPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} message message + * @param {string | ResolveStepHook} target target + */ + constructor(source, message, target) { + this.source = source; + this.message = message; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("TryNextPlugin", (request, resolveContext, callback) => { + resolver.doResolve( + target, + request, + this.message, + resolveContext, + callback, + ); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/TsconfigPathsPlugin.js b/client/node_modules/enhanced-resolve/lib/TsconfigPathsPlugin.js new file mode 100644 index 0000000..ee8decf --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/TsconfigPathsPlugin.js @@ -0,0 +1,865 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Natsu @xiaoxiaojx +*/ + +"use strict"; + +const { aliasResolveHandler, compileAliasOptions } = require("./AliasUtils"); +const { modulesResolveHandler } = require("./ModulesUtils"); +const { readJson } = require("./util/fs"); +const { PathType: _PathType, isSubPath, normalize } = require("./util/path"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./AliasUtils").AliasOption} AliasOption */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").TsconfigPathsData} TsconfigPathsData */ +/** @typedef {import("./Resolver").TsconfigPathsMap} TsconfigPathsMap */ +/** @typedef {import("./ResolverFactory").TsconfigOptions} TsconfigOptions */ + +// Sentinel stored in `_contextSelectionCache` for `requestPath`s whose +// scan returned `null` ("no context matched"). Using a non-null marker +// lets the cache-hit path be a single `Map.get()` — we distinguish +// "cached null" from "not cached yet" without a second `has` lookup. +const NULL_CONTEXT = Symbol("NULL_CONTEXT"); + +/** + * Per-`TsconfigPathsMap` memoization of `_selectPathsDataForContext`. + * + * Real-world builds resolve hundreds of requests per source file (every + * import in the file), and webpack-style resolvers walk the same + * `requestPath` (= source-file directory) for each one. Without this + * cache every resolve re-scans the full `contextList` even though the + * answer is invariant for a given `(map, requestPath)` pair. + * + * The outer key is the `TsconfigPathsMap` itself — rebuilt on every + * tsconfig change — so a `WeakMap` lets the inner map be collected + * automatically once the map goes away. The inner Map is keyed by + * `requestPath` (string); a `Symbol` sentinel stands in for "no + * matching context" so `Map.get` alone distinguishes the three states + * (cached data / cached null / not cached). + * @type {WeakMap>} + */ +const _contextSelectionCache = new WeakMap(); + +/** + * @typedef {object} TsconfigCompilerOptions + * @property {string=} baseUrl Base URL for resolving paths + * @property {{ [key: string]: string[] }=} paths TypeScript paths mapping + */ + +/** + * @typedef {object} TsconfigReference + * @property {string} path Path to the referenced project + */ + +/** + * @typedef {object} Tsconfig + * @property {TsconfigCompilerOptions=} compilerOptions Compiler options + * @property {string | string[]=} extends Extended configuration paths + * @property {TsconfigReference[]=} references Project references + */ + +const DEFAULT_CONFIG_FILE = "tsconfig.json"; + +const READ_JSON_OPTIONS = { stripComments: true }; + +// Trailing `/*` or `\*` segment of a tsconfig `paths` mapping (e.g. +// `./src/*` → `./src`). Hoisted so we don't allocate a fresh regex per +// path entry on every tsconfig load — and so the same regex object can be +// reused for the matching `test` + `replace` pair below. +const WILDCARD_TAIL_RE = /[/\\]\*$/; + +/** + * @param {string} pattern Path pattern + * @returns {number} Length of the prefix + */ +function getPrefixLength(pattern) { + const prefixLength = pattern.indexOf("*"); + if (prefixLength === -1) { + return pattern.length; + } + return prefixLength; +} + +/** + * Sort path patterns. + * If a module name can be matched with multiple patterns then pattern with the longest prefix will be picked. + * @param {string[]} arr Array of path patterns + * @returns {string[]} Array of path patterns sorted by longest prefix + */ +function sortByLongestPrefix(arr) { + return [...arr].sort((a, b) => getPrefixLength(b) - getPrefixLength(a)); +} + +/** + * Merge two tsconfig objects + * @param {Tsconfig | null} base base config + * @param {Tsconfig | null} config config to merge + * @returns {Tsconfig} merged config + */ +function mergeTsconfigs(base, config) { + base = base || {}; + config = config || {}; + + return { + ...base, + ...config, + compilerOptions: { + .../** @type {TsconfigCompilerOptions} */ (base.compilerOptions), + .../** @type {TsconfigCompilerOptions} */ (config.compilerOptions), + }, + }; +} + +/** + * Substitute ${configDir} template variable in path + * @param {string} pathValue the path value + * @param {string} configDir the config directory + * @returns {string} the path with substituted template + */ +function substituteConfigDir(pathValue, configDir) { + // eslint-disable-next-line no-template-curly-in-string + if (!pathValue.includes("${configDir}")) return pathValue; + return pathValue.replace(/\$\{configDir\}/g, configDir); +} + +/** + * Convert tsconfig paths to resolver options + * @param {string} configDir Config file directory + * @param {{ [key: string]: string[] }} paths TypeScript paths mapping + * @param {Resolver} resolver resolver instance + * @param {string=} baseUrl Base URL for resolving paths (relative to configDir) + * @returns {TsconfigPathsData} the resolver options + */ +function tsconfigPathsToResolveOptions(configDir, paths, resolver, baseUrl) { + // Calculate absolute base URL + const absoluteBaseUrl = !baseUrl + ? configDir + : resolver.join(configDir, baseUrl); + + /** @type {string[]} */ + const sortedKeys = sortByLongestPrefix(Object.keys(paths)); + /** @type {AliasOption[]} */ + const alias = []; + /** @type {string[]} */ + const modules = []; + + for (const pattern of sortedKeys) { + const mappings = paths[pattern]; + // Substitute ${configDir} in path mappings + const absolutePaths = mappings.map((mapping) => { + const substituted = substituteConfigDir(mapping, configDir); + return resolver.join(absoluteBaseUrl, substituted); + }); + + if (absolutePaths.length > 0) { + if (pattern === "*") { + // Pull `dir/*` entries directly into `modules` with their + // trailing wildcard stripped, skipping anything else. The + // previous `.map(...).filter(Boolean)` form allocated two + // throwaway arrays plus a spread iterator per `*` mapping. + for (let j = 0; j < absolutePaths.length; j++) { + const dir = absolutePaths[j]; + if (WILDCARD_TAIL_RE.test(dir)) { + modules.push(dir.replace(WILDCARD_TAIL_RE, "")); + } + } + } else { + alias.push({ name: pattern, alias: absolutePaths }); + } + } + } + + if (baseUrl && absoluteBaseUrl && !modules.includes(absoluteBaseUrl)) { + modules.push(absoluteBaseUrl); + } + + return { + alias: compileAliasOptions(resolver, alias), + modules, + }; +} + +/** + * Get the base context for the current project + * @param {string} context the context + * @param {Resolver} resolver resolver instance + * @param {string=} baseUrl base URL for resolving paths + * @returns {string} the base context + */ +function getAbsoluteBaseUrl(context, resolver, baseUrl) { + return !baseUrl ? context : resolver.join(context, baseUrl); +} + +/** + * @param {TsconfigPathsData} main main paths data + * @param {string} mainContext main context + * @param {{ [baseUrl: string]: TsconfigPathsData }} refs references map + * @param {Set} fileDependencies file dependencies + * @returns {TsconfigPathsMap} the tsconfig paths map + */ +function buildTsconfigPathsMap(main, mainContext, refs, fileDependencies) { + const allContexts = /** @type {{ [context: string]: TsconfigPathsData }} */ ({ + [mainContext]: main, + ...refs, + }); + // Precompute the key list once per tsconfig load. `_selectPathsDataForContext` + // runs per resolve and otherwise would call `Object.entries(allContexts)` + // each time, allocating a fresh [key, value][] array. + const contextList = Object.keys(allContexts); + return { + main, + mainContext, + refs, + allContexts, + contextList, + fileDependencies, + }; +} + +module.exports = class TsconfigPathsPlugin { + /** + * @param {true | string | TsconfigOptions} configFileOrOptions tsconfig file path or options object + */ + constructor(configFileOrOptions) { + if ( + typeof configFileOrOptions === "object" && + configFileOrOptions !== null + ) { + // Options object format + const { configFile } = configFileOrOptions; + /** @type {boolean} */ + this.isAutoConfigFile = typeof configFile !== "string"; + /** @type {string} */ + this.configFile = this.isAutoConfigFile + ? DEFAULT_CONFIG_FILE + : /** @type {string} */ (configFile); + /** @type {string[] | "auto"} */ + if (Array.isArray(configFileOrOptions.references)) { + /** @type {TsconfigReference[] | "auto"} */ + this.references = configFileOrOptions.references.map((ref) => ({ + path: ref, + })); + } else if (configFileOrOptions.references === "auto") { + this.references = "auto"; + } else { + this.references = []; + } + /** @type {string | undefined} */ + this.baseUrl = configFileOrOptions.baseUrl; + } else { + /** @type {boolean} */ + this.isAutoConfigFile = configFileOrOptions === true; + /** @type {string} */ + this.configFile = this.isAutoConfigFile + ? DEFAULT_CONFIG_FILE + : /** @type {string} */ (configFileOrOptions); + /** @type {TsconfigReference[] | "auto"} */ + this.references = []; + /** @type {string | undefined} */ + this.baseUrl = undefined; + } + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const aliasTarget = resolver.ensureHook("internal-resolve"); + const moduleTarget = resolver.ensureHook("module"); + + resolver + .getHook("raw-resolve") + .tapAsync("TsconfigPathsPlugin", (request, resolveContext, callback) => { + this._getTsconfigPathsMap( + resolver, + request, + resolveContext, + (err, tsconfigPathsMap) => { + if (err) return callback(err); + if (!tsconfigPathsMap) return callback(); + + const selectedData = this._selectPathsDataForContext( + request.path, + tsconfigPathsMap, + ); + + if (!selectedData) return callback(); + + aliasResolveHandler( + resolver, + selectedData.alias, + aliasTarget, + request, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + // https://github.com/webpack/webpack/issues/20944 + // Unlike resolve.alias, tsconfig paths should fall through + // when a pattern matches but the mapped path does not exist + // (matching TypeScript's native resolution behavior). + return callback(); + }, + ); + }, + ); + }); + + resolver + .getHook("raw-module") + .tapAsync("TsconfigPathsPlugin", (request, resolveContext, callback) => { + this._getTsconfigPathsMap( + resolver, + request, + resolveContext, + (err, tsconfigPathsMap) => { + if (err) return callback(err); + if (!tsconfigPathsMap) return callback(); + + const selectedData = this._selectPathsDataForContext( + request.path, + tsconfigPathsMap, + ); + + if (!selectedData) return callback(); + + modulesResolveHandler( + resolver, + selectedData.modules, + moduleTarget, + request, + resolveContext, + callback, + ); + }, + ); + }); + } + + /** + * Get TsconfigPathsMap for the request (with caching) + * @param {Resolver} resolver the resolver + * @param {ResolveRequest} request the request + * @param {ResolveContext} resolveContext the resolve context + * @param {(err: Error | null, result?: TsconfigPathsMap | null) => void} callback the callback + * @returns {void} + */ + _getTsconfigPathsMap(resolver, request, resolveContext, callback) { + if (typeof request.tsconfigPathsMap !== "undefined") { + const cached = request.tsconfigPathsMap; + if (!cached) return callback(null, null); + if (resolveContext.fileDependencies) { + for (const fileDependency of cached.fileDependencies) { + resolveContext.fileDependencies.add(fileDependency); + } + } + return callback(null, cached); + } + + if (this.isAutoConfigFile) { + this._findTsconfigUpward( + resolver, + request.path || process.cwd(), + (err, result) => { + if (err) { + request.tsconfigPathsMap = null; + return callback(err); + } + if (!result) { + request.tsconfigPathsMap = null; + return callback(null, null); + } + const map = /** @type {TsconfigPathsMap} */ (result); + request.tsconfigPathsMap = map; + if (resolveContext.fileDependencies) { + for (const fileDependency of map.fileDependencies) { + resolveContext.fileDependencies.add(fileDependency); + } + } + callback(null, map); + }, + ); + return; + } + + const absTsconfigPath = resolver.join( + request.path || process.cwd(), + this.configFile, + ); + this._loadTsconfigPathsMap(resolver, absTsconfigPath, (err, result) => { + if (err) { + request.tsconfigPathsMap = null; + return callback(err); + } + + const map = /** @type {TsconfigPathsMap} */ (result); + request.tsconfigPathsMap = map; + if (resolveContext.fileDependencies) { + for (const fileDependency of map.fileDependencies) { + resolveContext.fileDependencies.add(fileDependency); + } + } + callback(null, map); + }); + } + + /** + * Walk up from startDir to the filesystem root looking for tsconfig.json. + * Like TypeScript's own `findConfigFile` / `forEachAncestorDirectory`. + * @param {Resolver} resolver the resolver + * @param {string} startDir the directory to start searching from + * @param {(err: Error | null, result?: TsconfigPathsMap | null) => void} callback the callback + * @returns {void} + */ + _findTsconfigUpward(resolver, startDir, callback) { + const { fileSystem } = resolver; + const configFileName = this.configFile; + + /** + * @param {string} dir current directory + */ + const check = (dir) => { + const candidate = resolver.join(dir, configFileName); + fileSystem.stat(candidate, (statErr) => { + if (!statErr) { + // Found — load it + this._loadTsconfigPathsMap(resolver, candidate, (loadErr, result) => { + if (loadErr) return callback(loadErr); + callback(null, result); + }); + return; + } + // Not found — move to parent + const parentDir = resolver.dirname(dir); + if (parentDir === dir) { + // Reached filesystem root, no tsconfig.json found + return callback(null, null); + } + check(parentDir); + }); + }; + + check(startDir); + } + + /** + * Load tsconfig.json and build complete TsconfigPathsMap + * Includes main project paths and all referenced projects + * @param {Resolver} resolver the resolver + * @param {string} absTsconfigPath absolute path to tsconfig.json + * @param {(err: Error | null, result?: TsconfigPathsMap) => void} callback the callback + * @returns {void} + */ + _loadTsconfigPathsMap(resolver, absTsconfigPath, callback) { + /** @type {Set} */ + const fileDependencies = new Set(); + + this._loadTsconfig( + resolver, + absTsconfigPath, + fileDependencies, + undefined, + (err, config) => { + if (err) return callback(err); + + const cfg = /** @type {Tsconfig} */ (config); + const compilerOptions = cfg.compilerOptions || {}; + const mainContext = resolver.dirname(absTsconfigPath); + + const baseUrl = + this.baseUrl !== undefined ? this.baseUrl : compilerOptions.baseUrl; + + const main = tsconfigPathsToResolveOptions( + mainContext, + compilerOptions.paths || {}, + resolver, + baseUrl, + ); + /** @type {{ [baseUrl: string]: TsconfigPathsData }} */ + const refs = {}; + + let referencesToUse = null; + if (this.references === "auto") { + referencesToUse = cfg.references; + } else if (Array.isArray(this.references)) { + referencesToUse = this.references; + } + + if (!Array.isArray(referencesToUse)) { + return callback( + null, + buildTsconfigPathsMap(main, mainContext, refs, fileDependencies), + ); + } + + this._loadTsconfigReferences( + resolver, + mainContext, + referencesToUse, + fileDependencies, + refs, + (refErr) => { + if (refErr) return callback(refErr); + callback( + null, + buildTsconfigPathsMap(main, mainContext, refs, fileDependencies), + ); + }, + ); + }, + ); + } + + /** + * Select the correct TsconfigPathsData based on request.path (context-aware) + * Matches the behavior of tsconfig-paths-webpack-plugin + * @param {string | false} requestPath the request path + * @param {TsconfigPathsMap} tsconfigPathsMap the tsconfig paths map + * @returns {TsconfigPathsData | null} the selected paths data + */ + _selectPathsDataForContext(requestPath, tsconfigPathsMap) { + const { main, allContexts, contextList } = tsconfigPathsMap; + if (!requestPath) { + return main; + } + // Single-context tsconfigs (no project references) hit the loop + // below at most once; in that case the cache lookup costs more + // than the loop itself. Only memoize when there are 2+ contexts + // — that's the monorepo / project-references shape where the + // scan actually walks multiple entries per resolve and the + // `(map, requestPath)` answer can be reused. + /** @type {Map | undefined} */ + let perMap; + if (contextList.length >= 2) { + perMap = _contextSelectionCache.get(tsconfigPathsMap); + if (perMap !== undefined) { + const cached = perMap.get(requestPath); + if (cached !== undefined) { + return cached === NULL_CONTEXT + ? null + : /** @type {TsconfigPathsData} */ (cached); + } + } else { + perMap = new Map(); + _contextSelectionCache.set(tsconfigPathsMap, perMap); + } + } + let longestMatchContext = null; + let longestMatchLength = 0; + // Iterate the pre-computed key list (the previous + // `Object.entries(allContexts)` form allocated a fresh + // `[key, value][]` per resolve). Defer the `allContexts[context]` + // lookup to after we know the context actually matches — non-matches + // are the common case and don't need the property access. + for (let i = 0; i < contextList.length; i++) { + const context = contextList[i]; + if (context === requestPath) { + const exact = allContexts[context]; + if (perMap !== undefined) perMap.set(requestPath, exact); + return exact; + } + // Cheap integer-compare gate first: a context can only beat the + // current longest match if its own length is strictly greater. + // Skipping `isSubPath` (a `startsWith` + char-code probe) when the + // length already disqualifies the candidate avoids the per-resolve + // scan over every shorter context. + if ( + context.length > longestMatchLength && + isSubPath(context, requestPath) + ) { + longestMatchContext = context; + longestMatchLength = context.length; + } + } + const result = + longestMatchContext === null ? null : allContexts[longestMatchContext]; + if (perMap !== undefined) { + perMap.set(requestPath, result === null ? NULL_CONTEXT : result); + } + return result; + } + + /** + * Load tsconfig from extends path + * @param {Resolver} resolver the resolver + * @param {string} configFilePath current config file path + * @param {string} extendedConfigValue extends value + * @param {Set} fileDependencies the file dependencies + * @param {Set} visitedConfigPaths config paths being loaded (for circular extends detection) + * @param {(err: Error | null, result?: Tsconfig) => void} callback callback + * @returns {void} + */ + _loadTsconfigFromExtends( + resolver, + configFilePath, + extendedConfigValue, + fileDependencies, + visitedConfigPaths, + callback, + ) { + const { fileSystem } = resolver; + const currentDir = resolver.dirname(configFilePath); + + // Substitute ${configDir} in extends path + extendedConfigValue = substituteConfigDir(extendedConfigValue, currentDir); + + // Remember the original value before potentially appending .json + const originalExtendedConfigValue = extendedConfigValue; + + if ( + typeof extendedConfigValue === "string" && + !extendedConfigValue.includes(".json") + ) { + extendedConfigValue += ".json"; + } + + const initialExtendedConfigPath = resolver.join( + currentDir, + extendedConfigValue, + ); + + fileSystem.stat(initialExtendedConfigPath, (existsErr) => { + let extendedConfigPath = initialExtendedConfigPath; + if (existsErr) { + // Handle scoped package extends like "@scope/name" (no sub-path): + // "@scope/name" should resolve to node_modules/@scope/name/tsconfig.json, + // not node_modules/@scope/name.json + // See: test/fixtures/tsconfig-paths/extends-pkg-entry/ + if ( + typeof originalExtendedConfigValue === "string" && + originalExtendedConfigValue.startsWith("@") && + originalExtendedConfigValue.split("/").length === 2 + ) { + extendedConfigPath = resolver.join( + currentDir, + normalize( + `node_modules/${originalExtendedConfigValue}/${DEFAULT_CONFIG_FILE}`, + ), + ); + } else if (extendedConfigValue.includes("/")) { + // Handle package sub-path extends like "react/tsconfig": + // "react/tsconfig" resolves to node_modules/react/tsconfig.json + // See: test/fixtures/tsconfig-paths/extends-npm/ + extendedConfigPath = resolver.join( + currentDir, + normalize(`node_modules/${extendedConfigValue}`), + ); + } else if ( + !originalExtendedConfigValue.startsWith(".") && + !originalExtendedConfigValue.startsWith("/") + ) { + // Handle unscoped package extends like "my-base-config" (no sub-path): + // "my-base-config" should resolve to node_modules/my-base-config/tsconfig.json + extendedConfigPath = resolver.join( + currentDir, + normalize( + `node_modules/${originalExtendedConfigValue}/${DEFAULT_CONFIG_FILE}`, + ), + ); + } + } + + this._loadTsconfig( + resolver, + extendedConfigPath, + fileDependencies, + visitedConfigPaths, + (err, config) => { + if (err) return callback(err); + + const cfg = /** @type {Tsconfig} */ (config); + const compilerOptions = cfg.compilerOptions || { + baseUrl: undefined, + }; + + if (compilerOptions.baseUrl) { + const extendedConfigDir = resolver.dirname(extendedConfigPath); + compilerOptions.baseUrl = getAbsoluteBaseUrl( + extendedConfigDir, + resolver, + compilerOptions.baseUrl, + ); + } + + delete cfg.references; + + callback(null, cfg); + }, + ); + }); + } + + /** + * Load referenced tsconfig projects and store in referenceMatchMap + * Simple implementation matching tsconfig-paths-webpack-plugin: + * Just load each reference and store independently + * @param {Resolver} resolver the resolver + * @param {string} context the context + * @param {TsconfigReference[]} references array of references + * @param {Set} fileDependencies the file dependencies + * @param {{ [baseUrl: string]: TsconfigPathsData }} referenceMatchMap the map to populate + * @param {(err: Error | null) => void} callback callback + * @param {Set=} visitedRefPaths visited reference config paths (for circular reference detection) + * @returns {void} + */ + _loadTsconfigReferences( + resolver, + context, + references, + fileDependencies, + referenceMatchMap, + callback, + visitedRefPaths, + ) { + if (references.length === 0) return callback(null); + + const visited = visitedRefPaths || new Set(); + let pending = references.length; + const finishOne = () => { + if (--pending === 0) callback(null); + }; + + for (const ref of references) { + const refPath = substituteConfigDir(ref.path, context); + const refConfigPath = resolver.join( + resolver.join(context, refPath), + DEFAULT_CONFIG_FILE, + ); + + if (visited.has(refConfigPath)) { + finishOne(); + continue; + } + visited.add(refConfigPath); + + this._loadTsconfig( + resolver, + refConfigPath, + fileDependencies, + undefined, + (err, refConfig) => { + // Failures are swallowed to match tsconfig-paths-webpack-plugin: + // a broken reference must not abort the main project's resolution. + if (err) return finishOne(); + + const cfg = /** @type {Tsconfig} */ (refConfig); + if (cfg.compilerOptions && cfg.compilerOptions.paths) { + const refContext = resolver.dirname(refConfigPath); + + referenceMatchMap[refContext] = tsconfigPathsToResolveOptions( + refContext, + cfg.compilerOptions.paths || {}, + resolver, + cfg.compilerOptions.baseUrl, + ); + } + + if (this.references === "auto" && Array.isArray(cfg.references)) { + this._loadTsconfigReferences( + resolver, + resolver.dirname(refConfigPath), + cfg.references, + fileDependencies, + referenceMatchMap, + finishOne, + visited, + ); + } else { + finishOne(); + } + }, + ); + } + } + + /** + * Load tsconfig.json with extends support + * @param {Resolver} resolver the resolver + * @param {string} configFilePath absolute path to tsconfig.json + * @param {Set} fileDependencies the file dependencies + * @param {Set | undefined} visitedConfigPaths config paths being loaded (for circular extends detection) + * @param {(err: Error | null, result?: Tsconfig) => void} callback callback + * @returns {void} + */ + _loadTsconfig( + resolver, + configFilePath, + fileDependencies, + visitedConfigPaths, + callback, + ) { + const visited = visitedConfigPaths || new Set(); + + if (visited.has(configFilePath)) { + return callback(null, /** @type {Tsconfig} */ ({})); + } + visited.add(configFilePath); + + readJson( + resolver.fileSystem, + configFilePath, + READ_JSON_OPTIONS, + (err, parsed) => { + if (err) return callback(/** @type {Error} */ (err)); + + const config = /** @type {Tsconfig} */ (parsed); + fileDependencies.add(configFilePath); + + const extendedConfig = config.extends; + if (!extendedConfig) return callback(null, config); + + if (!Array.isArray(extendedConfig)) { + this._loadTsconfigFromExtends( + resolver, + configFilePath, + extendedConfig, + fileDependencies, + visited, + (extErr, extendedTsconfig) => { + if (extErr) return callback(extErr); + callback( + null, + mergeTsconfigs( + /** @type {Tsconfig} */ (extendedTsconfig), + config, + ), + ); + }, + ); + return; + } + + /** @type {Tsconfig} */ + let base = {}; + let i = 0; + const next = () => { + if (i >= extendedConfig.length) { + return callback(null, mergeTsconfigs(base, config)); + } + this._loadTsconfigFromExtends( + resolver, + configFilePath, + extendedConfig[i++], + fileDependencies, + visited, + (extErr, extendedTsconfig) => { + if (extErr) return callback(extErr); + base = mergeTsconfigs( + base, + /** @type {Tsconfig} */ (extendedTsconfig), + ); + next(); + }, + ); + }; + next(); + }, + ); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js b/client/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js new file mode 100644 index 0000000..d661c1c --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js @@ -0,0 +1,200 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { isRelativeRequest } = require("./util/path"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./Resolver").ResolveContextYield} ResolveContextYield */ +/** @typedef {{ [k: string]: undefined | ResolveRequest | ResolveRequest[] }} Cache */ + +/** + * @param {string} relativePath relative path from package root + * @param {string} request relative request + * @param {Resolver} resolver resolver instance + * @returns {string} normalized request with a preserved leading dot + */ +function joinRelativePreservingLeadingDot(relativePath, request, resolver) { + const normalized = resolver.join(relativePath, request); + return isRelativeRequest(normalized) ? normalized : `./${normalized}`; +} + +/** + * @param {ResolveRequest} request request + * @returns {string | false | undefined} normalized path + */ +function getCachePath(request) { + if (request.descriptionFileRoot && !request.module) { + return request.descriptionFileRoot; + } + return request.path; +} + +/** + * @param {ResolveRequest} request request + * @param {Resolver} resolver resolver instance + * @returns {string | undefined} normalized request string + */ +function getCacheRequest(request, resolver) { + const requestString = request.request; + if ( + !requestString || + !request.relativePath || + !isRelativeRequest(requestString) + ) { + return requestString; + } + return joinRelativePreservingLeadingDot( + request.relativePath, + requestString, + resolver, + ); +} + +// Cache-key separator: `\0` is safe because paths, requests, queries and +// fragments produced by `parseIdentifier` never contain a raw NUL (the +// \0-escape in identifier.js is decoded back to the original char), and the +// context, when included, is passed through `JSON.stringify`, which escapes +// any NUL to \u0000. +// const SEP = "\0"; + +/** + * Build the cache id for a request. Called on every `described-resolve` + * invocation when `unsafeCache` is on, so it's a hot path. + * + * Equivalent in meaning to the previous `JSON.stringify({ ... })` form, but + * ~3–5× faster since we avoid the object allocation and JSON serializer for + * the fields that are already plain strings. + * @param {string} type type of cache + * @param {ResolveRequest} request request + * @param {boolean} withContext cache with context? + * @param {Resolver} resolver resolver instance + * @returns {string} cache id + */ +function getCacheId(type, request, withContext, resolver) { + // TODO use it in the next major release, it is faster + // const contextPart = withContext ? JSON.stringify(request.context) : ""; + // const path = getCachePath(request); + // const cacheRequest = getCacheRequest(request, resolver); + // return ( + // type + + // SEP + + // contextPart + + // SEP + + // (path || "") + + // SEP + + // (request.query || "") + + // SEP + + // (request.fragment || "") + + // SEP + + // (cacheRequest || "") + // ); + + return JSON.stringify({ + type, + context: withContext ? request.context : "", + path: getCachePath(request), + query: request.query, + fragment: request.fragment, + request: getCacheRequest(request, resolver), + }); +} + +module.exports = class UnsafeCachePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {(request: ResolveRequest) => boolean} filterPredicate filterPredicate + * @param {Cache} cache cache + * @param {boolean} withContext withContext + * @param {string | ResolveStepHook} target target + */ + constructor(source, filterPredicate, cache, withContext, target) { + this.source = source; + this.filterPredicate = filterPredicate; + this.withContext = withContext; + this.cache = cache; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("UnsafeCachePlugin", (request, resolveContext, callback) => { + if (!this.filterPredicate(request)) { + return resolver.doResolve( + target, + request, + null, + resolveContext, + callback, + ); + } + const isYield = typeof resolveContext.yield === "function"; + const cacheId = getCacheId( + isYield ? "yield" : "default", + request, + this.withContext, + resolver, + ); + const cacheEntry = this.cache[cacheId]; + if (cacheEntry) { + if (isYield) { + const yield_ = + /** @type {ResolveContextYield} */ + (resolveContext.yield); + if (Array.isArray(cacheEntry)) { + for (const result of cacheEntry) yield_(result); + } else { + yield_(cacheEntry); + } + return callback(null, null); + } + return callback(null, /** @type {ResolveRequest} */ (cacheEntry)); + } + + /** @type {ResolveContextYield | undefined} */ + let yieldFn; + /** @type {ResolveContextYield | undefined} */ + let yield_; + /** @type {ResolveRequest[]} */ + const yieldResult = []; + if (isYield) { + yieldFn = resolveContext.yield; + yield_ = (result) => { + yieldResult.push(result); + }; + } + + resolver.doResolve( + target, + request, + null, + yield_ ? { ...resolveContext, yield: yield_ } : resolveContext, + (err, result) => { + if (err) return callback(err); + if (isYield) { + if (result) yieldResult.push(result); + for (const result of yieldResult) { + /** @type {ResolveContextYield} */ + (yieldFn)(result); + } + this.cache[cacheId] = yieldResult; + return callback(null, null); + } + if (result) return callback(null, (this.cache[cacheId] = result)); + callback(); + }, + ); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/UseFilePlugin.js b/client/node_modules/enhanced-resolve/lib/UseFilePlugin.js new file mode 100644 index 0000000..f81c27f --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/UseFilePlugin.js @@ -0,0 +1,55 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class UseFilePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} filename filename + * @param {string | ResolveStepHook} target target + */ + constructor(source, filename, target) { + this.source = source; + this.filename = filename; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("UseFilePlugin", (request, resolveContext, callback) => { + const filePath = resolver.join( + /** @type {string} */ (request.path), + this.filename, + ); + + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: filePath, + relativePath: + request.relativePath && + resolver.join(request.relativePath, this.filename), + }; + resolver.doResolve( + target, + obj, + `using path: ${filePath}`, + resolveContext, + callback, + ); + }); + } +}; diff --git a/client/node_modules/enhanced-resolve/lib/createInnerContext.js b/client/node_modules/enhanced-resolve/lib/createInnerContext.js new file mode 100644 index 0000000..226d098 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/createInnerContext.js @@ -0,0 +1,56 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ + +/** + * Build the `ResolveContext` passed into the next hook in the chain. + * + * The caller — `Resolver.doResolve` — runs on every resolve step, so we + * want to allocate as little as possible here. Previously the caller + * constructed a temporary `{ log, yield, fileDependencies, ... }` literal + * and handed it to this helper, which then copied those same fields into + * a second fresh object. That's two allocations per step for what is + * effectively a struct copy with one mutated field (`stack`) and one + * optionally-wrapped field (`log`). Taking the parent context and the + * two things we actually want to change (stack, message) as separate + * arguments lets us allocate exactly one inner context. + * @param {ResolveContext} parent parent resolve context to inherit dependency sets / yield from + * @param {ResolveContext["stack"]} stack new stack tip for the nested call + * @param {null | string} message log message prefix for this step + * @returns {ResolveContext} inner context + */ +module.exports = function createInnerContext(parent, stack, message) { + const parentLog = parent.log; + let innerLog; + if (parentLog) { + if (message) { + let messageReported = false; + /** + * @param {string} msg message + */ + innerLog = (msg) => { + if (!messageReported) { + parentLog(message); + messageReported = true; + } + parentLog(` ${msg}`); + }; + } else { + innerLog = parentLog; + } + } + + return { + log: innerLog, + yield: parent.yield, + fileDependencies: parent.fileDependencies, + contextDependencies: parent.contextDependencies, + missingDependencies: parent.missingDependencies, + stack, + }; +}; diff --git a/client/node_modules/enhanced-resolve/lib/forEachBail.js b/client/node_modules/enhanced-resolve/lib/forEachBail.js new file mode 100644 index 0000000..ec02184 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/forEachBail.js @@ -0,0 +1,50 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ + +/** + * @template T + * @template Z + * @callback Iterator + * @param {T} item item + * @param {(err?: null | Error, result?: null | Z) => void} callback callback + * @param {number} i index + * @returns {void} + */ + +/** + * @template T + * @template Z + * @param {T[]} array array + * @param {Iterator} iterator iterator + * @param {(err?: null | Error, result?: null | Z, i?: number) => void} callback callback after all items are iterated + * @returns {void} + */ +module.exports = function forEachBail(array, iterator, callback) { + if (array.length === 0) return callback(); + + let i = 0; + const next = () => { + /** @type {boolean | undefined} */ + let loop; + iterator( + array[i++], + (err, result) => { + if (err || result !== undefined || i >= array.length) { + return callback(err, result, i); + } + if (loop === false) while (next()); + loop = true; + }, + i, + ); + if (!loop) loop = false; + return loop; + }; + while (next()); +}; diff --git a/client/node_modules/enhanced-resolve/lib/getInnerRequest.js b/client/node_modules/enhanced-resolve/lib/getInnerRequest.js new file mode 100644 index 0000000..affa6c4 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/getInnerRequest.js @@ -0,0 +1,41 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { isRelativeRequest } = require("./util/path"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ + +/** + * @param {Resolver} resolver resolver + * @param {ResolveRequest} request string + * @returns {string} inner request + */ +module.exports = function getInnerRequest(resolver, request) { + if ( + typeof request.__innerRequest === "string" && + request.__innerRequest_request === request.request && + request.__innerRequest_relativePath === request.relativePath + ) { + return request.__innerRequest; + } + /** @type {string | undefined} */ + let innerRequest; + if (request.request) { + innerRequest = request.request; + if (request.relativePath && isRelativeRequest(innerRequest)) { + innerRequest = resolver.join(request.relativePath, innerRequest); + } + } else { + innerRequest = request.relativePath; + } + // eslint-disable-next-line camelcase + request.__innerRequest_request = request.request; + // eslint-disable-next-line camelcase + request.__innerRequest_relativePath = request.relativePath; + return (request.__innerRequest = /** @type {string} */ (innerRequest)); +}; diff --git a/client/node_modules/enhanced-resolve/lib/getPaths.js b/client/node_modules/enhanced-resolve/lib/getPaths.js new file mode 100644 index 0000000..3f1b9a3 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/getPaths.js @@ -0,0 +1,82 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {{ paths: string[], segments: string[] }} GetPathsResult */ + +/** + * Walk `path` from tip to root, returning every ancestor directory (plus the + * input itself) in `paths`, and each corresponding segment name in `segments`. + * + * The return value may be shared across callers via `getPathsCached` — treat + * it as read-only. Callers that need to mutate (currently only + * `SymlinkPlugin`) should `slice()` the arrays locally before writing. + * @param {string} path path + * @returns {GetPathsResult} paths and segments + */ +function getPaths(path) { + if (path === "/") return { paths: ["/"], segments: [""] }; + const parts = path.split(/(.*?[\\/]+)/); + const paths = [path]; + const segments = [parts[parts.length - 1]]; + let part = parts[parts.length - 1]; + path = path.slice(0, Math.max(0, path.length - part.length - 1)); + for (let i = parts.length - 2; i > 2; i -= 2) { + paths.push(path); + part = parts[i]; + path = path.slice(0, Math.max(0, path.length - part.length)) || "/"; + segments.push(part.slice(0, -1)); + } + [, part] = parts; + segments.push(part); + paths.push(part); + return { + paths, + segments, + }; +} + +/** + * Per-filesystem memoization of `getPaths`. Kept in a standalone WeakMap + * rather than being hung off `resolver.pathCache` so that adding this cache + * does not change the hidden-class shape of `pathCache` — which is accessed + * on the hot path of every resolve as `resolver.pathCache.{join,dirname, + * basename}.fn(...)`. CodSpeed caught that shape change as a ~1–2% + * instruction-count regression on `cache-predicate`, so we keep pathCache + * shape-stable by owning this cache here instead. + * + * The cache lifetime is tied to the filesystem object (same invariant as + * `_pathCacheByFs` in `Resolver.js`): when the user swaps filesystems the + * entries become unreachable and get collected. + * @type {WeakMap>} + */ +const _getPathsCacheByFs = new WeakMap(); + +/** + * Memoized `getPaths`. The returned object is shared across callers — do + * not mutate the `paths` or `segments` arrays in-place; `slice()` first if + * you need a mutable copy. + * @param {FileSystem} fileSystem filesystem used as the cache namespace + * @param {string} path path + * @returns {GetPathsResult} paths and segments + */ +function getPathsCached(fileSystem, path) { + let cache = _getPathsCacheByFs.get(fileSystem); + if (cache === undefined) { + cache = new Map(); + _getPathsCacheByFs.set(fileSystem, cache); + } else { + const cached = cache.get(path); + if (cached !== undefined) return cached; + } + const result = getPaths(path); + cache.set(path, result); + return result; +} + +module.exports = getPaths; +module.exports.getPathsCached = getPathsCached; diff --git a/client/node_modules/enhanced-resolve/lib/index.js b/client/node_modules/enhanced-resolve/lib/index.js new file mode 100644 index 0000000..2efaf29 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/index.js @@ -0,0 +1,310 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const memoize = require("./util/memoize"); + +/** @typedef {import("./CachedInputFileSystem").BaseFileSystem} BaseFileSystem */ +/** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */ +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").Context} Context */ +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").ResolveCallback} ResolveCallback */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ +/** @typedef {import("./ResolverFactory").Plugin} Plugin */ +/** @typedef {import("./ResolverFactory").UserResolveOptions} ResolveOptions */ + +/** + * @typedef {{ + * (context: Context, path: string, request: string, resolveContext: ResolveContext, callback: ResolveCallback): void, + * (context: Context, path: string, request: string, callback: ResolveCallback): void, + * (path: string, request: string, resolveContext: ResolveContext, callback: ResolveCallback): void, + * (path: string, request: string, callback: ResolveCallback): void, + * }} ResolveFunctionAsync + */ + +/** + * @typedef {{ + * (context: Context, path: string, request: string, resolveContext?: ResolveContext): string | false, + * (path: string, request: string, resolveContext?: ResolveContext): string | false, + * }} ResolveFunction + */ + +/** + * @typedef {{ + * (context: Context, path: string, request: string, resolveContext?: ResolveContext): Promise, + * (path: string, request: string, resolveContext?: ResolveContext): Promise, + * }} ResolveFunctionPromise + */ + +const getCachedFileSystem = memoize(() => require("./CachedInputFileSystem")); + +const getNodeFileSystem = memoize(() => { + const fs = require("graceful-fs"); + + const CachedInputFileSystem = getCachedFileSystem(); + + return new CachedInputFileSystem(fs, 4000); +}); +const getNodeContext = memoize(() => ({ + environments: ["node+es3+es5+process+native"], +})); + +const getResolverFactory = memoize(() => require("./ResolverFactory")); + +const getAsyncResolver = memoize(() => + getResolverFactory().createResolver({ + conditionNames: ["node"], + extensions: [".js", ".json", ".node"], + fileSystem: getNodeFileSystem(), + }), +); + +/** + * @type {ResolveFunctionAsync} + */ +const resolve = + /** + * @param {object | string} context context + * @param {string} path path + * @param {string | ResolveContext | ResolveCallback} request request + * @param {ResolveContext | ResolveCallback=} resolveContext resolve context + * @param {ResolveCallback=} callback callback + */ + (context, path, request, resolveContext, callback) => { + if (typeof context === "string") { + callback = /** @type {ResolveCallback} */ (resolveContext); + resolveContext = /** @type {ResolveContext} */ (request); + request = path; + path = context; + context = getNodeContext(); + } + if (typeof callback !== "function") { + callback = /** @type {ResolveCallback} */ (resolveContext); + } + getAsyncResolver().resolve( + context, + path, + /** @type {string} */ (request), + /** @type {ResolveContext} */ (resolveContext), + /** @type {ResolveCallback} */ (callback), + ); + }; + +const getSyncResolver = memoize(() => + getResolverFactory().createResolver({ + conditionNames: ["node"], + extensions: [".js", ".json", ".node"], + useSyncFileSystemCalls: true, + fileSystem: getNodeFileSystem(), + }), +); + +/** + * @type {ResolveFunction} + */ +const resolveSync = + /** + * @param {object | string} context context + * @param {string} path path + * @param {string | ResolveContext | undefined} request request + * @param {ResolveContext=} resolveContext resolve context + * @returns {string | false} resolved path + */ + (context, path, request, resolveContext) => { + if (typeof context === "string") { + resolveContext = /** @type {ResolveContext} */ (request); + request = path; + path = context; + context = getNodeContext(); + } + return getSyncResolver().resolveSync( + context, + path, + /** @type {string} */ (request), + /** @type {ResolveContext} */ (resolveContext), + ); + }; + +/** + * @type {ResolveFunctionPromise} + */ +const resolvePromise = + /** + * @param {object | string} context context + * @param {string} path path + * @param {string | ResolveContext | undefined} request request + * @param {ResolveContext=} resolveContext resolve context + * @returns {Promise} resolved path + */ + (context, path, request, resolveContext) => { + if (typeof context === "string") { + resolveContext = /** @type {ResolveContext} */ (request); + request = path; + path = context; + context = getNodeContext(); + } + return getAsyncResolver().resolvePromise( + context, + path, + /** @type {string} */ (request), + /** @type {ResolveContext} */ (resolveContext), + ); + }; + +/** @typedef {Omit & Partial>} ResolveOptionsOptionalFS */ + +/** + * @param {ResolveOptionsOptionalFS} options Resolver options + * @returns {ResolveFunctionAsync} Resolver function + */ +function create(options) { + const resolver = getResolverFactory().createResolver({ + fileSystem: getNodeFileSystem(), + ...options, + }); + /** + * @param {object | string} context Custom context + * @param {string} path Base path + * @param {string | ResolveContext | ResolveCallback} request String to resolve + * @param {ResolveContext | ResolveCallback=} resolveContext Resolve context + * @param {ResolveCallback=} callback Result callback + */ + return function create(context, path, request, resolveContext, callback) { + if (typeof context === "string") { + callback = /** @type {ResolveCallback} */ (resolveContext); + resolveContext = /** @type {ResolveContext} */ (request); + request = path; + path = context; + context = getNodeContext(); + } + if (typeof callback !== "function") { + callback = /** @type {ResolveCallback} */ (resolveContext); + } + resolver.resolve( + context, + path, + /** @type {string} */ (request), + /** @type {ResolveContext} */ (resolveContext), + callback, + ); + }; +} + +/** + * @param {ResolveOptionsOptionalFS} options Resolver options + * @returns {ResolveFunction} Resolver function + */ +function createSync(options) { + const resolver = getResolverFactory().createResolver({ + useSyncFileSystemCalls: true, + fileSystem: getNodeFileSystem(), + ...options, + }); + /** + * @param {object | string} context custom context + * @param {string} path base path + * @param {string | ResolveContext | undefined} request request to resolve + * @param {ResolveContext=} resolveContext Resolve context + * @returns {string | false} Resolved path or false + */ + return function createSync(context, path, request, resolveContext) { + if (typeof context === "string") { + resolveContext = /** @type {ResolveContext} */ (request); + request = path; + path = context; + context = getNodeContext(); + } + return resolver.resolveSync( + context, + path, + /** @type {string} */ (request), + /** @type {ResolveContext} */ (resolveContext), + ); + }; +} + +/** + * @param {ResolveOptionsOptionalFS} options Resolver options + * @returns {ResolveFunctionPromise} Resolver function + */ +function createPromise(options) { + const resolver = getResolverFactory().createResolver({ + fileSystem: getNodeFileSystem(), + ...options, + }); + /** + * @param {object | string} context Custom context + * @param {string} path Base path + * @param {string | ResolveContext | undefined} request String to resolve + * @param {ResolveContext=} resolveContext Resolve context + * @returns {Promise} resolved path + */ + return function createPromise(context, path, request, resolveContext) { + if (typeof context === "string") { + resolveContext = /** @type {ResolveContext} */ (request); + request = path; + path = context; + context = getNodeContext(); + } + return resolver.resolvePromise( + context, + path, + /** @type {string} */ (request), + /** @type {ResolveContext} */ (resolveContext), + ); + }; +} + +/** + * @template A + * @template B + * @param {A} obj input a + * @param {B} exports input b + * @returns {A & B} merged + */ +const mergeExports = (obj, exports) => { + const descriptors = Object.getOwnPropertyDescriptors(exports); + Object.defineProperties(obj, descriptors); + return /** @type {A & B} */ (Object.freeze(obj)); +}; + +module.exports = mergeExports(resolve, { + get sync() { + return resolveSync; + }, + get promise() { + return resolvePromise; + }, + create: mergeExports(create, { + get sync() { + return createSync; + }, + get promise() { + return createPromise; + }, + }), + get ResolverFactory() { + return getResolverFactory(); + }, + get CachedInputFileSystem() { + return getCachedFileSystem(); + }, + get CloneBasenamePlugin() { + return require("./CloneBasenamePlugin"); + }, + get LogInfoPlugin() { + return require("./LogInfoPlugin"); + }, + get TsconfigPathsPlugin() { + return require("./TsconfigPathsPlugin"); + }, + get forEachBail() { + return require("./forEachBail"); + }, +}); diff --git a/client/node_modules/enhanced-resolve/lib/util/entrypoints.js b/client/node_modules/enhanced-resolve/lib/util/entrypoints.js new file mode 100644 index 0000000..7a873db --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/util/entrypoints.js @@ -0,0 +1,745 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const { parseIdentifier } = require("./identifier"); + +/** @typedef {string | (string | ConditionalMapping)[]} DirectMapping */ +/** @typedef {{ [k: string]: MappingValue }} ConditionalMapping */ +/** @typedef {ConditionalMapping | DirectMapping | null} MappingValue */ +/** @typedef {Record | ConditionalMapping | DirectMapping} ExportsField */ +/** @typedef {Record} ImportsField */ + +/** + * Processing exports/imports field + * @callback FieldProcessor + * @param {string} request request + * @param {Set} conditionNames condition names + * @returns {[string[], string | null]} resolved paths with used field + */ + +/* +Example exports field: +{ + ".": "./main.js", + "./feature": { + "browser": "./feature-browser.js", + "default": "./feature.js" + } +} +Terminology: + +Enhanced-resolve name keys ("." and "./feature") as exports field keys. + +If value is string or string[], mapping is called as a direct mapping +and value called as a direct export. + +If value is key-value object, mapping is called as a conditional mapping +and value called as a conditional export. + +Key in conditional mapping is called condition name. + +Conditional mapping nested in another conditional mapping is called nested mapping. + +---------- + +Example imports field: +{ + "#a": "./main.js", + "#moment": { + "browser": "./moment/index.js", + "default": "moment" + }, + "#moment/": { + "browser": "./moment/", + "default": "moment/" + } +} +Terminology: + +Enhanced-resolve name keys ("#a" and "#moment/", "#moment") as imports field keys. + +If value is string or string[], mapping is called as a direct mapping +and value called as a direct export. + +If value is key-value object, mapping is called as a conditional mapping +and value called as a conditional export. + +Key in conditional mapping is called condition name. + +Conditional mapping nested in another conditional mapping is called nested mapping. + +*/ + +const slashCode = "/".charCodeAt(0); +const dotCode = ".".charCodeAt(0); +const hashCode = "#".charCodeAt(0); +const patternRegEx = /\*/g; +const DOLLAR_ESCAPE_RE = /\$/g; + +/** @typedef {Record} RecordMapping */ + +/** + * Cached `Object.keys()` for objects whose shape does not change after the + * first observation — i.e. parsed `package.json` fields and the nested + * conditional mappings inside them. `Object.keys` allocates a fresh array + * on every call; since `findMatch` / `conditionalMapping` run on every + * bare-specifier resolve, the allocation adds up quickly. + * @type {WeakMap} + */ +const _keysCache = new WeakMap(); + +/** + * @param {RecordMapping} obj object to read keys from + * @returns {string[]} cached keys array (DO NOT mutate) + */ +function cachedKeys(obj) { + let keys = _keysCache.get(obj); + if (keys === undefined) { + keys = Object.keys(obj); + _keysCache.set(obj, keys); + } + return keys; +} + +/** + * Per-key precomputed info used by `findMatch`. Equivalent to what the + * previous implementation recomputed inline on every resolve. + * @typedef {object} FieldKeyInfo + * @property {string} key the original key + * @property {number} patternIndex position of the single "*" in the key, or -1 when absent + * @property {string} wildcardPrefix substring before "*" (empty when patternIndex === -1) + * @property {string} wildcardSuffix substring after "*" (empty when patternIndex === -1) + * @property {boolean} isLegacySubpath true when key is a legacy `./foo/`-style folder key with no "*" + * @property {boolean} isPattern true when key contains "*" + * @property {boolean} isSubpathMapping true when key ends with "/" + * @property {boolean} isValidPattern true when key has at most one "*" + */ + +/** + * Cached per-field key metadata, keyed by the exports/imports field + * object. Computed lazily on first `findMatch` call and reused forever. + * Safe because `package.json` fields are immutable JSON values. + * @type {WeakMap} + */ +const _fieldKeyInfoCache = new WeakMap(); + +/** + * @param {ExportsField | ImportsField} field field object + * @returns {FieldKeyInfo[]} precomputed per-key info + */ +function getFieldKeyInfos(field) { + const fieldKey = /** @type {RecordMapping} */ (field); + let infos = _fieldKeyInfoCache.get(fieldKey); + if (infos !== undefined) return infos; + const keys = Object.getOwnPropertyNames(field); + infos = Array.from({ length: keys.length }); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const patternIndex = key.indexOf("*"); + // `isValidPattern` is true when the key has at most one `*`. Searching + // from `patternIndex + 1` stops as soon as a second `*` is found, so + // we avoid the full-string scan that `lastIndexOf` would do — and the + // single-star common case finishes in one pass. + const isValidPattern = + patternIndex === -1 || !key.includes("*", patternIndex + 1); + const keyLen = key.length; + const endsWithSlash = + keyLen > 0 && key.charCodeAt(keyLen - 1) === slashCode; + infos[i] = { + key, + patternIndex, + wildcardPrefix: patternIndex === -1 ? "" : key.slice(0, patternIndex), + wildcardSuffix: patternIndex === -1 ? "" : key.slice(patternIndex + 1), + isLegacySubpath: patternIndex === -1 && endsWithSlash, + isPattern: patternIndex !== -1, + isSubpathMapping: endsWithSlash, + isValidPattern, + }; + } + _fieldKeyInfoCache.set(fieldKey, infos); + return infos; +} + +/** + * @param {string} a first string + * @param {string} b second string + * @returns {number} compare result + */ +function patternKeyCompare(a, b) { + const aPatternIndex = a.indexOf("*"); + const bPatternIndex = b.indexOf("*"); + const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; + const baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; + + if (baseLenA > baseLenB) return -1; + if (baseLenB > baseLenA) return 1; + if (aPatternIndex === -1) return 1; + if (bPatternIndex === -1) return -1; + if (a.length > b.length) return -1; + if (b.length > a.length) return 1; + + return 0; +} + +/** @typedef {[MappingValue, string, boolean, boolean, string] | null} MatchTuple */ + +/** + * Per-field memoization of `findMatch(request, field)`. For a given field + * the result depends only on the `request` string (it does NOT depend on + * `conditionNames` — that's applied separately by `conditionalMapping`), + * so we can cache the tuple keyed by request. + * + * Typical build traffic runs the same request through the resolver + * repeatedly (same import re-resolved from different source files, module + * graph traversals that revisit a package, etc.), and every one of those + * hits walks the same key list and allocates the same tuple. Caching the + * tuple turns the second-and-onward call into a single Map lookup. + * + * Keyed on the field object via a module-level `WeakMap`, so the cache + * is freed automatically when the owning description file is GC'd. + * @type {WeakMap>} + */ +const _findMatchCache = new WeakMap(); + +/** + * @param {string} request request + * @param {ExportsField | ImportsField} field exports or import field + * @returns {MatchTuple} match result (uncached) + */ +function computeFindMatch(request, field) { + const requestLen = request.length; + const requestEndsWithSlash = + requestLen > 0 && request.charCodeAt(requestLen - 1) === slashCode; + const requestHasStar = request.includes("*"); + + if ( + !requestHasStar && + !requestEndsWithSlash && + Object.prototype.hasOwnProperty.call(field, request) + ) { + const target = /** @type {{ [k: string]: MappingValue }} */ (field)[ + request + ]; + + return [target, "", false, false, request]; + } + + /** @type {string} */ + let bestMatch = ""; + /** @type {FieldKeyInfo | null} */ + let bestMatchInfo = null; + /** @type {string | undefined} */ + let bestMatchSubpath; + + const infos = getFieldKeyInfos(field); + + for (let i = 0; i < infos.length; i++) { + const info = infos[i]; + const { key, patternIndex } = info; + + if (patternIndex !== -1) { + if ( + !info.isValidPattern || + !request.startsWith(info.wildcardPrefix) || + requestLen < key.length || + !request.endsWith(info.wildcardSuffix) || + patternKeyCompare(bestMatch, key) !== 1 + ) { + continue; + } + bestMatch = key; + bestMatchInfo = info; + bestMatchSubpath = request.slice( + patternIndex, + requestLen - info.wildcardSuffix.length, + ); + } else if ( + info.isLegacySubpath && + request.startsWith(key) && + patternKeyCompare(bestMatch, key) === 1 + ) { + bestMatch = key; + bestMatchInfo = info; + bestMatchSubpath = request.slice(key.length); + } + } + + if (bestMatch === "") return null; + + const target = + /** @type {{ [k: string]: MappingValue }} */ + (field)[bestMatch]; + + return [ + target, + /** @type {string} */ (bestMatchSubpath), + /** @type {FieldKeyInfo} */ (bestMatchInfo).isSubpathMapping, + /** @type {FieldKeyInfo} */ (bestMatchInfo).isPattern, + bestMatch, + ]; +} + +/** + * Trying to match request to field + * @param {string} request request + * @param {ExportsField | ImportsField} field exports or import field + * @returns {MatchTuple} match or null, number is negative and one less when it's a folder mapping, number is request.length + 1 for direct mappings + */ +function findMatch(request, field) { + const fieldKey = /** @type {RecordMapping} */ (field); + let perRequest = _findMatchCache.get(fieldKey); + if (perRequest === undefined) { + perRequest = new Map(); + _findMatchCache.set(fieldKey, perRequest); + } else { + // `computeFindMatch` only ever returns `MatchTuple | null` — never + // `undefined` — and `Map.set(k, null)` then `Map.get(k)` returns + // `null`, not `undefined`. So `get(...) === undefined` already + // unambiguously means "not cached yet"; one Map lookup is enough, + // no follow-up `has` needed to disambiguate "cached null". + const cached = perRequest.get(request); + if (cached !== undefined) return cached; + } + + const result = computeFindMatch(request, field); + perRequest.set(request, result); + return result; +} + +/** + * Sentinel stored in the conditional-mapping cache for inputs whose walk + * returns `null` ("no condition matched"). Using a non-null marker lets the + * cache-hit path be a single `WeakMap.get()` — we distinguish + * "cached null" from "not cached yet" without a second `has` call. + */ +const NULL_RESULT = Symbol("NULL_RESULT"); + +/** + * Memoization of `conditionalMapping(mapping, conditionNames)`. The result + * depends only on the mapping object (immutable — owned by a parsed + * `package.json`) and the `conditionNames` Set (owned by the resolver's + * options and stable for its lifetime), so it is safe to cache per (mapping, + * conditionNames) pair. + * + * A conditional `exports` entry that appears inside a `directMapping` array + * (the common `"browser": [...fallback list...]` shape, plus nested + * conditions) gets walked on every resolve that traverses the parent entry. + * Without this cache each of those walks re-reads `Object.keys` on the + * mapping and re-visits every condition until one matches, even though the + * inputs are identical. + * + * Outer key is the conditional mapping itself; inner key is the condition + * Set. Both are object references, so WeakMap-of-WeakMap lets both levels + * be collected automatically when the description file or resolver go away. + * @type {WeakMap, DirectMapping | typeof NULL_RESULT>>} + */ +const _conditionalMappingCache = new WeakMap(); + +/** + * @param {ConditionalMapping} conditionalMapping_ conditional mapping + * @param {Set} conditionNames condition names + * @returns {DirectMapping | null} direct mapping if found (uncached) + */ +function computeConditionalMapping(conditionalMapping_, conditionNames) { + /** @type {[ConditionalMapping, string[], number][]} */ + const lookup = [[conditionalMapping_, cachedKeys(conditionalMapping_), 0]]; + + loop: while (lookup.length > 0) { + const top = lookup[lookup.length - 1]; + const [mapping, conditions, j] = top; + + for (let i = j; i < conditions.length; i++) { + const condition = conditions[i]; + + if (condition === "default" || conditionNames.has(condition)) { + const innerMapping = mapping[condition]; + if ( + innerMapping !== null && + typeof innerMapping === "object" && + !Array.isArray(innerMapping) + ) { + const nested = /** @type {ConditionalMapping} */ (innerMapping); + top[2] = i + 1; + lookup.push([nested, cachedKeys(nested), 0]); + continue loop; + } + + return /** @type {DirectMapping} */ (innerMapping); + } + } + + lookup.pop(); + } + + return null; +} + +/** + * @param {ConditionalMapping} conditionalMapping_ conditional mapping + * @param {Set} conditionNames condition names + * @returns {DirectMapping | null} direct mapping if found + */ +function conditionalMapping(conditionalMapping_, conditionNames) { + let perSet = _conditionalMappingCache.get(conditionalMapping_); + if (perSet !== undefined) { + const cached = perSet.get(conditionNames); + if (cached !== undefined) { + return cached === NULL_RESULT + ? null + : /** @type {DirectMapping} */ (cached); + } + } else { + perSet = new WeakMap(); + _conditionalMappingCache.set(conditionalMapping_, perSet); + } + const result = computeConditionalMapping(conditionalMapping_, conditionNames); + perSet.set(conditionNames, result === null ? NULL_RESULT : result); + return result; +} + +/** + * @param {string | undefined} remainingRequest remaining request when folder mapping, undefined for file mappings + * @param {boolean} isPattern true, if mapping is a pattern (contains "*") + * @param {boolean} isSubpathMapping true, for subpath mappings + * @param {string} mappingTarget direct export + * @param {(d: string, f: boolean) => void} assert asserting direct value + * @returns {string} mapping result + */ +function targetMapping( + remainingRequest, + isPattern, + isSubpathMapping, + mappingTarget, + assert, +) { + if (remainingRequest === undefined) { + assert(mappingTarget, false); + + return mappingTarget; + } + + if (isSubpathMapping) { + assert(mappingTarget, true); + + return mappingTarget + remainingRequest; + } + + assert(mappingTarget, false); + + let result = mappingTarget; + + if (isPattern) { + const escapedRemainder = remainingRequest.includes("$") + ? remainingRequest.replace(DOLLAR_ESCAPE_RE, "$$") + : remainingRequest; + result = result.replace(patternRegEx, escapedRemainder); + } + + return result; +} + +/** + * @param {string | undefined} remainingRequest remaining request when folder mapping, undefined for file mappings + * @param {boolean} isPattern true, if mapping is a pattern (contains "*") + * @param {boolean} isSubpathMapping true, for subpath mappings + * @param {DirectMapping | null} mappingTarget direct export + * @param {Set} conditionNames condition names + * @param {(d: string, f: boolean) => void} assert asserting direct value + * @returns {string[]} mapping result + */ +function directMapping( + remainingRequest, + isPattern, + isSubpathMapping, + mappingTarget, + conditionNames, + assert, +) { + if (mappingTarget === null) return []; + + if (typeof mappingTarget === "string") { + return [ + targetMapping( + remainingRequest, + isPattern, + isSubpathMapping, + mappingTarget, + assert, + ), + ]; + } + + /** @type {string[]} */ + const targets = []; + + for (let i = 0, len = mappingTarget.length; i < len; i++) { + const exp = mappingTarget[i]; + if (typeof exp === "string") { + targets.push( + targetMapping( + remainingRequest, + isPattern, + isSubpathMapping, + exp, + assert, + ), + ); + continue; + } + + const mapping = conditionalMapping(exp, conditionNames); + if (!mapping) continue; + const innerExports = directMapping( + remainingRequest, + isPattern, + isSubpathMapping, + mapping, + conditionNames, + assert, + ); + for (let j = 0, innerLen = innerExports.length; j < innerLen; j++) { + targets.push(innerExports[j]); + } + } + + return targets; +} + +/** @type {[string[], null]} */ +const EMPTY_NO_MATCH = /** @type {[string[], null]} */ ([[], null]); + +/** + * @param {ExportsField | ImportsField} field root + * @param {(s: string) => string} normalizeRequest Normalize request, for `imports` field it adds `#`, for `exports` field it adds `.` or `./` + * @param {(s: string) => string} assertRequest assertRequest + * @param {(s: string, f: boolean) => void} assertTarget assertTarget + * @returns {FieldProcessor} field processor + */ +function createFieldProcessor( + field, + normalizeRequest, + assertRequest, + assertTarget, +) { + return function fieldProcessor(request, conditionNames) { + const match = findMatch(normalizeRequest(assertRequest(request)), field); + + if (match === null) return EMPTY_NO_MATCH; + + const [mapping, remainingRequest, isSubpathMapping, isPattern, usedField] = + match; + + /** @type {DirectMapping | null} */ + let direct; + if ( + mapping !== null && + typeof mapping === "object" && + !Array.isArray(mapping) + ) { + direct = conditionalMapping( + /** @type {ConditionalMapping} */ (mapping), + conditionNames, + ); + if (direct === null) return EMPTY_NO_MATCH; + } else { + direct = /** @type {DirectMapping} */ (mapping); + } + + return [ + directMapping( + remainingRequest, + isPattern, + isSubpathMapping, + direct, + conditionNames, + assertTarget, + ), + usedField, + ]; + }; +} + +/** + * @param {string} request request + * @returns {string} updated request + */ +function assertExportsFieldRequest(request) { + if (request.charCodeAt(0) !== dotCode) { + throw new Error('Request should be relative path and start with "."'); + } + if (request.length === 1) return ""; + if (request.charCodeAt(1) !== slashCode) { + throw new Error('Request should be relative path and start with "./"'); + } + if (request.charCodeAt(request.length - 1) === slashCode) { + throw new Error("Only requesting file allowed"); + } + + return request.slice(2); +} + +/** + * @param {ExportsField} field exports field + * @returns {ExportsField} normalized exports field + */ +function buildExportsField(field) { + // handle syntax sugar, if exports field is direct mapping for "." + if (typeof field === "string" || Array.isArray(field)) { + return { ".": field }; + } + + const keys = Object.keys(field); + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + + if (key.charCodeAt(0) !== dotCode) { + // handle syntax sugar, if exports field is conditional mapping for "." + if (i === 0) { + while (i < keys.length) { + const charCode = keys[i].charCodeAt(0); + if (charCode === dotCode || charCode === slashCode) { + throw new Error( + `Exports field key should be relative path and start with "." (key: ${JSON.stringify( + key, + )})`, + ); + } + i++; + } + + return { ".": field }; + } + + throw new Error( + `Exports field key should be relative path and start with "." (key: ${JSON.stringify( + key, + )})`, + ); + } + + if (key.length === 1) { + continue; + } + + if (key.charCodeAt(1) !== slashCode) { + throw new Error( + `Exports field key should be relative path and start with "./" (key: ${JSON.stringify( + key, + )})`, + ); + } + } + + return field; +} + +/** + * @param {string} exp export target + * @param {boolean} expectFolder is folder expected + */ +function assertExportTarget(exp, expectFolder) { + const parsedIdentifier = parseIdentifier(exp); + + if (!parsedIdentifier) { + return; + } + + const [relativePath] = parsedIdentifier; + const isFolder = + relativePath.charCodeAt(relativePath.length - 1) === slashCode; + + if (isFolder !== expectFolder) { + throw new Error( + expectFolder + ? `Expecting folder to folder mapping. ${JSON.stringify( + exp, + )} should end with "/"` + : `Expecting file to file mapping. ${JSON.stringify( + exp, + )} should not end with "/"`, + ); + } +} + +/** + * @param {ExportsField} exportsField the exports field + * @returns {FieldProcessor} process callback + */ +module.exports.processExportsField = function processExportsField( + exportsField, +) { + return createFieldProcessor( + buildExportsField(exportsField), + (request) => (request.length === 0 ? "." : `./${request}`), + assertExportsFieldRequest, + assertExportTarget, + ); +}; + +/** + * @param {string} request request + * @returns {string} updated request + */ +function assertImportsFieldRequest(request) { + if (request.charCodeAt(0) !== hashCode) { + throw new Error('Request should start with "#"'); + } + if (request.length === 1) { + throw new Error("Request should have at least 2 characters"); + } + // Note: #/ patterns are now allowed per Node.js PR #60864 + // https://github.com/nodejs/node/pull/60864 + if (request.charCodeAt(request.length - 1) === slashCode) { + throw new Error("Only requesting file allowed"); + } + + return request.slice(1); +} + +/** + * @param {string} imp import target + * @param {boolean} expectFolder is folder expected + */ +function assertImportTarget(imp, expectFolder) { + const parsedIdentifier = parseIdentifier(imp); + + if (!parsedIdentifier) { + return; + } + + const [relativePath] = parsedIdentifier; + const isFolder = + relativePath.charCodeAt(relativePath.length - 1) === slashCode; + + if (isFolder !== expectFolder) { + throw new Error( + expectFolder + ? `Expecting folder to folder mapping. ${JSON.stringify( + imp, + )} should end with "/"` + : `Expecting file to file mapping. ${JSON.stringify( + imp, + )} should not end with "/"`, + ); + } +} + +/** + * @param {ImportsField} importsField the exports field + * @returns {FieldProcessor} process callback + */ +module.exports.processImportsField = function processImportsField( + importsField, +) { + return createFieldProcessor( + importsField, + (request) => `#${request}`, + assertImportsFieldRequest, + assertImportTarget, + ); +}; diff --git a/client/node_modules/enhanced-resolve/lib/util/fs.js b/client/node_modules/enhanced-resolve/lib/util/fs.js new file mode 100644 index 0000000..753dd36 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/util/fs.js @@ -0,0 +1,75 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Natsu @xiaoxiaojx +*/ + +"use strict"; + +const stripJsonComments = require("./strip-json-comments"); + +/** @typedef {import("../Resolver").FileSystem} FileSystem */ +/** @typedef {import("../Resolver").JsonObject} JsonObject */ + +/** + * @typedef {object} ReadJsonOptions + * @property {boolean=} stripComments Whether to strip JSONC comments + */ + +/** @type {WeakMap} */ +const _stripCommentsCache = new WeakMap(); + +/** + * Read and parse JSON file (supports JSONC with comments). + * Callback-based so a synchronous `fileSystem` stays synchronous all the + * way through — Promise wrapping would defer resolution by a Promise tick + * and break `resolveSync` when `tsconfig` is used together with + * `useSyncFileSystemCalls: true`. + * @param {FileSystem} fileSystem the file system + * @param {string} jsonFilePath absolute path to JSON file + * @param {ReadJsonOptions} options Options + * @param {(err: NodeJS.ErrnoException | Error | null, content?: JsonObject) => void} callback callback + * @returns {void} + */ +function readJson(fileSystem, jsonFilePath, options, callback) { + const { stripComments = false } = options; + const { readJson: fsReadJson } = fileSystem; + if (fsReadJson && !stripComments) { + fsReadJson(jsonFilePath, (err, content) => { + if (err) return callback(err); + callback(null, /** @type {JsonObject} */ (content)); + }); + return; + } + + fileSystem.readFile(jsonFilePath, (err, data) => { + if (err) return callback(err); + const buf = /** @type {Buffer} */ (data); + + if (stripComments) { + const cached = _stripCommentsCache.get(buf); + if (cached !== undefined) return callback(null, cached); + } + + let result; + try { + const jsonText = buf.toString(); + const jsonWithoutComments = stripComments + ? stripJsonComments(jsonText, { + trailingCommas: true, + whitespace: true, + }) + : jsonText; + result = JSON.parse(jsonWithoutComments); + } catch (parseErr) { + return callback(/** @type {Error} */ (parseErr)); + } + + if (stripComments) { + _stripCommentsCache.set(buf, result); + } + + callback(null, result); + }); +} + +module.exports.readJson = readJson; diff --git a/client/node_modules/enhanced-resolve/lib/util/identifier.js b/client/node_modules/enhanced-resolve/lib/util/identifier.js new file mode 100644 index 0000000..8eeb6ea --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/util/identifier.js @@ -0,0 +1,103 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const memorize = require("./memoize"); + +const getUrl = memorize(() => require("url")); + +const PATH_QUERY_FRAGMENT_REGEXP = + /^(#?(?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; +const ZERO_ESCAPE_REGEXP = /\0(.)/g; +const FILE_REG_EXP = /file:/i; + +/** + * Index past a DOS device path prefix (`\\?\…` or `\\.\…`), or 0. Kept + * out of `parseIdentifier` on purpose: inlining it back bloats the caller + * beyond the size where V8's interpreter and JIT both handle it well + * (the cause of the description-files-multi CodSpeed regression). + * @param {string} identifier identifier known to start with `\` + * @returns {number} 4 if identifier starts with a DOS device prefix, else 0 + */ +function dosPrefixEnd(identifier) { + if ( + identifier.length >= 4 && + identifier.charCodeAt(1) === 92 && + identifier.charCodeAt(3) === 92 + ) { + const c2 = identifier.charCodeAt(2); + if (c2 === 63 || c2 === 46) return 4; + } + return 0; +} + +/** + * @param {string} identifier identifier + * @returns {[string, string, string] | null} parsed identifier + */ +function parseIdentifier(identifier) { + if (!identifier) { + return null; + } + + if (FILE_REG_EXP.test(identifier)) { + identifier = getUrl().fileURLToPath(identifier); + } + + const firstEscape = identifier.indexOf("\0"); + + // Handle `\0` + if (firstEscape !== -1) { + const match = PATH_QUERY_FRAGMENT_REGEXP.exec(identifier); + + if (!match) return null; + + return [ + match[1].replace(ZERO_ESCAPE_REGEXP, "$1"), + match[2] ? match[2].replace(ZERO_ESCAPE_REGEXP, "$1") : "", + match[3] || "", + ]; + } + + // Fast path for inputs that don't use \0 escaping. DOS device paths + // (`\\?\…`, `\\.\…`) embed a literal `?` / `.` that must not be read + // as a query separator; skip past the prefix when the input actually + // starts with `\`. Gate is a single char-code compare so this function + // stays inside V8's inline budget for its hot callers (resolver parse). + const scanStart = + identifier.charCodeAt(0) === 92 ? dosPrefixEnd(identifier) : 0; + const queryStart = identifier.indexOf("?", scanStart); + // Start at index 1 (or past a DOS prefix) to ignore a possible leading hash. + const fragmentStart = identifier.indexOf("#", scanStart || 1); + + if (fragmentStart < 0) { + if (queryStart < 0) { + // No fragment, no query + return [identifier, "", ""]; + } + + // Query, no fragment + return [identifier.slice(0, queryStart), identifier.slice(queryStart), ""]; + } + + if (queryStart < 0 || fragmentStart < queryStart) { + // Fragment, no query + return [ + identifier.slice(0, fragmentStart), + "", + identifier.slice(fragmentStart), + ]; + } + + // Query and fragment + return [ + identifier.slice(0, queryStart), + identifier.slice(queryStart, fragmentStart), + identifier.slice(fragmentStart), + ]; +} + +module.exports.parseIdentifier = parseIdentifier; diff --git a/client/node_modules/enhanced-resolve/lib/util/memoize.js b/client/node_modules/enhanced-resolve/lib/util/memoize.js new file mode 100644 index 0000000..b46e252 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/util/memoize.js @@ -0,0 +1,37 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * @template T + * @typedef {() => T} FunctionReturning + */ + +/** + * @template T + * @param {FunctionReturning} fn memorized function + * @returns {FunctionReturning} new function + */ +const memoize = (fn) => { + let cache = false; + /** @type {T | undefined} */ + let result; + return () => { + if (cache) { + return /** @type {T} */ (result); + } + + result = fn(); + cache = true; + // Allow to clean up memory for fn + // and all dependent resources + /** @type {FunctionReturning | undefined} */ + (fn) = undefined; + return /** @type {T} */ (result); + }; +}; + +module.exports = memoize; diff --git a/client/node_modules/enhanced-resolve/lib/util/module-browser.js b/client/node_modules/enhanced-resolve/lib/util/module-browser.js new file mode 100644 index 0000000..1258c22 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/util/module-browser.js @@ -0,0 +1,8 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +module.exports = {}; diff --git a/client/node_modules/enhanced-resolve/lib/util/path.js b/client/node_modules/enhanced-resolve/lib/util/path.js new file mode 100644 index 0000000..707b614 --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/util/path.js @@ -0,0 +1,344 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const path = require("path"); + +const CHAR_HASH = "#".charCodeAt(0); +const CHAR_SLASH = "/".charCodeAt(0); +const CHAR_BACKSLASH = "\\".charCodeAt(0); +const CHAR_A = "A".charCodeAt(0); +const CHAR_Z = "Z".charCodeAt(0); +const CHAR_LOWER_A = "a".charCodeAt(0); +const CHAR_LOWER_Z = "z".charCodeAt(0); +const CHAR_DOT = ".".charCodeAt(0); +const CHAR_COLON = ":".charCodeAt(0); +const CHAR_QUESTION = "?".charCodeAt(0); + +const posixNormalize = path.posix.normalize; +const winNormalize = path.win32.normalize; + +/** + * @enum {number} + */ +const PathType = Object.freeze({ + Empty: 0, + Normal: 1, + Relative: 2, + AbsoluteWin: 3, + AbsolutePosix: 4, + Internal: 5, +}); + +const deprecatedInvalidSegmentRegEx = + /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i; + +const invalidSegmentRegEx = + /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i; + +/** + * @param {string} maybePath a path known to start with `\\` + * @returns {PathType} AbsoluteWin for `\\?\…` / `\\.\…`, otherwise Normal + */ +const getDosDeviceType = (maybePath) => { + if (maybePath.length >= 4 && maybePath.charCodeAt(3) === CHAR_BACKSLASH) { + const c2 = maybePath.charCodeAt(2); + if (c2 === CHAR_QUESTION || c2 === CHAR_DOT) { + return PathType.AbsoluteWin; + } + } + return PathType.Normal; +}; + +/** + * @param {string} maybePath a path + * @returns {PathType} type of path + */ +const getType = (maybePath) => { + switch (maybePath.length) { + case 0: + return PathType.Empty; + case 1: { + const c0 = maybePath.charCodeAt(0); + switch (c0) { + case CHAR_DOT: + return PathType.Relative; + case CHAR_SLASH: + return PathType.AbsolutePosix; + case CHAR_HASH: + return PathType.Internal; + } + return PathType.Normal; + } + case 2: { + const c0 = maybePath.charCodeAt(0); + switch (c0) { + case CHAR_DOT: { + const c1 = maybePath.charCodeAt(1); + switch (c1) { + case CHAR_DOT: + case CHAR_SLASH: + return PathType.Relative; + } + return PathType.Normal; + } + case CHAR_SLASH: + return PathType.AbsolutePosix; + case CHAR_HASH: + return PathType.Internal; + } + const c1 = maybePath.charCodeAt(1); + if ( + c1 === CHAR_COLON && + ((c0 >= CHAR_A && c0 <= CHAR_Z) || + (c0 >= CHAR_LOWER_A && c0 <= CHAR_LOWER_Z)) + ) { + return PathType.AbsoluteWin; + } + return PathType.Normal; + } + } + const c0 = maybePath.charCodeAt(0); + switch (c0) { + case CHAR_DOT: { + const c1 = maybePath.charCodeAt(1); + switch (c1) { + case CHAR_SLASH: + return PathType.Relative; + case CHAR_DOT: { + const c2 = maybePath.charCodeAt(2); + if (c2 === CHAR_SLASH) return PathType.Relative; + return PathType.Normal; + } + } + return PathType.Normal; + } + case CHAR_SLASH: + return PathType.AbsolutePosix; + case CHAR_HASH: + return PathType.Internal; + } + const c1 = maybePath.charCodeAt(1); + if (c1 === CHAR_COLON) { + const c2 = maybePath.charCodeAt(2); + if ( + (c2 === CHAR_BACKSLASH || c2 === CHAR_SLASH) && + ((c0 >= CHAR_A && c0 <= CHAR_Z) || + (c0 >= CHAR_LOWER_A && c0 <= CHAR_LOWER_Z)) + ) { + return PathType.AbsoluteWin; + } + } + // DOS device paths (`\\?\…`, `\\.\…`) are handled in a cold helper so + // this function stays small — inlining the full check here regressed + // `description-files-multi` under `--no-opt` interpretation. Here we + // only pay the two-byte gate for non-DOS inputs. + if (c0 === CHAR_BACKSLASH && c1 === CHAR_BACKSLASH) { + return getDosDeviceType(maybePath); + } + return PathType.Normal; +}; + +/** + * @param {string} maybePath a path + * @returns {string} the normalized path + */ +const normalize = (maybePath) => { + switch (getType(maybePath)) { + case PathType.Empty: + return maybePath; + case PathType.AbsoluteWin: + return winNormalize(maybePath); + case PathType.Relative: { + const r = posixNormalize(maybePath); + return getType(r) === PathType.Relative ? r : `./${r}`; + } + } + return posixNormalize(maybePath); +}; + +/** + * @param {string} rootPath the root path + * @param {string | undefined} request the request path + * @returns {string} the joined path + */ +const join = (rootPath, request) => { + if (!request) return normalize(rootPath); + const requestType = getType(request); + switch (requestType) { + case PathType.AbsolutePosix: + return posixNormalize(request); + case PathType.AbsoluteWin: + return winNormalize(request); + } + switch (getType(rootPath)) { + case PathType.Normal: + case PathType.Relative: + case PathType.AbsolutePosix: + return posixNormalize(`${rootPath}/${request}`); + case PathType.AbsoluteWin: + return winNormalize(`${rootPath}\\${request}`); + } + switch (requestType) { + case PathType.Empty: + return rootPath; + case PathType.Relative: { + const r = posixNormalize(rootPath); + return getType(r) === PathType.Relative ? r : `./${r}`; + } + } + return posixNormalize(rootPath); +}; + +/** + * @param {string} maybePath a path + * @returns {string} the directory name + */ +const dirname = (maybePath) => { + switch (getType(maybePath)) { + case PathType.AbsoluteWin: + return path.win32.dirname(maybePath); + } + return path.posix.dirname(maybePath); +}; + +/** @typedef {{ fn: (rootPath: string, request: string) => string, cache: Map> }} CachedJoin */ + +/** + * @returns {CachedJoin} cached join + */ +const createCachedJoin = () => { + /** @type {CachedJoin["cache"]} */ + const cache = new Map(); + /** @type {CachedJoin["fn"]} */ + const fn = (rootPath, request) => { + /** @type {string | undefined} */ + let cacheEntry; + let inner = cache.get(rootPath); + if (inner === undefined) { + cache.set(rootPath, (inner = new Map())); + } else { + cacheEntry = inner.get(request); + if (cacheEntry !== undefined) return cacheEntry; + } + cacheEntry = join(rootPath, request); + inner.set(request, cacheEntry); + return cacheEntry; + }; + return { fn, cache }; +}; + +/** @typedef {{ fn: (maybePath: string) => string, cache: Map }} CachedDirname */ + +/** + * @returns {CachedDirname} cached dirname + */ +const createCachedDirname = () => { + /** @type {CachedDirname["cache"]} */ + const cache = new Map(); + /** @type {CachedDirname["fn"]} */ + const fn = (maybePath) => { + const cacheEntry = cache.get(maybePath); + if (cacheEntry !== undefined) return cacheEntry; + const result = dirname(maybePath); + cache.set(maybePath, result); + return result; + }; + return { fn, cache }; +}; + +/** @typedef {{ fn: (maybePath: string, suffix?: string) => string, cache: Map> }} CachedBasename */ + +/** + * @returns {CachedBasename} cached basename + */ +const createCachedBasename = () => { + /** @type {CachedBasename["cache"]} */ + const cache = new Map(); + /** @type {CachedBasename["fn"]} */ + const fn = (maybePath, suffix) => { + /** @type {string | undefined} */ + let cacheEntry; + let inner = cache.get(maybePath); + if (inner === undefined) { + cache.set(maybePath, (inner = new Map())); + } else { + cacheEntry = inner.get(suffix); + if (cacheEntry !== undefined) return cacheEntry; + } + cacheEntry = path.basename(maybePath, suffix); + inner.set(suffix, cacheEntry); + return cacheEntry; + }; + return { fn, cache }; +}; + +/** + * Whether `request` is a relative request — i.e. matches `^\.\.?(?:\/|$)`. + * + * This is called on every `doResolve` via `UnsafeCachePlugin` and + * `getInnerRequest`, so the char-code form is meaningfully faster than the + * equivalent regex test: no regex state machine, no string object churn. + * @param {string} request request string + * @returns {boolean} true if request is relative + */ +const isRelativeRequest = (request) => { + const len = request.length; + if (len === 0 || request.charCodeAt(0) !== CHAR_DOT) return false; + if (len === 1) return true; // "." + const c1 = request.charCodeAt(1); + if (c1 === CHAR_SLASH) return true; // "./..." + if (c1 !== CHAR_DOT) return false; // ".x..." + if (len === 2) return true; // ".." + return request.charCodeAt(2) === CHAR_SLASH; // "../..." +}; + +/** + * Check if childPath is a subdirectory of parentPath. + * + * Called from `TsconfigPathsPlugin._selectPathsDataForContext` inside a loop + * over every tsconfig-paths context on every resolve, so it's worth keeping + * cheap. Compared to the previous `startsWith(normalize(parent + "/"))` + * version, this: checks the last char with `charCodeAt` instead of two + * `endsWith` calls; and skips `normalize()` entirely in the common case + * (parent has no trailing separator), since all we really need is the same + * anchoring effect — a cheap `startsWith` plus a separator char check on the + * byte immediately after `parentPath.length`. + * @param {string} parentPath parent directory path + * @param {string} childPath child path to check + * @returns {boolean} true if childPath is under parentPath + */ +const isSubPath = (parentPath, childPath) => { + const parentLen = parentPath.length; + if (parentLen === 0) { + // Match the old `normalize("" + "/") === "/"` fallback: an empty + // parent only "contains" a child that starts with a forward slash. + return childPath.length > 0 && childPath.charCodeAt(0) === CHAR_SLASH; + } + const lastChar = parentPath.charCodeAt(parentLen - 1); + if (lastChar === CHAR_SLASH || lastChar === CHAR_BACKSLASH) { + // Parent already ends with a separator — a plain prefix test is enough. + return childPath.startsWith(parentPath); + } + if (childPath.length <= parentLen) return false; + if (!childPath.startsWith(parentPath)) return false; + // Must be followed by a separator so "/app" doesn't match "/app-other". + const nextChar = childPath.charCodeAt(parentLen); + return nextChar === CHAR_SLASH || nextChar === CHAR_BACKSLASH; +}; + +module.exports.PathType = PathType; +module.exports.createCachedBasename = createCachedBasename; +module.exports.createCachedDirname = createCachedDirname; +module.exports.createCachedJoin = createCachedJoin; +module.exports.deprecatedInvalidSegmentRegEx = deprecatedInvalidSegmentRegEx; +module.exports.dirname = dirname; +module.exports.getType = getType; +module.exports.invalidSegmentRegEx = invalidSegmentRegEx; +module.exports.isRelativeRequest = isRelativeRequest; +module.exports.isSubPath = isSubPath; +module.exports.join = join; +module.exports.normalize = normalize; diff --git a/client/node_modules/enhanced-resolve/lib/util/process-browser.js b/client/node_modules/enhanced-resolve/lib/util/process-browser.js new file mode 100644 index 0000000..95f8d5e --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/util/process-browser.js @@ -0,0 +1,23 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +module.exports = { + /** + * @type {Record} + */ + versions: {}, + // eslint-disable-next-line jsdoc/reject-function-type + /** @param {Function} fn function */ + nextTick(fn) { + // eslint-disable-next-line prefer-rest-params + const args = Array.prototype.slice.call(arguments, 1); + Promise.resolve().then(() => { + // eslint-disable-next-line prefer-spread + fn.apply(null, args); + }); + }, +}; diff --git a/client/node_modules/enhanced-resolve/lib/util/strip-json-comments.js b/client/node_modules/enhanced-resolve/lib/util/strip-json-comments.js new file mode 100644 index 0000000..5096f8b --- /dev/null +++ b/client/node_modules/enhanced-resolve/lib/util/strip-json-comments.js @@ -0,0 +1,177 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Natsu @xiaoxiaojx + + This file contains code ported from strip-json-comments: + https://github.com/sindresorhus/strip-json-comments + Original license: MIT + Original author: Sindre Sorhus +*/ + +"use strict"; + +/** + * @typedef {object} StripJsonCommentsOptions + * @property {boolean=} whitespace Replace comments with whitespace + * @property {boolean=} trailingCommas Strip trailing commas + */ + +const singleComment = Symbol("singleComment"); +const multiComment = Symbol("multiComment"); + +/** + * Strip without whitespace (returns empty string) + * @param {string} _string Unused + * @param {number} _start Unused + * @param {number} _end Unused + * @returns {string} Empty string for all input + */ +const stripWithoutWhitespace = (_string, _start, _end) => ""; + +/** + * Replace all characters except ASCII spaces, tabs and line endings with regular spaces to ensure valid JSON output. + * @param {string} string String to process + * @param {number} start Start index + * @param {number} end End index + * @returns {string} Processed string with comments replaced by whitespace + */ +const stripWithWhitespace = (string, start, end) => + string.slice(start, end).replace(/[^ \t\r\n]/g, " "); + +/** + * Check if a quote is escaped + * @param {string} jsonString JSON string + * @param {number} quotePosition Position of the quote + * @returns {boolean} True if the quote at the given position is escaped + */ +const isEscaped = (jsonString, quotePosition) => { + let index = quotePosition - 1; + let backslashCount = 0; + + while (jsonString[index] === "\\") { + index -= 1; + backslashCount += 1; + } + + return Boolean(backslashCount % 2); +}; + +/** + * Strip comments from JSON string + * @param {string} jsonString JSON string with potential comments + * @param {StripJsonCommentsOptions} options Options + * @returns {string} JSON string without comments + */ +function stripJsonComments( + jsonString, + { whitespace = true, trailingCommas = false } = {}, +) { + if (typeof jsonString !== "string") { + throw new TypeError( + `Expected argument \`jsonString\` to be a \`string\`, got \`${typeof jsonString}\``, + ); + } + + const strip = whitespace ? stripWithWhitespace : stripWithoutWhitespace; + + let isInsideString = false; + /** @type {false | typeof singleComment | typeof multiComment} */ + let isInsideComment = false; + let offset = 0; + let buffer = ""; + let result = ""; + let commaIndex = -1; + + for (let index = 0; index < jsonString.length; index++) { + const currentCharacter = jsonString[index]; + const nextCharacter = jsonString[index + 1]; + + if (!isInsideComment && currentCharacter === '"') { + // Enter or exit string + const escaped = isEscaped(jsonString, index); + if (!escaped) { + isInsideString = !isInsideString; + } + } + + if (isInsideString) { + continue; + } + + if (!isInsideComment && currentCharacter + nextCharacter === "//") { + // Enter single-line comment + buffer += jsonString.slice(offset, index); + offset = index; + isInsideComment = singleComment; + index++; + } else if ( + isInsideComment === singleComment && + currentCharacter + nextCharacter === "\r\n" + ) { + // Exit single-line comment via \r\n + index++; + isInsideComment = false; + buffer += strip(jsonString, offset, index); + offset = index; + continue; + } else if (isInsideComment === singleComment && currentCharacter === "\n") { + // Exit single-line comment via \n + isInsideComment = false; + buffer += strip(jsonString, offset, index); + offset = index; + } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") { + // Enter multiline comment + buffer += jsonString.slice(offset, index); + offset = index; + isInsideComment = multiComment; + index++; + continue; + } else if ( + isInsideComment === multiComment && + currentCharacter + nextCharacter === "*/" + ) { + // Exit multiline comment + index++; + isInsideComment = false; + buffer += strip(jsonString, offset, index + 1); + offset = index + 1; + continue; + } else if (trailingCommas && !isInsideComment) { + if (commaIndex !== -1) { + if (currentCharacter === "}" || currentCharacter === "]") { + // Strip trailing comma + buffer += jsonString.slice(offset, index); + result += strip(buffer, 0, 1) + buffer.slice(1); + buffer = ""; + offset = index; + commaIndex = -1; + } else if ( + currentCharacter !== " " && + currentCharacter !== "\t" && + currentCharacter !== "\r" && + currentCharacter !== "\n" + ) { + // Hit non-whitespace following a comma; comma is not trailing + buffer += jsonString.slice(offset, index); + offset = index; + commaIndex = -1; + } + } else if (currentCharacter === ",") { + // Flush buffer prior to this point, and save new comma index + result += buffer + jsonString.slice(offset, index); + buffer = ""; + offset = index; + commaIndex = index; + } + } + } + + const remaining = + isInsideComment === singleComment + ? strip(jsonString, offset, jsonString.length) + : jsonString.slice(offset); + + return result + buffer + remaining; +} + +module.exports = stripJsonComments; diff --git a/client/node_modules/enhanced-resolve/package.json b/client/node_modules/enhanced-resolve/package.json new file mode 100644 index 0000000..b1e04f1 --- /dev/null +++ b/client/node_modules/enhanced-resolve/package.json @@ -0,0 +1,83 @@ +{ + "name": "enhanced-resolve", + "version": "5.21.6", + "description": "Offers a async require.resolve function. It's highly configurable.", + "homepage": "http://github.com/webpack/enhanced-resolve", + "repository": { + "type": "git", + "url": "git://github.com/webpack/enhanced-resolve.git" + }, + "license": "MIT", + "author": "Tobias Koppers @sokra", + "main": "lib/index.js", + "browser": { + "process": "./lib/util/process-browser.js", + "module": "./lib/util/module-browser.js" + }, + "types": "types.d.ts", + "files": [ + "lib", + "types.d.ts", + "LICENSE" + ], + "scripts": { + "prepare": "husky", + "lint": "npm run lint:code && npm run lint:types && npm run lint:types-test && npm run lint:special && npm run fmt:check && npm run lint:spellcheck", + "lint:code": "eslint --cache .", + "lint:special": "node node_modules/tooling/inherit-types && node node_modules/tooling/generate-types", + "lint:types": "tsc", + "lint:types-test": "tsc -p tsconfig.types.test.json", + "lint:spellcheck": "cspell --cache --no-must-find-files --quiet \"**/*.*\"", + "fmt": "npm run fmt:base -- --log-level warn --write", + "fmt:check": "npm run fmt:base -- --check", + "fmt:base": "node_modules/prettier/bin/prettier.cjs --cache --ignore-unknown .", + "fix": "npm run fix:code && npm run fix:special", + "fix:code": "npm run lint:code -- --fix", + "fix:special": "node node_modules/tooling/inherit-types --write && node node_modules/tooling/generate-types --write", + "type-report": "rimraf coverage && npm run cover:types && npm run cover:report && open-cli coverage/lcov-report/index.html", + "pretest": "npm run lint", + "test": "npm run test:coverage", + "test:only": "jest", + "test:watch": "npm run test:only -- --watch", + "test:coverage": "npm run test:only -- --collectCoverageFrom=\"lib/**/*.js\" --coverage", + "version": "changeset version", + "release": "changeset publish", + "benchmark": "node --max-old-space-size=4096 --hash-seed=1 --random-seed=1 --no-opt --predictable --predictable-gc-schedule --interpreted-frames-native-stack --allow-natives-syntax --expose-gc --no-concurrent-sweeping ./benchmark/run.mjs" + }, + "lint-staged": { + "*.{js,cjs,mjs}": [ + "eslint --cache --fix" + ], + "*": [ + "prettier --cache --write --ignore-unknown", + "cspell --cache --no-must-find-files" + ] + }, + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "devDependencies": { + "@changesets/cli": "^2.30.0", + "@changesets/get-github-info": "^0.8.0", + "@codspeed/core": "^5.2.0", + "@types/graceful-fs": "^4.1.6", + "@types/jest": "^30.0.0", + "@types/node": "^24.10.4", + "cspell": "^10.0.0", + "eslint": "^9.39.2", + "eslint-config-webpack": "^4.9.5", + "husky": "^9.1.7", + "jest": "^30.3.0", + "lint-staged": "^17.0.4", + "memfs": "^4.56.11", + "prettier": "^3.7.4", + "prettier-2": "npm:prettier@^2", + "tooling": "webpack/tooling#v1.26.1", + "tinybench": "^6.0.0", + "typescript": "^6.0.2" + }, + "engines": { + "node": ">=10.13.0" + } +} diff --git a/client/node_modules/enhanced-resolve/types.d.ts b/client/node_modules/enhanced-resolve/types.d.ts new file mode 100644 index 0000000..997900d --- /dev/null +++ b/client/node_modules/enhanced-resolve/types.d.ts @@ -0,0 +1,2006 @@ +/* + * This file was automatically generated. + * DO NOT MODIFY BY HAND. + * Run `yarn fix:special` to update + */ + +import { Buffer } from "buffer"; +import { AsyncSeriesBailHook, AsyncSeriesHook, SyncHook } from "tapable"; +import { URL as URL_Import } from "url"; + +declare interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal; +} +type Alias = string | false | string[]; +declare interface AliasOption { + alias: Alias; + name: string; + onlyModule?: boolean; +} +type AliasOptionNewRequest = string | false | string[]; +declare interface AliasOptions { + [index: string]: AliasOptionNewRequest; +} +type BaseFileSystem = FileSystem & SyncFileSystem; +declare interface BaseResolveRequest { + /** + * path + */ + path: string | false; + + /** + * content + */ + context?: Context; + + /** + * description file path + */ + descriptionFilePath?: string; + + /** + * description file root + */ + descriptionFileRoot?: string; + + /** + * description file data + */ + descriptionFileData?: JsonObject; + + /** + * tsconfig paths map + */ + tsconfigPathsMap?: null | TsconfigPathsMap; + + /** + * relative path + */ + relativePath?: string; + + /** + * true when need to ignore symlinks, otherwise false + */ + ignoreSymlinks?: boolean; + + /** + * true when full specified, otherwise false + */ + fullySpecified?: boolean; + + /** + * inner request for internal usage + */ + __innerRequest?: string; + + /** + * inner request for internal usage + */ + __innerRequest_request?: string; + + /** + * inner relative path for internal usage + */ + __innerRequest_relativePath?: string; +} +declare interface BasenameCacheEntry { + /** + * cached dirname function + */ + fn: (maybePath: string, suffix?: string) => string; + + /** + * the underlying cache map + */ + cache: Map>; +} +type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; +type BufferEncodingOption = "buffer" | { encoding: "buffer" }; +declare interface Cache { + [index: string]: undefined | ResolveRequest | ResolveRequest[]; +} +declare class CachedInputFileSystem { + constructor(fileSystem: BaseFileSystem, duration: number); + fileSystem: BaseFileSystem; + lstat?: LStat; + lstatSync?: LStatSync; + stat: Stat; + statSync: StatSync; + readdir: Readdir; + readdirSync: ReaddirSync; + readFile: ReadFile; + readFileSync: ReadFileSync; + readJson?: ( + pathOrFileDescription: PathOrFileDescriptor, + callback: ( + err: null | Error | NodeJS.ErrnoException, + result?: JsonObject, + ) => void, + ) => void; + readJsonSync?: (pathOrFileDescription: PathOrFileDescriptor) => JsonObject; + readlink: Readlink; + readlinkSync: ReadlinkSync; + realpath?: RealPath; + realpathSync?: RealPathSync; + purge( + what?: + | string + | number + | Buffer + | URL_url + | (string | number | Buffer | URL_url)[] + | Set, + ): void; +} +declare class CloneBasenamePlugin { + constructor( + source: + | string + | AsyncSeriesBailHook< + [ResolveRequest, ResolveContext], + null | ResolveRequest + >, + target: + | string + | AsyncSeriesBailHook< + [ResolveRequest, ResolveContext], + null | ResolveRequest + >, + ); + source: + | string + | AsyncSeriesBailHook< + [ResolveRequest, ResolveContext], + null | ResolveRequest + >; + target: + | string + | AsyncSeriesBailHook< + [ResolveRequest, ResolveContext], + null | ResolveRequest + >; + apply(resolver: Resolver): void; +} +declare interface CompiledAliasOption { + /** + * original alias name + */ + name: string; + + /** + * name + "/" — precomputed to avoid per-resolve concat + */ + nameWithSlash: string; + + /** + * alias target(s) + */ + alias: Alias; + + /** + * normalized onlyModule flag + */ + onlyModule: boolean; + + /** + * absolute form of `name` (with slash ending), null when not absolute + */ + absolutePath: null | string; + + /** + * substring before the single "*" in `name`, null when no wildcard + */ + wildcardPrefix: null | string; + + /** + * substring after the single "*" in `name`, null when no wildcard + */ + wildcardSuffix: null | string; + + /** + * first character code of `name` — used as a cheap screen on the hot path. `-1` indicates "matches any first char" (empty wildcard prefix). + */ + firstCharCode: number; + + /** + * true when `alias` is an array — precomputed so the hot path skips `Array.isArray` + */ + arrayAlias: boolean; +} +declare interface CompiledAliasOptions { + /** + * declaration-ordered list + */ + all: CompiledAliasOption[]; + + /** + * bucketed by first char code + */ + byFirstChar: Map; + + /** + * true when an empty-prefix wildcard is present + */ + hasAnyFirstChar: boolean; + + /** + * true when the bucket fast-path should be used at resolve time + */ + useBuckets: boolean; +} +type Context = KnownContext & Record; +declare interface Dirent { + /** + * true when is file, otherwise false + */ + isFile: () => boolean; + + /** + * true when is directory, otherwise false + */ + isDirectory: () => boolean; + + /** + * true when is block device, otherwise false + */ + isBlockDevice: () => boolean; + + /** + * true when is character device, otherwise false + */ + isCharacterDevice: () => boolean; + + /** + * true when is symbolic link, otherwise false + */ + isSymbolicLink: () => boolean; + + /** + * true when is FIFO, otherwise false + */ + isFIFO: () => boolean; + + /** + * true when is socket, otherwise false + */ + isSocket: () => boolean; + + /** + * name + */ + name: T; + + /** + * path + */ + parentPath: string; + + /** + * path + */ + path?: string; +} +declare interface DirnameCacheEntry { + /** + * cached dirname function + */ + fn: (maybePath: string) => string; + + /** + * the underlying cache map + */ + cache: Map; +} +type EncodingOption = + | undefined + | null + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex" + | ObjectEncodingOptions; +type ErrorWithDetail = Error & { details?: string }; +declare interface ExtensionAliasOption { + alias: string | string[]; + extension: string; +} +declare interface ExtensionAliasOptions { + [index: string]: string | string[]; +} +declare interface FileSystem { + /** + * read file method + */ + readFile: ReadFile; + + /** + * readdir method + */ + readdir: Readdir; + + /** + * read json method + */ + readJson?: ( + pathOrFileDescription: PathOrFileDescriptor, + callback: ( + err: null | Error | NodeJS.ErrnoException, + result?: JsonObject, + ) => void, + ) => void; + + /** + * read link method + */ + readlink: Readlink; + + /** + * lstat method + */ + lstat?: LStat; + + /** + * stat method + */ + stat: Stat; + + /** + * realpath method + */ + realpath?: RealPath; +} +type IBigIntStats = IStatsBase & { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; +}; +declare interface IStats { + /** + * is file + */ + isFile: () => boolean; + + /** + * is directory + */ + isDirectory: () => boolean; + + /** + * is block device + */ + isBlockDevice: () => boolean; + + /** + * is character device + */ + isCharacterDevice: () => boolean; + + /** + * is symbolic link + */ + isSymbolicLink: () => boolean; + + /** + * is FIFO + */ + isFIFO: () => boolean; + + /** + * is socket + */ + isSocket: () => boolean; + + /** + * dev + */ + dev: number; + + /** + * ino + */ + ino: number; + + /** + * mode + */ + mode: number; + + /** + * nlink + */ + nlink: number; + + /** + * uid + */ + uid: number; + + /** + * gid + */ + gid: number; + + /** + * rdev + */ + rdev: number; + + /** + * size + */ + size: number; + + /** + * blksize + */ + blksize: number; + + /** + * blocks + */ + blocks: number; + + /** + * atime ms + */ + atimeMs: number; + + /** + * mtime ms + */ + mtimeMs: number; + + /** + * ctime ms + */ + ctimeMs: number; + + /** + * birthtime ms + */ + birthtimeMs: number; + + /** + * atime + */ + atime: Date; + + /** + * mtime + */ + mtime: Date; + + /** + * ctime + */ + ctime: Date; + + /** + * birthtime + */ + birthtime: Date; +} +declare interface IStatsBase { + /** + * is file + */ + isFile: () => boolean; + + /** + * is directory + */ + isDirectory: () => boolean; + + /** + * is block device + */ + isBlockDevice: () => boolean; + + /** + * is character device + */ + isCharacterDevice: () => boolean; + + /** + * is symbolic link + */ + isSymbolicLink: () => boolean; + + /** + * is FIFO + */ + isFIFO: () => boolean; + + /** + * is socket + */ + isSocket: () => boolean; + + /** + * dev + */ + dev: T; + + /** + * ino + */ + ino: T; + + /** + * mode + */ + mode: T; + + /** + * nlink + */ + nlink: T; + + /** + * uid + */ + uid: T; + + /** + * gid + */ + gid: T; + + /** + * rdev + */ + rdev: T; + + /** + * size + */ + size: T; + + /** + * blksize + */ + blksize: T; + + /** + * blocks + */ + blocks: T; + + /** + * atime ms + */ + atimeMs: T; + + /** + * mtime ms + */ + mtimeMs: T; + + /** + * ctime ms + */ + ctimeMs: T; + + /** + * birthtime ms + */ + birthtimeMs: T; + + /** + * atime + */ + atime: Date; + + /** + * mtime + */ + mtime: Date; + + /** + * ctime + */ + ctime: Date; + + /** + * birthtime + */ + birthtime: Date; +} +declare interface Iterator { + ( + item: T, + callback: (err?: null | Error, result?: null | Z) => void, + i: number, + ): void; +} +declare interface JoinCacheEntry { + /** + * cached join function + */ + fn: (rootPath: string, request: string) => string; + + /** + * the underlying cache map + */ + cache: Map>; +} +declare interface JsonObject { + [index: string]: + | undefined + | null + | string + | number + | boolean + | JsonObject + | JsonValue[]; +} +type JsonValue = null | string | number | boolean | JsonObject | JsonValue[]; +declare interface KnownContext { + /** + * environments + */ + environments?: string[]; +} +declare interface KnownHooks { + /** + * resolve step hook + */ + resolveStep: SyncHook< + [ + AsyncSeriesBailHook< + [ResolveRequest, ResolveContext], + null | ResolveRequest + >, + ResolveRequest, + ] + >; + + /** + * no resolve hook + */ + noResolve: SyncHook<[ResolveRequest, Error]>; + + /** + * resolve hook + */ + resolve: AsyncSeriesBailHook< + [ResolveRequest, ResolveContext], + null | ResolveRequest + >; + + /** + * result hook + */ + result: AsyncSeriesHook<[ResolveRequest, ResolveContext]>; +} +declare interface LStat { + ( + path: PathLike, + callback: (err: null | NodeJS.ErrnoException, result?: IStats) => void, + ): void; + ( + path: PathLike, + options: undefined | (StatOptions & { bigint?: false }), + callback: (err: null | NodeJS.ErrnoException, result?: IStats) => void, + ): void; + ( + path: PathLike, + options: StatOptions & { bigint: true }, + callback: ( + err: null | NodeJS.ErrnoException, + result?: IBigIntStats, + ) => void, + ): void; + ( + path: PathLike, + options: undefined | StatOptions, + callback: ( + err: null | NodeJS.ErrnoException, + result?: IStats | IBigIntStats, + ) => void, + ): void; +} +declare interface LStatSync { + (path: PathLike, options?: undefined): IStats; + ( + path: PathLike, + options?: StatSyncOptions & { bigint?: false; throwIfNoEntry: false }, + ): undefined | IStats; + ( + path: PathLike, + options: StatSyncOptions & { bigint: true; throwIfNoEntry: false }, + ): undefined | IBigIntStats; + (path: PathLike, options?: StatSyncOptions & { bigint?: false }): IStats; + (path: PathLike, options: StatSyncOptions & { bigint: true }): IBigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { bigint: boolean; throwIfNoEntry?: false }, + ): IStats | IBigIntStats; + ( + path: PathLike, + options?: StatSyncOptions, + ): undefined | IStats | IBigIntStats; +} +declare class LogInfoPlugin { + constructor( + source: + | string + | AsyncSeriesBailHook< + [ResolveRequest, ResolveContext], + null | ResolveRequest + >, + ); + source: + | string + | AsyncSeriesBailHook< + [ResolveRequest, ResolveContext], + null | ResolveRequest + >; + apply(resolver: Resolver): void; +} +declare interface ObjectEncodingOptions { + /** + * encoding + */ + encoding?: + | null + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; +} +declare interface ParsedIdentifier { + /** + * request + */ + request: string; + + /** + * query + */ + query: string; + + /** + * fragment + */ + fragment: string; + + /** + * is directory + */ + directory: boolean; + + /** + * is module + */ + module: boolean; + + /** + * is file + */ + file: boolean; + + /** + * is internal + */ + internal: boolean; +} +declare interface PathCacheFunctions { + /** + * cached join + */ + join: JoinCacheEntry; + + /** + * cached dirname + */ + dirname: DirnameCacheEntry; + + /** + * cached basename + */ + basename: BasenameCacheEntry; +} +type PathLike = string | Buffer | URL_url; +type PathOrFileDescriptor = string | number | Buffer | URL_url; +type Plugin = + | undefined + | null + | false + | "" + | 0 + | { apply: (this: Resolver, resolver: Resolver) => void } + | ((this: Resolver, resolver: Resolver) => void); +declare interface PnpApi { + /** + * resolve to unqualified + */ + resolveToUnqualified: ( + packageName: string, + issuer: string, + options: { considerBuiltins: boolean }, + ) => null | string; +} +declare interface ReadFile { + ( + path: PathOrFileDescriptor, + options: + | undefined + | null + | ({ encoding?: null; flag?: string } & Abortable), + callback: (err: null | NodeJS.ErrnoException, result?: Buffer) => void, + ): void; + ( + path: PathOrFileDescriptor, + options: + | ({ encoding: BufferEncoding; flag?: string } & Abortable) + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex", + callback: (err: null | NodeJS.ErrnoException, result?: string) => void, + ): void; + ( + path: PathOrFileDescriptor, + options: + | undefined + | null + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex" + | (ObjectEncodingOptions & { flag?: string } & Abortable), + callback: ( + err: null | NodeJS.ErrnoException, + result?: string | Buffer, + ) => void, + ): void; + ( + path: PathOrFileDescriptor, + callback: (err: null | NodeJS.ErrnoException, result?: Buffer) => void, + ): void; +} +declare interface ReadFileSync { + ( + path: PathOrFileDescriptor, + options?: null | { encoding?: null; flag?: string }, + ): Buffer; + ( + path: PathOrFileDescriptor, + options: + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex" + | { encoding: BufferEncoding; flag?: string }, + ): string; + ( + path: PathOrFileDescriptor, + options?: + | null + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex" + | (ObjectEncodingOptions & { flag?: string }), + ): string | Buffer; +} +declare interface Readdir { + ( + path: PathLike, + options: + | undefined + | null + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex" + | { + encoding: + | null + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + withFileTypes?: false; + recursive?: boolean; + }, + callback: (err: null | NodeJS.ErrnoException, files?: string[]) => void, + ): void; + ( + path: PathLike, + options: + | { encoding: "buffer"; withFileTypes?: false; recursive?: boolean } + | "buffer", + callback: (err: null | NodeJS.ErrnoException, files?: Buffer[]) => void, + ): void; + ( + path: PathLike, + options: + | undefined + | null + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex" + | (ObjectEncodingOptions & { + withFileTypes?: false; + recursive?: boolean; + }), + callback: ( + err: null | NodeJS.ErrnoException, + files?: string[] | Buffer[], + ) => void, + ): void; + ( + path: PathLike, + callback: (err: null | NodeJS.ErrnoException, files?: string[]) => void, + ): void; + ( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean; + }, + callback: ( + err: null | NodeJS.ErrnoException, + files?: Dirent[], + ) => void, + ): void; + ( + path: PathLike, + options: { encoding: "buffer"; withFileTypes: true; recursive?: boolean }, + callback: ( + err: null | NodeJS.ErrnoException, + files: Dirent[], + ) => void, + ): void; +} +declare interface ReaddirSync { + ( + path: PathLike, + options?: + | null + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex" + | { + encoding: + | null + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + withFileTypes?: false; + recursive?: boolean; + }, + ): string[]; + ( + path: PathLike, + options: + | "buffer" + | { encoding: "buffer"; withFileTypes?: false; recursive?: boolean }, + ): Buffer[]; + ( + path: PathLike, + options?: + | null + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex" + | (ObjectEncodingOptions & { + withFileTypes?: false; + recursive?: boolean; + }), + ): string[] | Buffer[]; + ( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean; + }, + ): Dirent[]; + ( + path: PathLike, + options: { encoding: "buffer"; withFileTypes: true; recursive?: boolean }, + ): Dirent[]; +} +declare interface Readlink { + ( + path: PathLike, + options: EncodingOption, + callback: (err: null | NodeJS.ErrnoException, result?: string) => void, + ): void; + ( + path: PathLike, + options: BufferEncodingOption, + callback: (err: null | NodeJS.ErrnoException, result?: Buffer) => void, + ): void; + ( + path: PathLike, + options: EncodingOption, + callback: ( + err: null | NodeJS.ErrnoException, + result?: string | Buffer, + ) => void, + ): void; + ( + path: PathLike, + callback: (err: null | NodeJS.ErrnoException, result?: string) => void, + ): void; +} +declare interface ReadlinkSync { + (path: PathLike, options?: EncodingOption): string; + (path: PathLike, options: BufferEncodingOption): Buffer; + (path: PathLike, options?: EncodingOption): string | Buffer; +} +declare interface RealPath { + ( + path: PathLike, + options: EncodingOption, + callback: (err: null | NodeJS.ErrnoException, result?: string) => void, + ): void; + ( + path: PathLike, + options: BufferEncodingOption, + callback: (err: null | NodeJS.ErrnoException, result?: Buffer) => void, + ): void; + ( + path: PathLike, + options: EncodingOption, + callback: ( + err: null | NodeJS.ErrnoException, + result?: string | Buffer, + ) => void, + ): void; + ( + path: PathLike, + callback: (err: null | NodeJS.ErrnoException, result?: string) => void, + ): void; +} +declare interface RealPathSync { + (path: PathLike, options?: EncodingOption): string; + (path: PathLike, options: BufferEncodingOption): Buffer; + (path: PathLike, options?: EncodingOption): string | Buffer; +} +declare interface ResolveContext { + /** + * directories that was found on file system + */ + contextDependencies?: WriteOnlySet; + + /** + * files that was found on file system + */ + fileDependencies?: WriteOnlySet; + + /** + * dependencies that was not found on file system + */ + missingDependencies?: WriteOnlySet; + + /** + * tip of the resolver call stack (a singly-linked list with Set-like API). For instance, `resolve → parsedResolve → describedResolve`. Accepts a legacy `Set` for back-compat with older callers; it is normalized internally without a hot-path branch. + */ + stack?: StackEntry | Set; + + /** + * log function + */ + log?: (str: string) => void; + + /** + * yield result, if provided plugins can return several results + */ + yield?: (request: ResolveRequest) => void; +} +declare interface ResolveFunction { + ( + context: Context, + path: string, + request: string, + resolveContext?: ResolveContext, + ): string | false; + ( + path: string, + request: string, + resolveContext?: ResolveContext, + ): string | false; +} +declare interface ResolveFunctionAsync { + ( + context: Context, + path: string, + request: string, + resolveContext: ResolveContext, + callback: ( + err: null | ErrorWithDetail, + res?: string | false, + req?: ResolveRequest, + ) => void, + ): void; + ( + context: Context, + path: string, + request: string, + callback: ( + err: null | ErrorWithDetail, + res?: string | false, + req?: ResolveRequest, + ) => void, + ): void; + ( + path: string, + request: string, + resolveContext: ResolveContext, + callback: ( + err: null | ErrorWithDetail, + res?: string | false, + req?: ResolveRequest, + ) => void, + ): void; + ( + path: string, + request: string, + callback: ( + err: null | ErrorWithDetail, + res?: string | false, + req?: ResolveRequest, + ) => void, + ): void; +} +declare interface ResolveFunctionPromise { + ( + context: Context, + path: string, + request: string, + resolveContext?: ResolveContext, + ): Promise; + ( + path: string, + request: string, + resolveContext?: ResolveContext, + ): Promise; +} +type ResolveOptionsOptionalFS = Omit< + ResolveOptionsResolverFactoryObject_2, + "fileSystem" +> & + Partial>; +declare interface ResolveOptionsResolverFactoryObject_1 { + /** + * alias + */ + alias: AliasOption[]; + + /** + * fallback + */ + fallback: AliasOption[]; + + /** + * alias fields + */ + aliasFields: Set; + + /** + * extension alias + */ + extensionAlias: ExtensionAliasOption[]; + + /** + * apply extension alias to exports field targets + */ + extensionAliasForExports: boolean; + + /** + * cache predicate + */ + cachePredicate: (predicate: ResolveRequest) => boolean; + + /** + * cache with context + */ + cacheWithContext: boolean; + + /** + * A list of exports field condition names. + */ + conditionNames: Set; + + /** + * description files + */ + descriptionFiles: string[]; + + /** + * enforce extension + */ + enforceExtension: boolean; + + /** + * exports fields + */ + exportsFields: Set; + + /** + * imports fields + */ + importsFields: Set; + + /** + * extensions + */ + extensions: Set; + + /** + * fileSystem + */ + fileSystem: FileSystem; + + /** + * unsafe cache + */ + unsafeCache: false | Cache; + + /** + * symlinks + */ + symlinks: boolean; + + /** + * resolver + */ + resolver?: Resolver; + + /** + * modules + */ + modules: (string | string[])[]; + + /** + * main fields + */ + mainFields: { name: string[]; forceRelative: boolean }[]; + + /** + * main files + */ + mainFiles: Set; + + /** + * plugins + */ + plugins: Plugin[]; + + /** + * pnp API + */ + pnpApi: null | PnpApi; + + /** + * roots + */ + roots: Set; + + /** + * fully specified + */ + fullySpecified: boolean; + + /** + * resolve to context + */ + resolveToContext: boolean; + + /** + * restrictions + */ + restrictions: Set; + + /** + * prefer relative + */ + preferRelative: boolean; + + /** + * prefer absolute + */ + preferAbsolute: boolean; + + /** + * tsconfig file path or config object + */ + tsconfig: string | boolean | TsconfigOptions; +} +declare interface ResolveOptionsResolverFactoryObject_2 { + /** + * A list of module alias configurations or an object which maps key to value + */ + alias?: AliasOptions | AliasOption[]; + + /** + * A list of module alias configurations or an object which maps key to value, applied only after modules option + */ + fallback?: AliasOptions | AliasOption[]; + + /** + * An object which maps extension to extension aliases + */ + extensionAlias?: ExtensionAliasOptions; + + /** + * Also apply `extensionAlias` to paths resolved through the package.json `exports` field. Off by default (Node.js-aligned); when enabled, matches TypeScript's behavior for packages that ship TS sources alongside compiled JS. + */ + extensionAliasForExports?: boolean; + + /** + * A list of alias fields in description files + */ + aliasFields?: (string | string[])[]; + + /** + * A function which decides whether a request should be cached or not. An object is passed with at least `path` and `request` properties. + */ + cachePredicate?: (predicate: ResolveRequest) => boolean; + + /** + * Whether or not the unsafeCache should include request context as part of the cache key. + */ + cacheWithContext?: boolean; + + /** + * A list of description files to read from + */ + descriptionFiles?: string[]; + + /** + * A list of exports field condition names. + */ + conditionNames?: string[]; + + /** + * Enforce that a extension from extensions must be used + */ + enforceExtension?: boolean; + + /** + * A list of exports fields in description files + */ + exportsFields?: (string | string[])[]; + + /** + * A list of imports fields in description files + */ + importsFields?: (string | string[])[]; + + /** + * A list of extensions which should be tried for files + */ + extensions?: string[]; + + /** + * The file system which should be used + */ + fileSystem: FileSystem; + + /** + * Use this cache object to unsafely cache the successful requests + */ + unsafeCache?: boolean | Cache; + + /** + * Resolve symlinks to their symlinked location + */ + symlinks?: boolean; + + /** + * A prepared Resolver to which the plugins are attached + */ + resolver?: Resolver; + + /** + * A list of directories to resolve modules from, can be absolute path or folder name + */ + modules?: string | string[]; + + /** + * A list of main fields in description files + */ + mainFields?: ( + | string + | string[] + | { name: string | string[]; forceRelative: boolean } + )[]; + + /** + * A list of main files in directories + */ + mainFiles?: string[]; + + /** + * A list of additional resolve plugins which should be applied + */ + plugins?: Plugin[]; + + /** + * A PnP API that should be used - null is "never", undefined is "auto" + */ + pnpApi?: null | PnpApi; + + /** + * A list of root paths + */ + roots?: string[]; + + /** + * The request is already fully specified and no extensions or directories are resolved for it + */ + fullySpecified?: boolean; + + /** + * Resolve to a context instead of a file + */ + resolveToContext?: boolean; + + /** + * A list of resolve restrictions + */ + restrictions?: (string | RegExp)[]; + + /** + * Use only the sync constraints of the file system calls + */ + useSyncFileSystemCalls?: boolean; + + /** + * Prefer to resolve module requests as relative requests before falling back to modules + */ + preferRelative?: boolean; + + /** + * Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots + */ + preferAbsolute?: boolean; + + /** + * TypeScript config file path or config object with configFile and references + */ + tsconfig?: string | boolean | TsconfigOptions; +} +type ResolveRequest = BaseResolveRequest & Partial; +declare abstract class Resolver { + fileSystem: FileSystem; + options: ResolveOptionsResolverFactoryObject_1; + pathCache: PathCacheFunctions; + hooks: KnownHooks; + ensureHook( + name: + | string + | AsyncSeriesBailHook< + [ResolveRequest, ResolveContext], + null | ResolveRequest + >, + ): AsyncSeriesBailHook< + [ResolveRequest, ResolveContext], + null | ResolveRequest + >; + getHook( + name: + | string + | AsyncSeriesBailHook< + [ResolveRequest, ResolveContext], + null | ResolveRequest + >, + ): AsyncSeriesBailHook< + [ResolveRequest, ResolveContext], + null | ResolveRequest + >; + resolveSync( + path: string, + request: string, + resolveContext?: ResolveContext, + ): string | false; + resolveSync( + context: Context, + path: string, + request: string, + resolveContext?: ResolveContext, + ): string | false; + resolvePromise( + path: string, + request: string, + resolveContext?: ResolveContext, + ): Promise; + resolvePromise( + context: Context, + path: string, + request: string, + resolveContext?: ResolveContext, + ): Promise; + resolve( + path: string, + request: string, + callback: ( + err: null | ErrorWithDetail, + res?: string | false, + req?: ResolveRequest, + ) => void, + ): void; + resolve( + path: string, + request: string, + resolveContext: ResolveContext, + callback: ( + err: null | ErrorWithDetail, + res?: string | false, + req?: ResolveRequest, + ) => void, + ): void; + resolve( + context: Context, + path: string, + request: string, + callback: ( + err: null | ErrorWithDetail, + res?: string | false, + req?: ResolveRequest, + ) => void, + ): void; + resolve( + context: Context, + path: string, + request: string, + resolveContext: ResolveContext, + callback: ( + err: null | ErrorWithDetail, + res?: string | false, + req?: ResolveRequest, + ) => void, + ): void; + doResolve( + hook: AsyncSeriesBailHook< + [ResolveRequest, ResolveContext], + null | ResolveRequest + >, + request: ResolveRequest, + message: null | string, + resolveContext: ResolveContext, + callback: (err?: null | Error, result?: ResolveRequest) => void, + ): void; + parse(identifier: string): ParsedIdentifier; + isModule(path: string): boolean; + isPrivate(path: string): boolean; + isDirectory(path: string): boolean; + normalize(path: string): string; + join(path: string, request: string): string; + dirname(path: string): string; + basename(path: string, suffix?: string): string; +} +declare abstract class StackEntry { + name?: string; + path: string | false; + request: string; + query: string; + fragment: string; + directory: boolean; + module: boolean; + parent?: StackEntry; + + /** + * Strings seeded by callers that still pass `stack: new Set([...])`. + * Propagated through the chain so deeper `doResolve` calls still see + * them during recursion checks. `undefined` in the common case so + * there is no extra work on the hot path. + */ + preSeeded?: Set; + + /** + * Walk the linked list looking for an entry with the same request shape. + * Set-compatible: callers that used `stack.has(entry)` keep working. + * NOTE: kept monomorphic on purpose. An earlier draft accepted a string + * query too (so pre-5.21 plugins keeping their own `Set` of + * seen entries could probe the live stack with the formatted form), + * but adding the second shape regressed `doResolve`'s heap profile by + * ~1 MiB / 200 resolves on stack-churn — V8 keeps a polymorphic + * call-site state for `parent.has(stackEntry)` once `has` has two + * argument shapes. Plugins that need string membership can reach for + * `[...stack].find(e => e.includes(formattedString))` via the + * `String`-method proxies on `StackEntry` instead. + */ + has(query: StackEntry): boolean; + + /** + * Number of entries on the stack (oldest-to-newest length). + */ + get size(): number; + + /** + * Human-readable form used in recursion error messages, logs, and the + * iterator above. Not memoized: caching would require an extra slot on + * every `StackEntry`, which costs heap even on resolves that never look + * at the formatted form. + */ + toString(): string; +} +declare interface Stat { + ( + path: PathLike, + callback: (err: null | NodeJS.ErrnoException, result?: IStats) => void, + ): void; + ( + path: PathLike, + options: undefined | (StatOptions & { bigint?: false }), + callback: (err: null | NodeJS.ErrnoException, result?: IStats) => void, + ): void; + ( + path: PathLike, + options: StatOptions & { bigint: true }, + callback: ( + err: null | NodeJS.ErrnoException, + result?: IBigIntStats, + ) => void, + ): void; + ( + path: PathLike, + options: undefined | StatOptions, + callback: ( + err: null | NodeJS.ErrnoException, + result?: IStats | IBigIntStats, + ) => void, + ): void; +} +declare interface StatOptions { + /** + * need bigint values + */ + bigint?: boolean; +} +declare interface StatSync { + (path: PathLike, options?: undefined): IStats; + ( + path: PathLike, + options?: StatSyncOptions & { bigint?: false; throwIfNoEntry: false }, + ): undefined | IStats; + ( + path: PathLike, + options: StatSyncOptions & { bigint: true; throwIfNoEntry: false }, + ): undefined | IBigIntStats; + (path: PathLike, options?: StatSyncOptions & { bigint?: false }): IStats; + (path: PathLike, options: StatSyncOptions & { bigint: true }): IBigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { bigint: boolean; throwIfNoEntry?: false }, + ): IStats | IBigIntStats; + ( + path: PathLike, + options?: StatSyncOptions, + ): undefined | IStats | IBigIntStats; +} +declare interface StatSyncOptions { + /** + * need bigint values + */ + bigint?: boolean; + + /** + * throw if no entry + */ + throwIfNoEntry?: boolean; +} +declare interface SyncFileSystem { + /** + * read file sync method + */ + readFileSync: ReadFileSync; + + /** + * read dir sync method + */ + readdirSync: ReaddirSync; + + /** + * read json sync method + */ + readJsonSync?: (pathOrFileDescription: PathOrFileDescriptor) => JsonObject; + + /** + * read link sync method + */ + readlinkSync: ReadlinkSync; + + /** + * lstat sync method + */ + lstatSync?: LStatSync; + + /** + * stat sync method + */ + statSync: StatSync; + + /** + * real path sync method + */ + realpathSync?: RealPathSync; +} +declare interface TsconfigOptions { + /** + * A relative path to the tsconfig file based on cwd, or an absolute path of tsconfig file + */ + configFile?: string; + + /** + * References to other tsconfig files. 'auto' inherits from TypeScript config, or an array of relative/absolute paths + */ + references?: string[] | "auto"; + + /** + * Override baseUrl from tsconfig.json. If provided, this value will be used instead of the baseUrl in the tsconfig file + */ + baseUrl?: string; +} +declare interface TsconfigPathsData { + /** + * tsconfig file data + */ + alias: CompiledAliasOptions; + + /** + * tsconfig file data + */ + modules: string[]; +} +declare interface TsconfigPathsMap { + /** + * main tsconfig paths data + */ + main: TsconfigPathsData; + + /** + * main tsconfig base URL (absolute path) + */ + mainContext: string; + + /** + * referenced tsconfig paths data mapped by baseUrl + */ + refs: { [index: string]: TsconfigPathsData }; + + /** + * all contexts (main + refs) for quick lookup + */ + allContexts: { [index: string]: TsconfigPathsData }; + + /** + * precomputed `Object.keys(allContexts)` — read-only; used on the `_selectPathsDataForContext` hot path + */ + contextList: string[]; + + /** + * file dependencies + */ + fileDependencies: Set; +} +declare class TsconfigPathsPlugin { + constructor(configFileOrOptions: string | true | TsconfigOptions); + isAutoConfigFile: boolean; + configFile: string; + references: "auto" | TsconfigReference[]; + baseUrl?: string; + apply(resolver: Resolver): void; +} +declare interface TsconfigReference { + /** + * Path to the referenced project + */ + path: string; +} +declare interface URL_url extends URL_Import {} +declare interface WriteOnlySet { + add: (item: T) => void; +} +declare function exports( + context: Context, + path: string, + request: string, + resolveContext: ResolveContext, + callback: ( + err: null | ErrorWithDetail, + res?: string | false, + req?: ResolveRequest, + ) => void, +): void; +declare function exports( + context: Context, + path: string, + request: string, + callback: ( + err: null | ErrorWithDetail, + res?: string | false, + req?: ResolveRequest, + ) => void, +): void; +declare function exports( + path: string, + request: string, + resolveContext: ResolveContext, + callback: ( + err: null | ErrorWithDetail, + res?: string | false, + req?: ResolveRequest, + ) => void, +): void; +declare function exports( + path: string, + request: string, + callback: ( + err: null | ErrorWithDetail, + res?: string | false, + req?: ResolveRequest, + ) => void, +): void; +declare namespace exports { + export const sync: ResolveFunction; + export const promise: ResolveFunctionPromise; + export function create( + options: ResolveOptionsOptionalFS, + ): ResolveFunctionAsync; + export namespace create { + export const sync: (options: ResolveOptionsOptionalFS) => ResolveFunction; + export const promise: ( + options: ResolveOptionsOptionalFS, + ) => ResolveFunctionPromise; + } + export namespace ResolverFactory { + export let createResolver: ( + options: ResolveOptionsResolverFactoryObject_2, + ) => Resolver; + } + export const forEachBail: ( + array: T[], + iterator: Iterator, + callback: (err?: null | Error, result?: null | Z, i?: number) => void, + ) => void; + export type ResolveCallback = ( + err: null | ErrorWithDetail, + res?: string | false, + req?: ResolveRequest, + ) => void; + export { + CachedInputFileSystem, + CloneBasenamePlugin, + LogInfoPlugin, + TsconfigPathsPlugin, + ResolveOptionsOptionalFS, + BaseFileSystem, + PnpApi, + Resolver, + Context, + FileSystem, + ResolveContext, + ResolveRequest, + SyncFileSystem, + Plugin, + ResolveOptionsResolverFactoryObject_2 as ResolveOptions, + ResolveFunctionAsync, + ResolveFunction, + ResolveFunctionPromise, + }; +} + +export = exports; diff --git a/client/node_modules/fraction.js/CHANGELOG.md b/client/node_modules/fraction.js/CHANGELOG.md new file mode 100644 index 0000000..ec492a7 --- /dev/null +++ b/client/node_modules/fraction.js/CHANGELOG.md @@ -0,0 +1,38 @@ +# CHANGELOG + +v5.2.2 + - Improved documentation and removed unecessary check + +v5.2.1: + - 2bb7b05: Added negative sign check + +v5.2: + - 6f9d124: Implemented log and improved simplify + - b773e7a: Added named export to TS definition + - 70304f9: Fixed merge conflict + - 3b940d3: Implemented other comparing functions + - 10acdfc: Update README.md + - ba41d00: Update README.md + - 73ded97: Update README.md + - acabc39: Fixed param parsing + +v5.0.5: + - 2c9d4c2: Improved roundTo() and param parser + +v5.0.4: + - 39e61e7: Fixed bignum param passing + +v5.0.3: + - 7d9a3ec: Upgraded bundler for code quality + +v5.0.2: + - c64b1d6: fixed esm export + +v5.0.1: + - e440f9c: Fixed CJS export + - 9bbdd29: Fixed CJS export + +v5.0.0: + - ac7cd06: Fixed readme + - 33cc9e5: Added crude build + - 1adcc76: Release breaking v5.0. Fraction.js now builds on BigInt. The API stays the same as v4, except that the object attributes `n`, `d`, and `s`, are not Number but BigInt and may break code that directly accesses these attributes. \ No newline at end of file diff --git a/client/node_modules/fraction.js/LICENSE b/client/node_modules/fraction.js/LICENSE new file mode 100644 index 0000000..8741015 --- /dev/null +++ b/client/node_modules/fraction.js/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Robert Eisele + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/client/node_modules/fraction.js/README.md b/client/node_modules/fraction.js/README.md new file mode 100644 index 0000000..e53343e --- /dev/null +++ b/client/node_modules/fraction.js/README.md @@ -0,0 +1,520 @@ +# Fraction.js - ℚ in JavaScript + +[![NPM Package](https://img.shields.io/npm/v/fraction.js.svg?style=flat)](https://npmjs.org/package/fraction.js "View this project on npm") +[![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg)](http://opensource.org/licenses/MIT) + +Do you find the limitations of floating-point arithmetic frustrating, especially when rational and irrational numbers like π or √2 are stored within the same finite precision? This can lead to avoidable inaccuracies such as: + +```javascript +1 / 98 * 98 // Results in 0.9999999999999999 +``` + +For applications requiring higher precision or where working with fractions is preferable, consider incorporating *Fraction.js* into your project. + +The library effectively addresses precision issues, as demonstrated below: + +```javascript +Fraction(1).div(98).mul(98) // Returns 1 +``` + +*Fraction.js* uses a `BigInt` representation for both the numerator and denominator, ensuring minimal performance overhead while maximizing accuracy. Its design is optimized for precision, making it an ideal choice as a foundational library for other math tools, such as [Polynomial.js](https://github.com/rawify/Polynomial.js) and [Math.js](https://github.com/josdejong/mathjs). + +## Convert Decimal to Fraction + +One of the core features of *Fraction.js* is its ability to seamlessly convert decimal numbers into fractions. + +```javascript +let x = new Fraction(1.88); +let res = x.toFraction(true); // Returns "1 22/25" as a string +``` + +This is particularly useful when you need precise fraction representations instead of dealing with the limitations of floating-point arithmetic. What if you allow some error tolerance? + +```javascript +let x = new Fraction(0.33333); +let res = x.simplify(0.001) // Error < 0.001 + .toFraction(); // Returns "1/3" as a string +``` + +## Precision + +As native `BigInt` support in JavaScript becomes more common, libraries like *Fraction.js* use it to handle calculations with higher precision. This improves the speed and accuracy of math operations with large numbers, providing a better solution for tasks that need more precision than floating-point numbers can offer. + +## Examples / Motivation + +A simple example of using *Fraction.js* might look like this: + +```javascript +var f = new Fraction("9.4'31'"); // 9.4313131313131... +f.mul([-4, 3]).mod("4.'8'"); // 4.88888888888888... +``` + +The result can then be displayed as: + +```javascript +console.log(f.toFraction()); // -4154 / 1485 +``` + +Additionally, you can access the internal attributes of the fraction, such as the sign (s), numerator (n), and denominator (d). Keep in mind that these values are stored as `BigInt`: + +```javascript +Number(f.s) * Number(f.n) / Number(f.d) = -1 * 4154 / 1485 = -2.797306... +``` + +If you attempted to calculate this manually using floating-point arithmetic, you'd get something like: + +```javascript +(9.4313131 * (-4 / 3)) % 4.888888 = -2.797308133... +``` + +While the result is reasonably close, it’s not as accurate as the fraction-based approach that *Fraction.js* provides, especially when dealing with repeating decimals or complex operations. This highlights the value of precision that the library brings. + +### Laplace Probability + +Here's a straightforward example of using *Fraction.js* to calculate probabilities. Let's determine the probability of rolling a specific outcome on a fair die: + +- **P({3})**: The probability of rolling a 3. +- **P({1, 4})**: The probability of rolling either 1 or 4. +- **P({2, 4, 6})**: The probability of rolling 2, 4, or 6. + +#### P({3}): + +```javascript +var p = new Fraction([3].length, 6).toString(); // "0.1(6)" +``` + +#### P({1, 4}): + +```javascript +var p = new Fraction([1, 4].length, 6).toString(); // "0.(3)" +``` + +#### P({2, 4, 6}): + +```javascript +var p = new Fraction([2, 4, 6].length, 6).toString(); // "0.5" +``` + +### Convert degrees/minutes/seconds to precise rational representation: + +57+45/60+17/3600 + +```javascript +var deg = 57; // 57° +var min = 45; // 45 Minutes +var sec = 17; // 17 Seconds + +new Fraction(deg).add(min, 60).add(sec, 3600).toString() // -> 57.7547(2) +``` + + +### Rational approximation of irrational numbers + +To approximate a number like *sqrt(5) - 2* with a numerator and denominator, you can reformat the equation as follows: *pow(n / d + 2, 2) = 5*. + +Then the following algorithm will generate the rational number besides the binary representation. + +```javascript +var x = "/", s = ""; + +var a = new Fraction(0), + b = new Fraction(1); +for (var n = 0; n <= 10; n++) { + + var c = a.add(b).div(2); + + console.log(n + "\t" + a + "\t" + b + "\t" + c + "\t" + x); + + if (c.add(2).pow(2).valueOf() < 5) { + a = c; + x = "1"; + } else { + b = c; + x = "0"; + } + s+= x; +} +console.log(s) +``` + +The result is + +``` +n a[n] b[n] c[n] x[n] +0 0/1 1/1 1/2 / +1 0/1 1/2 1/4 0 +2 0/1 1/4 1/8 0 +3 1/8 1/4 3/16 1 +4 3/16 1/4 7/32 1 +5 7/32 1/4 15/64 1 +6 15/64 1/4 31/128 1 +7 15/64 31/128 61/256 0 +8 15/64 61/256 121/512 0 +9 15/64 121/512 241/1024 0 +10 241/1024 121/512 483/2048 1 +``` + +Thus the approximation after 11 iterations of the bisection method is *483 / 2048* and the binary representation is 0.00111100011 (see [WolframAlpha](http://www.wolframalpha.com/input/?i=sqrt%285%29-2+binary)) + +I published another example on how to approximate PI with fraction.js on my [blog](https://raw.org/article/rational-numbers-in-javascript/) (Still not the best idea to approximate irrational numbers, but it illustrates the capabilities of Fraction.js perfectly). + + +### Get the exact fractional part of a number + +```javascript +var f = new Fraction("-6.(3416)"); +console.log(f.mod(1).abs().toFraction()); // = 3416/9999 +``` + +### Mathematical correct modulo + +The behaviour on negative congruences is different to most modulo implementations in computer science. Even the *mod()* function of Fraction.js behaves in the typical way. To solve the problem of having the mathematical correct modulo with Fraction.js you could come up with this: + +```javascript +var a = -1; +var b = 10.99; + +console.log(new Fraction(a) + .mod(b)); // Not correct, usual Modulo + +console.log(new Fraction(a) + .mod(b).add(b).mod(b)); // Correct! Mathematical Modulo +``` + +fmod() imprecision circumvented +--- +It turns out that Fraction.js outperforms almost any fmod() implementation, including JavaScript itself, [php.js](http://phpjs.org/functions/fmod/), C++, Python, Java and even Wolframalpha due to the fact that numbers like 0.05, 0.1, ... are infinite decimal in base 2. + +The equation *fmod(4.55, 0.05)* gives *0.04999999999999957*, wolframalpha says *1/20*. The correct answer should be **zero**, as 0.05 divides 4.55 without any remainder. + + +## Parser + +Any function (see below) as well as the constructor of the *Fraction* class parses its input and reduce it to the smallest term. + +You can pass either Arrays, Objects, Integers, Doubles or Strings. + +### Arrays / Objects + +```javascript +new Fraction(numerator, denominator); +new Fraction([numerator, denominator]); +new Fraction({n: numerator, d: denominator}); +``` + +### Integers + +```javascript +new Fraction(123); +``` + +### Doubles + +```javascript +new Fraction(55.4); +``` + +**Note:** If you pass a double as it is, Fraction.js will perform a number analysis based on Farey Sequences. If you concern performance, cache Fraction.js objects and pass arrays/objects. + +The method is really precise, but too large exact numbers, like 1234567.9991829 will result in a wrong approximation. If you want to keep the number as it is, convert it to a string, as the string parser will not perform any further observations. If you have problems with the approximation, in the file `examples/approx.js` is a different approximation algorithm, which might work better in some more specific use-cases. + + +### Strings + +```javascript +new Fraction("123.45"); +new Fraction("123/45"); // A rational number represented as two decimals, separated by a slash +new Fraction("123:45"); // A rational number represented as two decimals, separated by a colon +new Fraction("4 123/45"); // A rational number represented as a whole number and a fraction +new Fraction("123.'456'"); // Note the quotes, see below! +new Fraction("123.(456)"); // Note the brackets, see below! +new Fraction("123.45'6'"); // Note the quotes, see below! +new Fraction("123.45(6)"); // Note the brackets, see below! +``` + +### Two arguments + +```javascript +new Fraction(3, 2); // 3/2 = 1.5 +``` + +### Repeating decimal places + +*Fraction.js* can easily handle repeating decimal places. For example *1/3* is *0.3333...*. There is only one repeating digit. As you can see in the examples above, you can pass a number like *1/3* as "0.'3'" or "0.(3)", which are synonym. There are no tests to parse something like 0.166666666 to 1/6! If you really want to handle this number, wrap around brackets on your own with the function below for example: 0.1(66666666) + +Assume you want to divide 123.32 / 33.6(567). [WolframAlpha](http://www.wolframalpha.com/input/?i=123.32+%2F+%2812453%2F370%29) states that you'll get a period of 1776 digits. *Fraction.js* comes to the same result. Give it a try: + +```javascript +var f = new Fraction("123.32"); +console.log("Bam: " + f.div("33.6(567)")); +``` + +To automatically make a number like "0.123123123" to something more Fraction.js friendly like "0.(123)", I hacked this little brute force algorithm in a 10 minutes. Improvements are welcome... + +```javascript +function formatDecimal(str) { + + var comma, pre, offset, pad, times, repeat; + + if (-1 === (comma = str.indexOf("."))) + return str; + + pre = str.substr(0, comma + 1); + str = str.substr(comma + 1); + + for (var i = 0; i < str.length; i++) { + + offset = str.substr(0, i); + + for (var j = 0; j < 5; j++) { + + pad = str.substr(i, j + 1); + + times = Math.ceil((str.length - offset.length) / pad.length); + + repeat = new Array(times + 1).join(pad); // Silly String.repeat hack + + if (0 === (offset + repeat).indexOf(str)) { + return pre + offset + "(" + pad + ")"; + } + } + } + return null; +} + +var f, x = formatDecimal("13.0123123123"); // = 13.0(123) +if (x !== null) { + f = new Fraction(x); +} +``` + +## Attributes + + +The Fraction object allows direct access to the numerator, denominator and sign attributes. It is ensured that only the sign-attribute holds sign information so that a sign comparison is only necessary against this attribute. + +```javascript +var f = new Fraction('-1/2'); +console.log(f.n); // Numerator: 1 +console.log(f.d); // Denominator: 2 +console.log(f.s); // Sign: -1 +``` + + +## Functions + +### Fraction abs() + +Returns the actual number without any sign information + +### Fraction neg() + +Returns the actual number with flipped sign in order to get the additive inverse + +### Fraction add(n) + +Returns the sum of the actual number and the parameter n + +### Fraction sub(n) + +Returns the difference of the actual number and the parameter n + +### Fraction mul(n) + +Returns the product of the actual number and the parameter n + +### Fraction div(n) + +Returns the quotient of the actual number and the parameter n + +### Fraction pow(exp) + +Returns the power of the actual number, raised to an possible rational exponent. If the result becomes non-rational the function returns `null`. + +### Fraction log(base) + +Returns the logarithm of the actual number to a given rational base. If the result becomes non-rational the function returns `null`. + +### Fraction mod(n) + +Returns the modulus (rest of the division) of the actual object and n (this % n). It's a much more precise [fmod()](#fmod-impreciseness-circumvented) if you like. Please note that *mod()* is just like the modulo operator of most programming languages. If you want a mathematical correct modulo, see [here](#mathematical-correct-modulo). + +### Fraction mod() + +Returns the modulus (rest of the division) of the actual object (numerator mod denominator) + +### Fraction gcd(n) + +Returns the fractional greatest common divisor + +### Fraction lcm(n) + +Returns the fractional least common multiple + +### Fraction ceil([places=0-16]) + +Returns the ceiling of a rational number with Math.ceil + +### Fraction floor([places=0-16]) + +Returns the floor of a rational number with Math.floor + +### Fraction round([places=0-16]) + +Returns the rational number rounded with Math.round + +### Fraction roundTo(multiple) + +Rounds a fraction to the closest multiple of another fraction. + +### Fraction inverse() + +Returns the multiplicative inverse of the actual number (n / d becomes d / n) in order to get the reciprocal + +### Fraction simplify([eps=0.001]) + +Simplifies the rational number under a certain error threshold. Ex. `0.333` will be `1/3` with `eps=0.001` + +### boolean equals(n) + +Check if two rational numbers are equal + +### boolean lt(n) + +Check if this rational number is less than another + +### boolean lte(n) + +Check if this rational number is less than or equal another + +### boolean gt(n) + +Check if this rational number is greater than another + +### boolean gte(n) + +Check if this rational number is greater than or equal another + +### int compare(n) + +Compare two numbers. +``` +result < 0: n is greater than actual number +result > 0: n is smaller than actual number +result = 0: n is equal to the actual number +``` + +### boolean divisible(n) + +Check if two numbers are divisible (n divides this) + +### double valueOf() + +Returns a decimal representation of the fraction + +### String toString([decimalPlaces=15]) + +Generates an exact string representation of the given object. For repeating decimal places, digits within repeating cycles are enclosed in parentheses, e.g., `1/3 = "0.(3)"`. For other numbers, the string will include up to the specified `decimalPlaces` significant digits, including any trailing zeros if truncation occurs. For example, `1/2` will be represented as `"0.5"`, without additional trailing zeros. + +**Note:** Since both `valueOf()` and `toString()` are provided, `toString()` will only be invoked implicitly when the object is used in a string context. For instance, when using the plus operator like `"123" + new Fraction`, `valueOf()` will be called first, as JavaScript attempts to combine primitives before concatenating them, with the string type taking precedence. However, `alert(new Fraction)` or `String(new Fraction)` will behave as expected. To ensure specific behavior, explicitly call either `toString()` or `valueOf()`. + +### String toLatex(showMixed=false) + +Generates an exact LaTeX representation of the actual object. You can see a [live demo](https://raw.org/article/rational-numbers-in-javascript/) on my blog. + +The optional boolean parameter indicates if you want to show the a mixed fraction. "1 1/3" instead of "4/3" + +### String toFraction(showMixed=false) + +Gets a string representation of the fraction + +The optional boolean parameter indicates if you want to showa mixed fraction. "1 1/3" instead of "4/3" + +### Array toContinued() + +Gets an array of the fraction represented as a continued fraction. The first element always contains the whole part. + +```javascript +var f = new Fraction('88/33'); +var c = f.toContinued(); // [2, 1, 2] +``` + +### Fraction clone() + +Creates a copy of the actual Fraction object + + +## Exceptions + +If a really hard error occurs (parsing error, division by zero), *Fraction.js* throws exceptions! Please make sure you handle them correctly. + + +## Installation + +You can install `Fraction.js` via npm: + +```bash +npm install fraction.js +``` + +Or with yarn: + +```bash +yarn add fraction.js +``` + +Alternatively, download or clone the repository: + +```bash +git clone https://github.com/rawify/Fraction.js +``` + +## Usage + +Include the `fraction.min.js` file in your project: + +```html + + +``` + +Or in a Node.js project: + +```javascript +const Fraction = require('fraction.js'); +``` + +or + +```javascript +import Fraction from 'fraction.js'; +``` + + +## Coding Style + +As every library I publish, Fraction.js is also built to be as small as possible after compressing it with Google Closure Compiler in advanced mode. Thus the coding style orientates a little on maxing-out the compression rate. Please make sure you keep this style if you plan to extend the library. + +## Building the library + +After cloning the Git repository run: + +```bash +npm install +npm run build +``` + +## Run a test + +Testing the source against the shipped test suite is as easy as + +```bash +npm run test +``` + +## Copyright and Licensing + +Copyright (c) 2025, [Robert Eisele](https://raw.org/) +Licensed under the MIT license. diff --git a/client/node_modules/fraction.js/dist/fraction.js b/client/node_modules/fraction.js/dist/fraction.js new file mode 100644 index 0000000..816d5db --- /dev/null +++ b/client/node_modules/fraction.js/dist/fraction.js @@ -0,0 +1,1045 @@ +'use strict'; + +/** + * + * This class offers the possibility to calculate fractions. + * You can pass a fraction in different formats. Either as array, as double, as string or as an integer. + * + * Array/Object form + * [ 0 => , 1 => ] + * { n => , d => } + * + * Integer form + * - Single integer value as BigInt or Number + * + * Double form + * - Single double value as Number + * + * String form + * 123.456 - a simple double + * 123/456 - a string fraction + * 123.'456' - a double with repeating decimal places + * 123.(456) - synonym + * 123.45'6' - a double with repeating last place + * 123.45(6) - synonym + * + * Example: + * let f = new Fraction("9.4'31'"); + * f.mul([-4, 3]).div(4.9); + * + */ + +// Set Identity function to downgrade BigInt to Number if needed +if (typeof BigInt === 'undefined') BigInt = function (n) { if (isNaN(n)) throw new Error(""); return n; }; + +const C_ZERO = BigInt(0); +const C_ONE = BigInt(1); +const C_TWO = BigInt(2); +const C_THREE = BigInt(3); +const C_FIVE = BigInt(5); +const C_TEN = BigInt(10); +const MAX_INTEGER = BigInt(Number.MAX_SAFE_INTEGER); + +// Maximum search depth for cyclic rational numbers. 2000 should be more than enough. +// Example: 1/7 = 0.(142857) has 6 repeating decimal places. +// If MAX_CYCLE_LEN gets reduced, long cycles will not be detected and toString() only gets the first 10 digits +const MAX_CYCLE_LEN = 2000; + +// Parsed data to avoid calling "new" all the time +const P = { + "s": C_ONE, + "n": C_ZERO, + "d": C_ONE +}; + +function assign(n, s) { + + try { + n = BigInt(n); + } catch (e) { + throw InvalidParameter(); + } + return n * s; +} + +function ifloor(x) { + return typeof x === 'bigint' ? x : Math.floor(x); +} + +// Creates a new Fraction internally without the need of the bulky constructor +function newFraction(n, d) { + + if (d === C_ZERO) { + throw DivisionByZero(); + } + + const f = Object.create(Fraction.prototype); + f["s"] = n < C_ZERO ? -C_ONE : C_ONE; + + n = n < C_ZERO ? -n : n; + + const a = gcd(n, d); + + f["n"] = n / a; + f["d"] = d / a; + return f; +} + +const FACTORSTEPS = [C_TWO * C_TWO, C_TWO, C_TWO * C_TWO, C_TWO, C_TWO * C_TWO, C_TWO * C_THREE, C_TWO, C_TWO * C_THREE]; // repeats +function factorize(n) { + + const factors = Object.create(null); + if (n <= C_ONE) { + factors[n] = C_ONE; + return factors; + } + + const add = (p) => { factors[p] = (factors[p] || C_ZERO) + C_ONE; }; + + while (n % C_TWO === C_ZERO) { add(C_TWO); n /= C_TWO; } + while (n % C_THREE === C_ZERO) { add(C_THREE); n /= C_THREE; } + while (n % C_FIVE === C_ZERO) { add(C_FIVE); n /= C_FIVE; } + + // 30-wheel trial division: test only residues coprime to 2*3*5 + // Residue step pattern after 5: 7,11,13,17,19,23,29,31, ... + for (let si = 0, p = C_TWO + C_FIVE; p * p <= n;) { + while (n % p === C_ZERO) { add(p); n /= p; } + p += FACTORSTEPS[si]; + si = (si + 1) & 7; // fast modulo 8 + } + if (n > C_ONE) add(n); + return factors; +} + +const parse = function (p1, p2) { + + let n = C_ZERO, d = C_ONE, s = C_ONE; + + if (p1 === undefined || p1 === null) { // No argument + /* void */ + } else if (p2 !== undefined) { // Two arguments + + if (typeof p1 === "bigint") { + n = p1; + } else if (isNaN(p1)) { + throw InvalidParameter(); + } else if (p1 % 1 !== 0) { + throw NonIntegerParameter(); + } else { + n = BigInt(p1); + } + + if (typeof p2 === "bigint") { + d = p2; + } else if (isNaN(p2)) { + throw InvalidParameter(); + } else if (p2 % 1 !== 0) { + throw NonIntegerParameter(); + } else { + d = BigInt(p2); + } + + s = n * d; + + } else if (typeof p1 === "object") { + if ("d" in p1 && "n" in p1) { + n = BigInt(p1["n"]); + d = BigInt(p1["d"]); + if ("s" in p1) + n *= BigInt(p1["s"]); + } else if (0 in p1) { + n = BigInt(p1[0]); + if (1 in p1) + d = BigInt(p1[1]); + } else if (typeof p1 === "bigint") { + n = p1; + } else { + throw InvalidParameter(); + } + s = n * d; + } else if (typeof p1 === "number") { + + if (isNaN(p1)) { + throw InvalidParameter(); + } + + if (p1 < 0) { + s = -C_ONE; + p1 = -p1; + } + + if (p1 % 1 === 0) { + n = BigInt(p1); + } else { + + let z = 1; + + let A = 0, B = 1; + let C = 1, D = 1; + + let N = 10000000; + + if (p1 >= 1) { + z = 10 ** Math.floor(1 + Math.log10(p1)); + p1 /= z; + } + + // Using Farey Sequences + + while (B <= N && D <= N) { + let M = (A + C) / (B + D); + + if (p1 === M) { + if (B + D <= N) { + n = A + C; + d = B + D; + } else if (D > B) { + n = C; + d = D; + } else { + n = A; + d = B; + } + break; + + } else { + + if (p1 > M) { + A += C; + B += D; + } else { + C += A; + D += B; + } + + if (B > N) { + n = C; + d = D; + } else { + n = A; + d = B; + } + } + } + n = BigInt(n) * BigInt(z); + d = BigInt(d); + } + + } else if (typeof p1 === "string") { + + let ndx = 0; + + let v = C_ZERO, w = C_ZERO, x = C_ZERO, y = C_ONE, z = C_ONE; + + let match = p1.replace(/_/g, '').match(/\d+|./g); + + if (match === null) + throw InvalidParameter(); + + if (match[ndx] === '-') {// Check for minus sign at the beginning + s = -C_ONE; + ndx++; + } else if (match[ndx] === '+') {// Check for plus sign at the beginning + ndx++; + } + + if (match.length === ndx + 1) { // Check if it's just a simple number "1234" + w = assign(match[ndx++], s); + } else if (match[ndx + 1] === '.' || match[ndx] === '.') { // Check if it's a decimal number + + if (match[ndx] !== '.') { // Handle 0.5 and .5 + v = assign(match[ndx++], s); + } + ndx++; + + // Check for decimal places + if (ndx + 1 === match.length || match[ndx + 1] === '(' && match[ndx + 3] === ')' || match[ndx + 1] === "'" && match[ndx + 3] === "'") { + w = assign(match[ndx], s); + y = C_TEN ** BigInt(match[ndx].length); + ndx++; + } + + // Check for repeating places + if (match[ndx] === '(' && match[ndx + 2] === ')' || match[ndx] === "'" && match[ndx + 2] === "'") { + x = assign(match[ndx + 1], s); + z = C_TEN ** BigInt(match[ndx + 1].length) - C_ONE; + ndx += 3; + } + + } else if (match[ndx + 1] === '/' || match[ndx + 1] === ':') { // Check for a simple fraction "123/456" or "123:456" + w = assign(match[ndx], s); + y = assign(match[ndx + 2], C_ONE); + ndx += 3; + } else if (match[ndx + 3] === '/' && match[ndx + 1] === ' ') { // Check for a complex fraction "123 1/2" + v = assign(match[ndx], s); + w = assign(match[ndx + 2], s); + y = assign(match[ndx + 4], C_ONE); + ndx += 5; + } + + if (match.length <= ndx) { // Check for more tokens on the stack + d = y * z; + s = /* void */ + n = x + d * v + z * w; + } else { + throw InvalidParameter(); + } + + } else if (typeof p1 === "bigint") { + n = p1; + s = p1; + d = C_ONE; + } else { + throw InvalidParameter(); + } + + if (d === C_ZERO) { + throw DivisionByZero(); + } + + P["s"] = s < C_ZERO ? -C_ONE : C_ONE; + P["n"] = n < C_ZERO ? -n : n; + P["d"] = d < C_ZERO ? -d : d; +}; + +function modpow(b, e, m) { + + let r = C_ONE; + for (; e > C_ZERO; b = (b * b) % m, e >>= C_ONE) { + + if (e & C_ONE) { + r = (r * b) % m; + } + } + return r; +} + +function cycleLen(n, d) { + + for (; d % C_TWO === C_ZERO; + d /= C_TWO) { + } + + for (; d % C_FIVE === C_ZERO; + d /= C_FIVE) { + } + + if (d === C_ONE) // Catch non-cyclic numbers + return C_ZERO; + + // If we would like to compute really large numbers quicker, we could make use of Fermat's little theorem: + // 10^(d-1) % d == 1 + // However, we don't need such large numbers and MAX_CYCLE_LEN should be the capstone, + // as we want to translate the numbers to strings. + + let rem = C_TEN % d; + let t = 1; + + for (; rem !== C_ONE; t++) { + rem = rem * C_TEN % d; + + if (t > MAX_CYCLE_LEN) + return C_ZERO; // Returning 0 here means that we don't print it as a cyclic number. It's likely that the answer is `d-1` + } + return BigInt(t); +} + +function cycleStart(n, d, len) { + + let rem1 = C_ONE; + let rem2 = modpow(C_TEN, len, d); + + for (let t = 0; t < 300; t++) { // s < ~log10(Number.MAX_VALUE) + // Solve 10^s == 10^(s+t) (mod d) + + if (rem1 === rem2) + return BigInt(t); + + rem1 = rem1 * C_TEN % d; + rem2 = rem2 * C_TEN % d; + } + return 0; +} + +function gcd(a, b) { + + if (!a) + return b; + if (!b) + return a; + + while (1) { + a %= b; + if (!a) + return b; + b %= a; + if (!b) + return a; + } +} + +/** + * Module constructor + * + * @constructor + * @param {number|Fraction=} a + * @param {number=} b + */ +function Fraction(a, b) { + + parse(a, b); + + if (this instanceof Fraction) { + a = gcd(P["d"], P["n"]); // Abuse a + this["s"] = P["s"]; + this["n"] = P["n"] / a; + this["d"] = P["d"] / a; + } else { + return newFraction(P['s'] * P['n'], P['d']); + } +} + +const DivisionByZero = function () { return new Error("Division by Zero"); }; +const InvalidParameter = function () { return new Error("Invalid argument"); }; +const NonIntegerParameter = function () { return new Error("Parameters must be integer"); }; + +Fraction.prototype = { + + "s": C_ONE, + "n": C_ZERO, + "d": C_ONE, + + /** + * Calculates the absolute value + * + * Ex: new Fraction(-4).abs() => 4 + **/ + "abs": function () { + + return newFraction(this["n"], this["d"]); + }, + + /** + * Inverts the sign of the current fraction + * + * Ex: new Fraction(-4).neg() => 4 + **/ + "neg": function () { + + return newFraction(-this["s"] * this["n"], this["d"]); + }, + + /** + * Adds two rational numbers + * + * Ex: new Fraction({n: 2, d: 3}).add("14.9") => 467 / 30 + **/ + "add": function (a, b) { + + parse(a, b); + return newFraction( + this["s"] * this["n"] * P["d"] + P["s"] * this["d"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Subtracts two rational numbers + * + * Ex: new Fraction({n: 2, d: 3}).add("14.9") => -427 / 30 + **/ + "sub": function (a, b) { + + parse(a, b); + return newFraction( + this["s"] * this["n"] * P["d"] - P["s"] * this["d"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Multiplies two rational numbers + * + * Ex: new Fraction("-17.(345)").mul(3) => 5776 / 111 + **/ + "mul": function (a, b) { + + parse(a, b); + return newFraction( + this["s"] * P["s"] * this["n"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Divides two rational numbers + * + * Ex: new Fraction("-17.(345)").inverse().div(3) + **/ + "div": function (a, b) { + + parse(a, b); + return newFraction( + this["s"] * P["s"] * this["n"] * P["d"], + this["d"] * P["n"] + ); + }, + + /** + * Clones the actual object + * + * Ex: new Fraction("-17.(345)").clone() + **/ + "clone": function () { + return newFraction(this['s'] * this['n'], this['d']); + }, + + /** + * Calculates the modulo of two rational numbers - a more precise fmod + * + * Ex: new Fraction('4.(3)').mod([7, 8]) => (13/3) % (7/8) = (5/6) + * Ex: new Fraction(20, 10).mod().equals(0) ? "is Integer" + **/ + "mod": function (a, b) { + + if (a === undefined) { + return newFraction(this["s"] * this["n"] % this["d"], C_ONE); + } + + parse(a, b); + if (C_ZERO === P["n"] * this["d"]) { + throw DivisionByZero(); + } + + /** + * I derived the rational modulo similar to the modulo for integers + * + * https://raw.org/book/analysis/rational-numbers/ + * + * n1/d1 = (n2/d2) * q + r, where 0 ≤ r < n2/d2 + * => d2 * n1 = n2 * d1 * q + d1 * d2 * r + * => r = (d2 * n1 - n2 * d1 * q) / (d1 * d2) + * = (d2 * n1 - n2 * d1 * floor((d2 * n1) / (n2 * d1))) / (d1 * d2) + * = ((d2 * n1) % (n2 * d1)) / (d1 * d2) + */ + return newFraction( + this["s"] * (P["d"] * this["n"]) % (P["n"] * this["d"]), + P["d"] * this["d"]); + }, + + /** + * Calculates the fractional gcd of two rational numbers + * + * Ex: new Fraction(5,8).gcd(3,7) => 1/56 + */ + "gcd": function (a, b) { + + parse(a, b); + + // https://raw.org/book/analysis/rational-numbers/ + // gcd(a / b, c / d) = gcd(a, c) / lcm(b, d) + + return newFraction(gcd(P["n"], this["n"]) * gcd(P["d"], this["d"]), P["d"] * this["d"]); + }, + + /** + * Calculates the fractional lcm of two rational numbers + * + * Ex: new Fraction(5,8).lcm(3,7) => 15 + */ + "lcm": function (a, b) { + + parse(a, b); + + // https://raw.org/book/analysis/rational-numbers/ + // lcm(a / b, c / d) = lcm(a, c) / gcd(b, d) + + if (P["n"] === C_ZERO && this["n"] === C_ZERO) { + return newFraction(C_ZERO, C_ONE); + } + return newFraction(P["n"] * this["n"], gcd(P["n"], this["n"]) * gcd(P["d"], this["d"])); + }, + + /** + * Gets the inverse of the fraction, means numerator and denominator are exchanged + * + * Ex: new Fraction([-3, 4]).inverse() => -4 / 3 + **/ + "inverse": function () { + return newFraction(this["s"] * this["d"], this["n"]); + }, + + /** + * Calculates the fraction to some integer exponent + * + * Ex: new Fraction(-1,2).pow(-3) => -8 + */ + "pow": function (a, b) { + + parse(a, b); + + // Trivial case when exp is an integer + + if (P['d'] === C_ONE) { + + if (P['s'] < C_ZERO) { + return newFraction((this['s'] * this["d"]) ** P['n'], this["n"] ** P['n']); + } else { + return newFraction((this['s'] * this["n"]) ** P['n'], this["d"] ** P['n']); + } + } + + // Negative roots become complex + // (-a/b)^(c/d) = x + // ⇔ (-1)^(c/d) * (a/b)^(c/d) = x + // ⇔ (cos(pi) + i*sin(pi))^(c/d) * (a/b)^(c/d) = x + // ⇔ (cos(c*pi/d) + i*sin(c*pi/d)) * (a/b)^(c/d) = x # DeMoivre's formula + // From which follows that only for c=0 the root is non-complex + if (this['s'] < C_ZERO) return null; + + // Now prime factor n and d + let N = factorize(this['n']); + let D = factorize(this['d']); + + // Exponentiate and take root for n and d individually + let n = C_ONE; + let d = C_ONE; + for (let k in N) { + if (k === '1') continue; + if (k === '0') { + n = C_ZERO; + break; + } + N[k] *= P['n']; + + if (N[k] % P['d'] === C_ZERO) { + N[k] /= P['d']; + } else return null; + n *= BigInt(k) ** N[k]; + } + + for (let k in D) { + if (k === '1') continue; + D[k] *= P['n']; + + if (D[k] % P['d'] === C_ZERO) { + D[k] /= P['d']; + } else return null; + d *= BigInt(k) ** D[k]; + } + + if (P['s'] < C_ZERO) { + return newFraction(d, n); + } + return newFraction(n, d); + }, + + /** + * Calculates the logarithm of a fraction to a given rational base + * + * Ex: new Fraction(27, 8).log(9, 4) => 3/2 + */ + "log": function (a, b) { + + parse(a, b); + + if (this['s'] <= C_ZERO || P['s'] <= C_ZERO) return null; + + const allPrimes = Object.create(null); + + const baseFactors = factorize(P['n']); + const T1 = factorize(P['d']); + + const numberFactors = factorize(this['n']); + const T2 = factorize(this['d']); + + for (const prime in T1) { + baseFactors[prime] = (baseFactors[prime] || C_ZERO) - T1[prime]; + } + for (const prime in T2) { + numberFactors[prime] = (numberFactors[prime] || C_ZERO) - T2[prime]; + } + + for (const prime in baseFactors) { + if (prime === '1') continue; + allPrimes[prime] = true; + } + for (const prime in numberFactors) { + if (prime === '1') continue; + allPrimes[prime] = true; + } + + let retN = null; + let retD = null; + + // Iterate over all unique primes to determine if a consistent ratio exists + for (const prime in allPrimes) { + + const baseExponent = baseFactors[prime] || C_ZERO; + const numberExponent = numberFactors[prime] || C_ZERO; + + if (baseExponent === C_ZERO) { + if (numberExponent !== C_ZERO) { + return null; // Logarithm cannot be expressed as a rational number + } + continue; // Skip this prime since both exponents are zero + } + + // Calculate the ratio of exponents for this prime + let curN = numberExponent; + let curD = baseExponent; + + // Simplify the current ratio + const gcdValue = gcd(curN, curD); + curN /= gcdValue; + curD /= gcdValue; + + // Check if this is the first ratio; otherwise, ensure ratios are consistent + if (retN === null && retD === null) { + retN = curN; + retD = curD; + } else if (curN * retD !== retN * curD) { + return null; // Ratios do not match, logarithm cannot be rational + } + } + + return retN !== null && retD !== null + ? newFraction(retN, retD) + : null; + }, + + /** + * Check if two rational numbers are the same + * + * Ex: new Fraction(19.6).equals([98, 5]); + **/ + "equals": function (a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] === P["s"] * P["n"] * this["d"]; + }, + + /** + * Check if this rational number is less than another + * + * Ex: new Fraction(19.6).lt([98, 5]); + **/ + "lt": function (a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] < P["s"] * P["n"] * this["d"]; + }, + + /** + * Check if this rational number is less than or equal another + * + * Ex: new Fraction(19.6).lt([98, 5]); + **/ + "lte": function (a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] <= P["s"] * P["n"] * this["d"]; + }, + + /** + * Check if this rational number is greater than another + * + * Ex: new Fraction(19.6).lt([98, 5]); + **/ + "gt": function (a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] > P["s"] * P["n"] * this["d"]; + }, + + /** + * Check if this rational number is greater than or equal another + * + * Ex: new Fraction(19.6).lt([98, 5]); + **/ + "gte": function (a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] >= P["s"] * P["n"] * this["d"]; + }, + + /** + * Compare two rational numbers + * < 0 iff this < that + * > 0 iff this > that + * = 0 iff this = that + * + * Ex: new Fraction(19.6).compare([98, 5]); + **/ + "compare": function (a, b) { + + parse(a, b); + let t = this["s"] * this["n"] * P["d"] - P["s"] * P["n"] * this["d"]; + + return (C_ZERO < t) - (t < C_ZERO); + }, + + /** + * Calculates the ceil of a rational number + * + * Ex: new Fraction('4.(3)').ceil() => (5 / 1) + **/ + "ceil": function (places) { + + places = C_TEN ** BigInt(places || 0); + + return newFraction(ifloor(this["s"] * places * this["n"] / this["d"]) + + (places * this["n"] % this["d"] > C_ZERO && this["s"] >= C_ZERO ? C_ONE : C_ZERO), + places); + }, + + /** + * Calculates the floor of a rational number + * + * Ex: new Fraction('4.(3)').floor() => (4 / 1) + **/ + "floor": function (places) { + + places = C_TEN ** BigInt(places || 0); + + return newFraction(ifloor(this["s"] * places * this["n"] / this["d"]) - + (places * this["n"] % this["d"] > C_ZERO && this["s"] < C_ZERO ? C_ONE : C_ZERO), + places); + }, + + /** + * Rounds a rational numbers + * + * Ex: new Fraction('4.(3)').round() => (4 / 1) + **/ + "round": function (places) { + + places = C_TEN ** BigInt(places || 0); + + /* Derivation: + + s >= 0: + round(n / d) = ifloor(n / d) + (n % d) / d >= 0.5 ? 1 : 0 + = ifloor(n / d) + 2(n % d) >= d ? 1 : 0 + s < 0: + round(n / d) =-ifloor(n / d) - (n % d) / d > 0.5 ? 1 : 0 + =-ifloor(n / d) - 2(n % d) > d ? 1 : 0 + + =>: + + round(s * n / d) = s * ifloor(n / d) + s * (C + 2(n % d) > d ? 1 : 0) + where C = s >= 0 ? 1 : 0, to fix the >= for the positve case. + */ + + return newFraction(ifloor(this["s"] * places * this["n"] / this["d"]) + + this["s"] * ((this["s"] >= C_ZERO ? C_ONE : C_ZERO) + C_TWO * (places * this["n"] % this["d"]) > this["d"] ? C_ONE : C_ZERO), + places); + }, + + /** + * Rounds a rational number to a multiple of another rational number + * + * Ex: new Fraction('0.9').roundTo("1/8") => 7 / 8 + **/ + "roundTo": function (a, b) { + + /* + k * x/y ≤ a/b < (k+1) * x/y + ⇔ k ≤ a/b / (x/y) < (k+1) + ⇔ k = floor(a/b * y/x) + ⇔ k = floor((a * y) / (b * x)) + */ + + parse(a, b); + + const n = this['n'] * P['d']; + const d = this['d'] * P['n']; + const r = n % d; + + // round(n / d) = ifloor(n / d) + 2(n % d) >= d ? 1 : 0 + let k = ifloor(n / d); + if (r + r >= d) { + k++; + } + return newFraction(this['s'] * k * P['n'], P['d']); + }, + + /** + * Check if two rational numbers are divisible + * + * Ex: new Fraction(19.6).divisible(1.5); + */ + "divisible": function (a, b) { + + parse(a, b); + if (P['n'] === C_ZERO) return false; + return (this['n'] * P['d']) % (P['n'] * this['d']) === C_ZERO; + }, + + /** + * Returns a decimal representation of the fraction + * + * Ex: new Fraction("100.'91823'").valueOf() => 100.91823918239183 + **/ + 'valueOf': function () { + //if (this['n'] <= MAX_INTEGER && this['d'] <= MAX_INTEGER) { + return Number(this['s'] * this['n']) / Number(this['d']); + //} + }, + + /** + * Creates a string representation of a fraction with all digits + * + * Ex: new Fraction("100.'91823'").toString() => "100.(91823)" + **/ + 'toString': function (dec = 15) { + + let N = this["n"]; + let D = this["d"]; + + let cycLen = cycleLen(N, D); // Cycle length + let cycOff = cycleStart(N, D, cycLen); // Cycle start + + let str = this['s'] < C_ZERO ? "-" : ""; + + // Append integer part + str += ifloor(N / D); + + N %= D; + N *= C_TEN; + + if (N) + str += "."; + + if (cycLen) { + + for (let i = cycOff; i--;) { + str += ifloor(N / D); + N %= D; + N *= C_TEN; + } + str += "("; + for (let i = cycLen; i--;) { + str += ifloor(N / D); + N %= D; + N *= C_TEN; + } + str += ")"; + } else { + for (let i = dec; N && i--;) { + str += ifloor(N / D); + N %= D; + N *= C_TEN; + } + } + return str; + }, + + /** + * Returns a string-fraction representation of a Fraction object + * + * Ex: new Fraction("1.'3'").toFraction() => "4 1/3" + **/ + 'toFraction': function (showMixed = false) { + + let n = this["n"]; + let d = this["d"]; + let str = this['s'] < C_ZERO ? "-" : ""; + + if (d === C_ONE) { + str += n; + } else { + const whole = ifloor(n / d); + if (showMixed && whole > C_ZERO) { + str += whole; + str += " "; + n %= d; + } + + str += n; + str += '/'; + str += d; + } + return str; + }, + + /** + * Returns a latex representation of a Fraction object + * + * Ex: new Fraction("1.'3'").toLatex() => "\frac{4}{3}" + **/ + 'toLatex': function (showMixed = false) { + + let n = this["n"]; + let d = this["d"]; + let str = this['s'] < C_ZERO ? "-" : ""; + + if (d === C_ONE) { + str += n; + } else { + const whole = ifloor(n / d); + if (showMixed && whole > C_ZERO) { + str += whole; + n %= d; + } + + str += "\\frac{"; + str += n; + str += '}{'; + str += d; + str += '}'; + } + return str; + }, + + /** + * Returns an array of continued fraction elements + * + * Ex: new Fraction("7/8").toContinued() => [0,1,7] + */ + 'toContinued': function () { + + let a = this['n']; + let b = this['d']; + const res = []; + + while (b) { + res.push(ifloor(a / b)); + const t = a % b; + a = b; + b = t; + } + return res; + }, + + "simplify": function (eps = 1e-3) { + + // Continued fractions give best approximations for a max denominator, + // generally outperforming mediants in denominator–accuracy trade-offs. + // Semiconvergents can further reduce the denominator within tolerance. + + const ieps = BigInt(Math.ceil(1 / eps)); + + const thisABS = this['abs'](); + const cont = thisABS['toContinued'](); + + for (let i = 1; i < cont.length; i++) { + + let s = newFraction(cont[i - 1], C_ONE); + for (let k = i - 2; k >= 0; k--) { + s = s['inverse']()['add'](cont[k]); + } + + let t = s['sub'](thisABS); + if (t['n'] * ieps < t['d']) { // More robust than Math.abs(t.valueOf()) < eps + return s['mul'](this['s']); + } + } + return this; + } +}; + +Object.defineProperty(Fraction, "__esModule", { 'value': true }); +Fraction['default'] = Fraction; +Fraction['Fraction'] = Fraction; +module['exports'] = Fraction; diff --git a/client/node_modules/fraction.js/dist/fraction.min.js b/client/node_modules/fraction.js/dist/fraction.min.js new file mode 100644 index 0000000..97b02ee --- /dev/null +++ b/client/node_modules/fraction.js/dist/fraction.min.js @@ -0,0 +1,21 @@ +/* +Fraction.js v5.3.4 8/22/2025 +https://raw.org/article/rational-numbers-in-javascript/ + +Copyright (c) 2025, Robert Eisele (https://raw.org/) +Licensed under the MIT license. +*/ +'use strict';(function(F){function D(){return Error("Parameters must be integer")}function x(){return Error("Invalid argument")}function C(){return Error("Division by Zero")}function q(a,b){var d=g,c=h;let f=h;if(void 0!==a&&null!==a)if(void 0!==b){if("bigint"===typeof a)d=a;else{if(isNaN(a))throw x();if(0!==a%1)throw D();d=BigInt(a)}if("bigint"===typeof b)c=b;else{if(isNaN(b))throw x();if(0!==b%1)throw D();c=BigInt(b)}f=d*c}else if("object"===typeof a){if("d"in a&&"n"in a)d=BigInt(a.n),c=BigInt(a.d), +"s"in a&&(d*=BigInt(a.s));else if(0 in a)d=BigInt(a[0]),1 in a&&(c=BigInt(a[1]));else if("bigint"===typeof a)d=a;else throw x();f=d*c}else if("number"===typeof a){if(isNaN(a))throw x();0>a&&(f=-h,a=-a);if(0===a%1)d=BigInt(a);else{b=1;var k=0,l=1,m=1;let r=1;1<=a&&(b=10**Math.floor(1+Math.log10(a)),a/=b);for(;1E7>=l&&1E7>=r;)if(c=(k+m)/(l+r),a===c){1E7>=l+r?(d=k+m,c=l+r):r>l?(d=m,c=r):(d=k,c=l);break}else a>c?(k+=m,l+=r):(m+=k,r+=l),1E7h&&(b[a]=(b[a]||g)+h);return b}function y(a,b){if(!a)return b;if(!b)return a;for(;;){a%=b;if(!a)return b;b%=a;if(!b)return a}}function v(a,b){q(a,b);if(this instanceof v)a=y(e.d,e.n),this.s=e.s,this.n=e.n/a,this.d=e.d/a;else return n(e.s*e.n,e.d)}"undefined"===typeof BigInt&& +(BigInt=function(a){if(isNaN(a))throw Error("");return a});const g=BigInt(0),h=BigInt(1),p=BigInt(2),B=BigInt(3),z=BigInt(5),t=BigInt(10),e={s:h,n:g,d:h},G=[p*p,p,p*p,p,p*p,p*B,p,p*B];v.prototype={s:h,n:g,d:h,abs:function(){return n(this.n,this.d)},neg:function(){return n(-this.s*this.n,this.d)},add:function(a,b){q(a,b);return n(this.s*this.n*e.d+e.s*this.d*e.n,this.d*e.d)},sub:function(a,b){q(a,b);return n(this.s*this.n*e.d-e.s*this.d*e.n,this.d*e.d)},mul:function(a,b){q(a,b);return n(this.s*e.s* +this.n*e.n,this.d*e.d)},div:function(a,b){q(a,b);return n(this.s*e.s*this.n*e.d,this.d*e.n)},clone:function(){return n(this.s*this.n,this.d)},mod:function(a,b){if(void 0===a)return n(this.s*this.n%this.d,h);q(a,b);if(g===e.n*this.d)throw C();return n(this.s*e.d*this.n%(e.n*this.d),e.d*this.d)},gcd:function(a,b){q(a,b);return n(y(e.n,this.n)*y(e.d,this.d),e.d*this.d)},lcm:function(a,b){q(a,b);return e.n===g&&this.n===g?n(g,h):n(e.n*this.n,y(e.n,this.n)*y(e.d,this.d))},inverse:function(){return n(this.s* +this.d,this.n)},pow:function(a,b){q(a,b);if(e.d===h)return e.se.s*e.n*this.d},gte:function(a,b){q(a,b);return this.s*this.n*e.d>=e.s*e.n*this.d},compare:function(a,b){q(a,b);a=this.s*this.n*e.d-e.s*e.n*this.d;return(gg&&this.s>=g?h:g),a)},floor:function(a){a=t**BigInt(a||0);return n(u(this.s*a*this.n/ +this.d)-(a*this.n%this.d>g&&this.s=g?h:g)+a*this.n%this.d*p>this.d?h:g),a)},roundTo:function(a,b){q(a,b);var d=this.n*e.d;a=this.d*e.n;b=d%a;d=u(d/a);b+b>=a&&d++;return n(this.s*d*e.n,e.d)},divisible:function(a,b){q(a,b);return e.n===g?!1:this.n*e.d%(e.n*this.d)===g},valueOf:function(){return Number(this.s*this.n)/Number(this.d)},toString:function(a=15){let b=this.n,d=this.d;var c;a:{for(c=d;c%p===g;c/= +p);for(;c%z===g;c/=z);if(c===h)c=g;else{for(var f=t%c,k=1;f!==h;k++)if(f=f*t%c,2E3g;k=k*k%d,l>>=h)l&h&&(m=m*k%d);k=m;for(l=0;300>l;l++){if(f===k){f=BigInt(l);break a}f=f*t%d;k=k*t%d}f=0}k=f;f=this.sg&&(c+=f,c+=" ",b%=d);c=c+b+"/"+d}return c},toLatex:function(a=!1){let b=this.n,d=this.d,c=this.sg&&(c+=f,b%=d);c=c+"\\frac{"+b+"}{"+d;c+="}"}return c},toContinued:function(){let a=this.n,b=this.d;const d=[];for(;b;){d.push(u(a/b));const c=a%b;a=b;b=c}return d},simplify:function(a=.001){a=BigInt(Math.ceil(1/a));const b=this.abs(),d=b.toContinued();for(let f=1;f , 1 => ] + * { n => , d => } + * + * Integer form + * - Single integer value as BigInt or Number + * + * Double form + * - Single double value as Number + * + * String form + * 123.456 - a simple double + * 123/456 - a string fraction + * 123.'456' - a double with repeating decimal places + * 123.(456) - synonym + * 123.45'6' - a double with repeating last place + * 123.45(6) - synonym + * + * Example: + * let f = new Fraction("9.4'31'"); + * f.mul([-4, 3]).div(4.9); + * + */ + +// Set Identity function to downgrade BigInt to Number if needed +if (typeof BigInt === 'undefined') BigInt = function (n) { if (isNaN(n)) throw new Error(""); return n; }; + +const C_ZERO = BigInt(0); +const C_ONE = BigInt(1); +const C_TWO = BigInt(2); +const C_THREE = BigInt(3); +const C_FIVE = BigInt(5); +const C_TEN = BigInt(10); +const MAX_INTEGER = BigInt(Number.MAX_SAFE_INTEGER); + +// Maximum search depth for cyclic rational numbers. 2000 should be more than enough. +// Example: 1/7 = 0.(142857) has 6 repeating decimal places. +// If MAX_CYCLE_LEN gets reduced, long cycles will not be detected and toString() only gets the first 10 digits +const MAX_CYCLE_LEN = 2000; + +// Parsed data to avoid calling "new" all the time +const P = { + "s": C_ONE, + "n": C_ZERO, + "d": C_ONE +}; + +function assign(n, s) { + + try { + n = BigInt(n); + } catch (e) { + throw InvalidParameter(); + } + return n * s; +} + +function ifloor(x) { + return typeof x === 'bigint' ? x : Math.floor(x); +} + +// Creates a new Fraction internally without the need of the bulky constructor +function newFraction(n, d) { + + if (d === C_ZERO) { + throw DivisionByZero(); + } + + const f = Object.create(Fraction.prototype); + f["s"] = n < C_ZERO ? -C_ONE : C_ONE; + + n = n < C_ZERO ? -n : n; + + const a = gcd(n, d); + + f["n"] = n / a; + f["d"] = d / a; + return f; +} + +const FACTORSTEPS = [C_TWO * C_TWO, C_TWO, C_TWO * C_TWO, C_TWO, C_TWO * C_TWO, C_TWO * C_THREE, C_TWO, C_TWO * C_THREE]; // repeats +function factorize(n) { + + const factors = Object.create(null); + if (n <= C_ONE) { + factors[n] = C_ONE; + return factors; + } + + const add = (p) => { factors[p] = (factors[p] || C_ZERO) + C_ONE; }; + + while (n % C_TWO === C_ZERO) { add(C_TWO); n /= C_TWO; } + while (n % C_THREE === C_ZERO) { add(C_THREE); n /= C_THREE; } + while (n % C_FIVE === C_ZERO) { add(C_FIVE); n /= C_FIVE; } + + // 30-wheel trial division: test only residues coprime to 2*3*5 + // Residue step pattern after 5: 7,11,13,17,19,23,29,31, ... + for (let si = 0, p = C_TWO + C_FIVE; p * p <= n;) { + while (n % p === C_ZERO) { add(p); n /= p; } + p += FACTORSTEPS[si]; + si = (si + 1) & 7; // fast modulo 8 + } + if (n > C_ONE) add(n); + return factors; +} + +const parse = function (p1, p2) { + + let n = C_ZERO, d = C_ONE, s = C_ONE; + + if (p1 === undefined || p1 === null) { // No argument + /* void */ + } else if (p2 !== undefined) { // Two arguments + + if (typeof p1 === "bigint") { + n = p1; + } else if (isNaN(p1)) { + throw InvalidParameter(); + } else if (p1 % 1 !== 0) { + throw NonIntegerParameter(); + } else { + n = BigInt(p1); + } + + if (typeof p2 === "bigint") { + d = p2; + } else if (isNaN(p2)) { + throw InvalidParameter(); + } else if (p2 % 1 !== 0) { + throw NonIntegerParameter(); + } else { + d = BigInt(p2); + } + + s = n * d; + + } else if (typeof p1 === "object") { + if ("d" in p1 && "n" in p1) { + n = BigInt(p1["n"]); + d = BigInt(p1["d"]); + if ("s" in p1) + n *= BigInt(p1["s"]); + } else if (0 in p1) { + n = BigInt(p1[0]); + if (1 in p1) + d = BigInt(p1[1]); + } else if (typeof p1 === "bigint") { + n = p1; + } else { + throw InvalidParameter(); + } + s = n * d; + } else if (typeof p1 === "number") { + + if (isNaN(p1)) { + throw InvalidParameter(); + } + + if (p1 < 0) { + s = -C_ONE; + p1 = -p1; + } + + if (p1 % 1 === 0) { + n = BigInt(p1); + } else { + + let z = 1; + + let A = 0, B = 1; + let C = 1, D = 1; + + let N = 10000000; + + if (p1 >= 1) { + z = 10 ** Math.floor(1 + Math.log10(p1)); + p1 /= z; + } + + // Using Farey Sequences + + while (B <= N && D <= N) { + let M = (A + C) / (B + D); + + if (p1 === M) { + if (B + D <= N) { + n = A + C; + d = B + D; + } else if (D > B) { + n = C; + d = D; + } else { + n = A; + d = B; + } + break; + + } else { + + if (p1 > M) { + A += C; + B += D; + } else { + C += A; + D += B; + } + + if (B > N) { + n = C; + d = D; + } else { + n = A; + d = B; + } + } + } + n = BigInt(n) * BigInt(z); + d = BigInt(d); + } + + } else if (typeof p1 === "string") { + + let ndx = 0; + + let v = C_ZERO, w = C_ZERO, x = C_ZERO, y = C_ONE, z = C_ONE; + + let match = p1.replace(/_/g, '').match(/\d+|./g); + + if (match === null) + throw InvalidParameter(); + + if (match[ndx] === '-') {// Check for minus sign at the beginning + s = -C_ONE; + ndx++; + } else if (match[ndx] === '+') {// Check for plus sign at the beginning + ndx++; + } + + if (match.length === ndx + 1) { // Check if it's just a simple number "1234" + w = assign(match[ndx++], s); + } else if (match[ndx + 1] === '.' || match[ndx] === '.') { // Check if it's a decimal number + + if (match[ndx] !== '.') { // Handle 0.5 and .5 + v = assign(match[ndx++], s); + } + ndx++; + + // Check for decimal places + if (ndx + 1 === match.length || match[ndx + 1] === '(' && match[ndx + 3] === ')' || match[ndx + 1] === "'" && match[ndx + 3] === "'") { + w = assign(match[ndx], s); + y = C_TEN ** BigInt(match[ndx].length); + ndx++; + } + + // Check for repeating places + if (match[ndx] === '(' && match[ndx + 2] === ')' || match[ndx] === "'" && match[ndx + 2] === "'") { + x = assign(match[ndx + 1], s); + z = C_TEN ** BigInt(match[ndx + 1].length) - C_ONE; + ndx += 3; + } + + } else if (match[ndx + 1] === '/' || match[ndx + 1] === ':') { // Check for a simple fraction "123/456" or "123:456" + w = assign(match[ndx], s); + y = assign(match[ndx + 2], C_ONE); + ndx += 3; + } else if (match[ndx + 3] === '/' && match[ndx + 1] === ' ') { // Check for a complex fraction "123 1/2" + v = assign(match[ndx], s); + w = assign(match[ndx + 2], s); + y = assign(match[ndx + 4], C_ONE); + ndx += 5; + } + + if (match.length <= ndx) { // Check for more tokens on the stack + d = y * z; + s = /* void */ + n = x + d * v + z * w; + } else { + throw InvalidParameter(); + } + + } else if (typeof p1 === "bigint") { + n = p1; + s = p1; + d = C_ONE; + } else { + throw InvalidParameter(); + } + + if (d === C_ZERO) { + throw DivisionByZero(); + } + + P["s"] = s < C_ZERO ? -C_ONE : C_ONE; + P["n"] = n < C_ZERO ? -n : n; + P["d"] = d < C_ZERO ? -d : d; +}; + +function modpow(b, e, m) { + + let r = C_ONE; + for (; e > C_ZERO; b = (b * b) % m, e >>= C_ONE) { + + if (e & C_ONE) { + r = (r * b) % m; + } + } + return r; +} + +function cycleLen(n, d) { + + for (; d % C_TWO === C_ZERO; + d /= C_TWO) { + } + + for (; d % C_FIVE === C_ZERO; + d /= C_FIVE) { + } + + if (d === C_ONE) // Catch non-cyclic numbers + return C_ZERO; + + // If we would like to compute really large numbers quicker, we could make use of Fermat's little theorem: + // 10^(d-1) % d == 1 + // However, we don't need such large numbers and MAX_CYCLE_LEN should be the capstone, + // as we want to translate the numbers to strings. + + let rem = C_TEN % d; + let t = 1; + + for (; rem !== C_ONE; t++) { + rem = rem * C_TEN % d; + + if (t > MAX_CYCLE_LEN) + return C_ZERO; // Returning 0 here means that we don't print it as a cyclic number. It's likely that the answer is `d-1` + } + return BigInt(t); +} + +function cycleStart(n, d, len) { + + let rem1 = C_ONE; + let rem2 = modpow(C_TEN, len, d); + + for (let t = 0; t < 300; t++) { // s < ~log10(Number.MAX_VALUE) + // Solve 10^s == 10^(s+t) (mod d) + + if (rem1 === rem2) + return BigInt(t); + + rem1 = rem1 * C_TEN % d; + rem2 = rem2 * C_TEN % d; + } + return 0; +} + +function gcd(a, b) { + + if (!a) + return b; + if (!b) + return a; + + while (1) { + a %= b; + if (!a) + return b; + b %= a; + if (!b) + return a; + } +} + +/** + * Module constructor + * + * @constructor + * @param {number|Fraction=} a + * @param {number=} b + */ +function Fraction(a, b) { + + parse(a, b); + + if (this instanceof Fraction) { + a = gcd(P["d"], P["n"]); // Abuse a + this["s"] = P["s"]; + this["n"] = P["n"] / a; + this["d"] = P["d"] / a; + } else { + return newFraction(P['s'] * P['n'], P['d']); + } +} + +const DivisionByZero = function () { return new Error("Division by Zero"); }; +const InvalidParameter = function () { return new Error("Invalid argument"); }; +const NonIntegerParameter = function () { return new Error("Parameters must be integer"); }; + +Fraction.prototype = { + + "s": C_ONE, + "n": C_ZERO, + "d": C_ONE, + + /** + * Calculates the absolute value + * + * Ex: new Fraction(-4).abs() => 4 + **/ + "abs": function () { + + return newFraction(this["n"], this["d"]); + }, + + /** + * Inverts the sign of the current fraction + * + * Ex: new Fraction(-4).neg() => 4 + **/ + "neg": function () { + + return newFraction(-this["s"] * this["n"], this["d"]); + }, + + /** + * Adds two rational numbers + * + * Ex: new Fraction({n: 2, d: 3}).add("14.9") => 467 / 30 + **/ + "add": function (a, b) { + + parse(a, b); + return newFraction( + this["s"] * this["n"] * P["d"] + P["s"] * this["d"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Subtracts two rational numbers + * + * Ex: new Fraction({n: 2, d: 3}).add("14.9") => -427 / 30 + **/ + "sub": function (a, b) { + + parse(a, b); + return newFraction( + this["s"] * this["n"] * P["d"] - P["s"] * this["d"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Multiplies two rational numbers + * + * Ex: new Fraction("-17.(345)").mul(3) => 5776 / 111 + **/ + "mul": function (a, b) { + + parse(a, b); + return newFraction( + this["s"] * P["s"] * this["n"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Divides two rational numbers + * + * Ex: new Fraction("-17.(345)").inverse().div(3) + **/ + "div": function (a, b) { + + parse(a, b); + return newFraction( + this["s"] * P["s"] * this["n"] * P["d"], + this["d"] * P["n"] + ); + }, + + /** + * Clones the actual object + * + * Ex: new Fraction("-17.(345)").clone() + **/ + "clone": function () { + return newFraction(this['s'] * this['n'], this['d']); + }, + + /** + * Calculates the modulo of two rational numbers - a more precise fmod + * + * Ex: new Fraction('4.(3)').mod([7, 8]) => (13/3) % (7/8) = (5/6) + * Ex: new Fraction(20, 10).mod().equals(0) ? "is Integer" + **/ + "mod": function (a, b) { + + if (a === undefined) { + return newFraction(this["s"] * this["n"] % this["d"], C_ONE); + } + + parse(a, b); + if (C_ZERO === P["n"] * this["d"]) { + throw DivisionByZero(); + } + + /** + * I derived the rational modulo similar to the modulo for integers + * + * https://raw.org/book/analysis/rational-numbers/ + * + * n1/d1 = (n2/d2) * q + r, where 0 ≤ r < n2/d2 + * => d2 * n1 = n2 * d1 * q + d1 * d2 * r + * => r = (d2 * n1 - n2 * d1 * q) / (d1 * d2) + * = (d2 * n1 - n2 * d1 * floor((d2 * n1) / (n2 * d1))) / (d1 * d2) + * = ((d2 * n1) % (n2 * d1)) / (d1 * d2) + */ + return newFraction( + this["s"] * (P["d"] * this["n"]) % (P["n"] * this["d"]), + P["d"] * this["d"]); + }, + + /** + * Calculates the fractional gcd of two rational numbers + * + * Ex: new Fraction(5,8).gcd(3,7) => 1/56 + */ + "gcd": function (a, b) { + + parse(a, b); + + // https://raw.org/book/analysis/rational-numbers/ + // gcd(a / b, c / d) = gcd(a, c) / lcm(b, d) + + return newFraction(gcd(P["n"], this["n"]) * gcd(P["d"], this["d"]), P["d"] * this["d"]); + }, + + /** + * Calculates the fractional lcm of two rational numbers + * + * Ex: new Fraction(5,8).lcm(3,7) => 15 + */ + "lcm": function (a, b) { + + parse(a, b); + + // https://raw.org/book/analysis/rational-numbers/ + // lcm(a / b, c / d) = lcm(a, c) / gcd(b, d) + + if (P["n"] === C_ZERO && this["n"] === C_ZERO) { + return newFraction(C_ZERO, C_ONE); + } + return newFraction(P["n"] * this["n"], gcd(P["n"], this["n"]) * gcd(P["d"], this["d"])); + }, + + /** + * Gets the inverse of the fraction, means numerator and denominator are exchanged + * + * Ex: new Fraction([-3, 4]).inverse() => -4 / 3 + **/ + "inverse": function () { + return newFraction(this["s"] * this["d"], this["n"]); + }, + + /** + * Calculates the fraction to some integer exponent + * + * Ex: new Fraction(-1,2).pow(-3) => -8 + */ + "pow": function (a, b) { + + parse(a, b); + + // Trivial case when exp is an integer + + if (P['d'] === C_ONE) { + + if (P['s'] < C_ZERO) { + return newFraction((this['s'] * this["d"]) ** P['n'], this["n"] ** P['n']); + } else { + return newFraction((this['s'] * this["n"]) ** P['n'], this["d"] ** P['n']); + } + } + + // Negative roots become complex + // (-a/b)^(c/d) = x + // ⇔ (-1)^(c/d) * (a/b)^(c/d) = x + // ⇔ (cos(pi) + i*sin(pi))^(c/d) * (a/b)^(c/d) = x + // ⇔ (cos(c*pi/d) + i*sin(c*pi/d)) * (a/b)^(c/d) = x # DeMoivre's formula + // From which follows that only for c=0 the root is non-complex + if (this['s'] < C_ZERO) return null; + + // Now prime factor n and d + let N = factorize(this['n']); + let D = factorize(this['d']); + + // Exponentiate and take root for n and d individually + let n = C_ONE; + let d = C_ONE; + for (let k in N) { + if (k === '1') continue; + if (k === '0') { + n = C_ZERO; + break; + } + N[k] *= P['n']; + + if (N[k] % P['d'] === C_ZERO) { + N[k] /= P['d']; + } else return null; + n *= BigInt(k) ** N[k]; + } + + for (let k in D) { + if (k === '1') continue; + D[k] *= P['n']; + + if (D[k] % P['d'] === C_ZERO) { + D[k] /= P['d']; + } else return null; + d *= BigInt(k) ** D[k]; + } + + if (P['s'] < C_ZERO) { + return newFraction(d, n); + } + return newFraction(n, d); + }, + + /** + * Calculates the logarithm of a fraction to a given rational base + * + * Ex: new Fraction(27, 8).log(9, 4) => 3/2 + */ + "log": function (a, b) { + + parse(a, b); + + if (this['s'] <= C_ZERO || P['s'] <= C_ZERO) return null; + + const allPrimes = Object.create(null); + + const baseFactors = factorize(P['n']); + const T1 = factorize(P['d']); + + const numberFactors = factorize(this['n']); + const T2 = factorize(this['d']); + + for (const prime in T1) { + baseFactors[prime] = (baseFactors[prime] || C_ZERO) - T1[prime]; + } + for (const prime in T2) { + numberFactors[prime] = (numberFactors[prime] || C_ZERO) - T2[prime]; + } + + for (const prime in baseFactors) { + if (prime === '1') continue; + allPrimes[prime] = true; + } + for (const prime in numberFactors) { + if (prime === '1') continue; + allPrimes[prime] = true; + } + + let retN = null; + let retD = null; + + // Iterate over all unique primes to determine if a consistent ratio exists + for (const prime in allPrimes) { + + const baseExponent = baseFactors[prime] || C_ZERO; + const numberExponent = numberFactors[prime] || C_ZERO; + + if (baseExponent === C_ZERO) { + if (numberExponent !== C_ZERO) { + return null; // Logarithm cannot be expressed as a rational number + } + continue; // Skip this prime since both exponents are zero + } + + // Calculate the ratio of exponents for this prime + let curN = numberExponent; + let curD = baseExponent; + + // Simplify the current ratio + const gcdValue = gcd(curN, curD); + curN /= gcdValue; + curD /= gcdValue; + + // Check if this is the first ratio; otherwise, ensure ratios are consistent + if (retN === null && retD === null) { + retN = curN; + retD = curD; + } else if (curN * retD !== retN * curD) { + return null; // Ratios do not match, logarithm cannot be rational + } + } + + return retN !== null && retD !== null + ? newFraction(retN, retD) + : null; + }, + + /** + * Check if two rational numbers are the same + * + * Ex: new Fraction(19.6).equals([98, 5]); + **/ + "equals": function (a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] === P["s"] * P["n"] * this["d"]; + }, + + /** + * Check if this rational number is less than another + * + * Ex: new Fraction(19.6).lt([98, 5]); + **/ + "lt": function (a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] < P["s"] * P["n"] * this["d"]; + }, + + /** + * Check if this rational number is less than or equal another + * + * Ex: new Fraction(19.6).lt([98, 5]); + **/ + "lte": function (a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] <= P["s"] * P["n"] * this["d"]; + }, + + /** + * Check if this rational number is greater than another + * + * Ex: new Fraction(19.6).lt([98, 5]); + **/ + "gt": function (a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] > P["s"] * P["n"] * this["d"]; + }, + + /** + * Check if this rational number is greater than or equal another + * + * Ex: new Fraction(19.6).lt([98, 5]); + **/ + "gte": function (a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] >= P["s"] * P["n"] * this["d"]; + }, + + /** + * Compare two rational numbers + * < 0 iff this < that + * > 0 iff this > that + * = 0 iff this = that + * + * Ex: new Fraction(19.6).compare([98, 5]); + **/ + "compare": function (a, b) { + + parse(a, b); + let t = this["s"] * this["n"] * P["d"] - P["s"] * P["n"] * this["d"]; + + return (C_ZERO < t) - (t < C_ZERO); + }, + + /** + * Calculates the ceil of a rational number + * + * Ex: new Fraction('4.(3)').ceil() => (5 / 1) + **/ + "ceil": function (places) { + + places = C_TEN ** BigInt(places || 0); + + return newFraction(ifloor(this["s"] * places * this["n"] / this["d"]) + + (places * this["n"] % this["d"] > C_ZERO && this["s"] >= C_ZERO ? C_ONE : C_ZERO), + places); + }, + + /** + * Calculates the floor of a rational number + * + * Ex: new Fraction('4.(3)').floor() => (4 / 1) + **/ + "floor": function (places) { + + places = C_TEN ** BigInt(places || 0); + + return newFraction(ifloor(this["s"] * places * this["n"] / this["d"]) - + (places * this["n"] % this["d"] > C_ZERO && this["s"] < C_ZERO ? C_ONE : C_ZERO), + places); + }, + + /** + * Rounds a rational numbers + * + * Ex: new Fraction('4.(3)').round() => (4 / 1) + **/ + "round": function (places) { + + places = C_TEN ** BigInt(places || 0); + + /* Derivation: + + s >= 0: + round(n / d) = ifloor(n / d) + (n % d) / d >= 0.5 ? 1 : 0 + = ifloor(n / d) + 2(n % d) >= d ? 1 : 0 + s < 0: + round(n / d) =-ifloor(n / d) - (n % d) / d > 0.5 ? 1 : 0 + =-ifloor(n / d) - 2(n % d) > d ? 1 : 0 + + =>: + + round(s * n / d) = s * ifloor(n / d) + s * (C + 2(n % d) > d ? 1 : 0) + where C = s >= 0 ? 1 : 0, to fix the >= for the positve case. + */ + + return newFraction(ifloor(this["s"] * places * this["n"] / this["d"]) + + this["s"] * ((this["s"] >= C_ZERO ? C_ONE : C_ZERO) + C_TWO * (places * this["n"] % this["d"]) > this["d"] ? C_ONE : C_ZERO), + places); + }, + + /** + * Rounds a rational number to a multiple of another rational number + * + * Ex: new Fraction('0.9').roundTo("1/8") => 7 / 8 + **/ + "roundTo": function (a, b) { + + /* + k * x/y ≤ a/b < (k+1) * x/y + ⇔ k ≤ a/b / (x/y) < (k+1) + ⇔ k = floor(a/b * y/x) + ⇔ k = floor((a * y) / (b * x)) + */ + + parse(a, b); + + const n = this['n'] * P['d']; + const d = this['d'] * P['n']; + const r = n % d; + + // round(n / d) = ifloor(n / d) + 2(n % d) >= d ? 1 : 0 + let k = ifloor(n / d); + if (r + r >= d) { + k++; + } + return newFraction(this['s'] * k * P['n'], P['d']); + }, + + /** + * Check if two rational numbers are divisible + * + * Ex: new Fraction(19.6).divisible(1.5); + */ + "divisible": function (a, b) { + + parse(a, b); + if (P['n'] === C_ZERO) return false; + return (this['n'] * P['d']) % (P['n'] * this['d']) === C_ZERO; + }, + + /** + * Returns a decimal representation of the fraction + * + * Ex: new Fraction("100.'91823'").valueOf() => 100.91823918239183 + **/ + 'valueOf': function () { + //if (this['n'] <= MAX_INTEGER && this['d'] <= MAX_INTEGER) { + return Number(this['s'] * this['n']) / Number(this['d']); + //} + }, + + /** + * Creates a string representation of a fraction with all digits + * + * Ex: new Fraction("100.'91823'").toString() => "100.(91823)" + **/ + 'toString': function (dec = 15) { + + let N = this["n"]; + let D = this["d"]; + + let cycLen = cycleLen(N, D); // Cycle length + let cycOff = cycleStart(N, D, cycLen); // Cycle start + + let str = this['s'] < C_ZERO ? "-" : ""; + + // Append integer part + str += ifloor(N / D); + + N %= D; + N *= C_TEN; + + if (N) + str += "."; + + if (cycLen) { + + for (let i = cycOff; i--;) { + str += ifloor(N / D); + N %= D; + N *= C_TEN; + } + str += "("; + for (let i = cycLen; i--;) { + str += ifloor(N / D); + N %= D; + N *= C_TEN; + } + str += ")"; + } else { + for (let i = dec; N && i--;) { + str += ifloor(N / D); + N %= D; + N *= C_TEN; + } + } + return str; + }, + + /** + * Returns a string-fraction representation of a Fraction object + * + * Ex: new Fraction("1.'3'").toFraction() => "4 1/3" + **/ + 'toFraction': function (showMixed = false) { + + let n = this["n"]; + let d = this["d"]; + let str = this['s'] < C_ZERO ? "-" : ""; + + if (d === C_ONE) { + str += n; + } else { + const whole = ifloor(n / d); + if (showMixed && whole > C_ZERO) { + str += whole; + str += " "; + n %= d; + } + + str += n; + str += '/'; + str += d; + } + return str; + }, + + /** + * Returns a latex representation of a Fraction object + * + * Ex: new Fraction("1.'3'").toLatex() => "\frac{4}{3}" + **/ + 'toLatex': function (showMixed = false) { + + let n = this["n"]; + let d = this["d"]; + let str = this['s'] < C_ZERO ? "-" : ""; + + if (d === C_ONE) { + str += n; + } else { + const whole = ifloor(n / d); + if (showMixed && whole > C_ZERO) { + str += whole; + n %= d; + } + + str += "\\frac{"; + str += n; + str += '}{'; + str += d; + str += '}'; + } + return str; + }, + + /** + * Returns an array of continued fraction elements + * + * Ex: new Fraction("7/8").toContinued() => [0,1,7] + */ + 'toContinued': function () { + + let a = this['n']; + let b = this['d']; + const res = []; + + while (b) { + res.push(ifloor(a / b)); + const t = a % b; + a = b; + b = t; + } + return res; + }, + + "simplify": function (eps = 1e-3) { + + // Continued fractions give best approximations for a max denominator, + // generally outperforming mediants in denominator–accuracy trade-offs. + // Semiconvergents can further reduce the denominator within tolerance. + + const ieps = BigInt(Math.ceil(1 / eps)); + + const thisABS = this['abs'](); + const cont = thisABS['toContinued'](); + + for (let i = 1; i < cont.length; i++) { + + let s = newFraction(cont[i - 1], C_ONE); + for (let k = i - 2; k >= 0; k--) { + s = s['inverse']()['add'](cont[k]); + } + + let t = s['sub'](thisABS); + if (t['n'] * ieps < t['d']) { // More robust than Math.abs(t.valueOf()) < eps + return s['mul'](this['s']); + } + } + return this; + } +}; +export { + Fraction as default, Fraction +}; diff --git a/client/node_modules/fraction.js/examples/angles.js b/client/node_modules/fraction.js/examples/angles.js new file mode 100644 index 0000000..436947e --- /dev/null +++ b/client/node_modules/fraction.js/examples/angles.js @@ -0,0 +1,26 @@ +/* +Fraction.js v5.0.0 10/1/2024 +https://raw.org/article/rational-numbers-in-javascript/ + +Copyright (c) 2024, Robert Eisele (https://raw.org/) +Licensed under the MIT license. +*/ + +// This example generates a list of angles with human readable radians + +var Fraction = require('fraction.js'); + +var tab = []; +for (var d = 1; d <= 360; d++) { + + var pi = Fraction(2, 360).mul(d); + var tau = Fraction(1, 360).mul(d); + + if (pi.d <= 6n && pi.d != 5n) + tab.push([ + d, + pi.toFraction() + "pi", + tau.toFraction() + "tau"]); +} + +console.table(tab); diff --git a/client/node_modules/fraction.js/examples/approx.js b/client/node_modules/fraction.js/examples/approx.js new file mode 100644 index 0000000..36aa030 --- /dev/null +++ b/client/node_modules/fraction.js/examples/approx.js @@ -0,0 +1,54 @@ +/* +Fraction.js v5.0.0 10/1/2024 +https://raw.org/article/rational-numbers-in-javascript/ + +Copyright (c) 2024, Robert Eisele (https://raw.org/) +Licensed under the MIT license. +*/ +const Fraction = require('fraction.js'); + +// Another rational approximation, not using Farey Sequences but Binary Search using the mediant +function approximate(p, precision) { + + var num1 = Math.floor(p); + var den1 = 1; + + var num2 = num1 + 1; + var den2 = 1; + + if (p !== num1) { + + while (den1 <= precision && den2 <= precision) { + + var m = (num1 + num2) / (den1 + den2); + + if (p === m) { + + if (den1 + den2 <= precision) { + den1 += den2; + num1 += num2; + den2 = precision + 1; + } else if (den1 > den2) { + den2 = precision + 1; + } else { + den1 = precision + 1; + } + break; + + } else if (p < m) { + num2 += num1; + den2 += den1; + } else { + num1 += num2; + den1 += den2; + } + } + } + + if (den1 > precision) { + den1 = den2; + num1 = num2; + } + return new Fraction(num1, den1); +} + diff --git a/client/node_modules/fraction.js/examples/egyptian.js b/client/node_modules/fraction.js/examples/egyptian.js new file mode 100644 index 0000000..66fc209 --- /dev/null +++ b/client/node_modules/fraction.js/examples/egyptian.js @@ -0,0 +1,24 @@ +/* +Fraction.js v5.0.0 10/1/2024 +https://raw.org/article/rational-numbers-in-javascript/ + +Copyright (c) 2024, Robert Eisele (https://raw.org/) +Licensed under the MIT license. +*/ +const Fraction = require('fraction.js'); + +// Based on http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fractions/egyptian.html +function egyptian(a, b) { + + var res = []; + + do { + var t = Math.ceil(b / a); + var x = new Fraction(a, b).sub(1, t); + res.push(t); + a = Number(x.n); + b = Number(x.d); + } while (a !== 0n); + return res; +} +console.log("1 / " + egyptian(521, 1050).join(" + 1 / ")); diff --git a/client/node_modules/fraction.js/examples/hesse-convergence.js b/client/node_modules/fraction.js/examples/hesse-convergence.js new file mode 100644 index 0000000..c33a58b --- /dev/null +++ b/client/node_modules/fraction.js/examples/hesse-convergence.js @@ -0,0 +1,111 @@ +/* +Fraction.js v5.0.0 10/1/2024 +https://raw.org/article/rational-numbers-in-javascript/ + +Copyright (c) 2024, Robert Eisele (https://raw.org/) +Licensed under the MIT license. +*/ +const Fraction = require('fraction.js'); + +/* +We have the polynom f(x) = 1/3x_1^2 + x_2^2 + x_1 * x_2 + 3 + +The gradient of f(x): + +grad(x) = | x_1^2+x_2 | + | 2x_2+x_1 | + +And thus the Hesse-Matrix H: +| 2x_1 1 | +| 1 2 | + +The inverse Hesse-Matrix H^-1 is +| -2 / (1-4x_1) 1 / (1 - 4x_1) | +| 1 / (1 - 4x_1) -2x_1 / (1 - 4x_1) | + +We now want to find lim ->oo x[n], with the starting element of (3 2)^T + +*/ + +// Get the Hesse Matrix +function H(x) { + + var z = Fraction(1).sub(Fraction(4).mul(x[0])); + + return [ + Fraction(-2).div(z), + Fraction(1).div(z), + Fraction(1).div(z), + Fraction(-2).mul(x[0]).div(z), + ]; +} + +// Get the gradient of f(x) +function grad(x) { + + return [ + Fraction(x[0]).mul(x[0]).add(x[1]), + Fraction(2).mul(x[1]).add(x[0]) + ]; +} + +// A simple matrix multiplication helper +function matrMult(m, v) { + + return [ + Fraction(m[0]).mul(v[0]).add(Fraction(m[1]).mul(v[1])), + Fraction(m[2]).mul(v[0]).add(Fraction(m[3]).mul(v[1])) + ]; +} + +// A simple vector subtraction helper +function vecSub(a, b) { + + return [ + Fraction(a[0]).sub(b[0]), + Fraction(a[1]).sub(b[1]) + ]; +} + +// Main function, gets a vector and the actual index +function run(V, j) { + + var t = H(V); + //console.log("H(X)"); + for (var i in t) { + + // console.log(t[i].toFraction()); + } + + var s = grad(V); + //console.log("vf(X)"); + for (var i in s) { + + // console.log(s[i].toFraction()); + } + + //console.log("multiplication"); + var r = matrMult(t, s); + for (var i in r) { + + // console.log(r[i].toFraction()); + } + + var R = (vecSub(V, r)); + + console.log("X" + j); + console.log(R[0].toFraction(), "= " + R[0].valueOf()); + console.log(R[1].toFraction(), "= " + R[1].valueOf()); + console.log("\n"); + + return R; +} + + +// Set the starting vector +var v = [3, 2]; + +for (var i = 0; i < 15; i++) { + + v = run(v, i); +} diff --git a/client/node_modules/fraction.js/examples/integrate.js b/client/node_modules/fraction.js/examples/integrate.js new file mode 100644 index 0000000..6376aed --- /dev/null +++ b/client/node_modules/fraction.js/examples/integrate.js @@ -0,0 +1,67 @@ +/* +Fraction.js v5.0.0 10/1/2024 +https://raw.org/article/rational-numbers-in-javascript/ + +Copyright (c) 2024, Robert Eisele (https://raw.org/) +Licensed under the MIT license. +*/ +const Fraction = require('fraction.js'); + +// NOTE: This is a nice example, but a stable version of this is served with Polynomial.js: +// https://github.com/rawify/Polynomial.js + +function integrate(poly) { + + poly = poly.replace(/\s+/g, ""); + + var regex = /(\([+-]?[0-9/]+\)|[+-]?[0-9/]+)x(?:\^(\([+-]?[0-9/]+\)|[+-]?[0-9]+))?/g; + var arr; + var res = {}; + while (null !== (arr = regex.exec(poly))) { + + var a = (arr[1] || "1").replace("(", "").replace(")", "").split("/"); + var b = (arr[2] || "1").replace("(", "").replace(")", "").split("/"); + + var exp = new Fraction(b).add(1); + var key = "" + exp; + + if (res[key] !== undefined) { + res[key] = { x: new Fraction(a).div(exp).add(res[key].x), e: exp }; + } else { + res[key] = { x: new Fraction(a).div(exp), e: exp }; + } + } + + var str = ""; + var c = 0; + for (var i in res) { + if (res[i].x.s !== -1n && c > 0) { + str += "+"; + } else if (res[i].x.s === -1n) { + str += "-"; + } + if (res[i].x.n !== res[i].x.d) { + if (res[i].x.d !== 1n) { + str += res[i].x.n + "/" + res[i].x.d; + } else { + str += res[i].x.n; + } + } + str += "x"; + if (res[i].e.n !== res[i].e.d) { + str += "^"; + if (res[i].e.d !== 1n) { + str += "(" + res[i].e.n + "/" + res[i].e.d + ")"; + } else { + str += res[i].e.n; + } + } + c++; + } + return str; +} + +var poly = "-2/3x^3-2x^2+3x+8x^3-1/3x^(4/8)"; + +console.log("f(x): " + poly); +console.log("F(x): " + integrate(poly)); diff --git a/client/node_modules/fraction.js/examples/ratio-chain.js b/client/node_modules/fraction.js/examples/ratio-chain.js new file mode 100644 index 0000000..fab7876 --- /dev/null +++ b/client/node_modules/fraction.js/examples/ratio-chain.js @@ -0,0 +1,24 @@ +/* +Given the ratio a : b : c = 2 : 3 : 4 +What is c, given a = 40? + +A general ratio chain is a_1 : a_2 : a_3 : ... : a_n = r_1 : r2 : r_3 : ... : r_n. +Now each term can be expressed as a_i = r_i * x for some unknown proportional constant x. +If a_k is known it follows that x = a_k / r_k. Substituting x into the first equation yields +a_i = r_i / r_k * a_k. + +Given an array r and a given value a_k, the following function calculates all a_i: +*/ + +function calculateRatios(r, a_k, k) { + const x = Fraction(a_k).div(r[k]); + return r.map(r_i => x.mul(r_i)); +} + +// Example usage: +const r = [2, 3, 4]; // Ratio array representing a : b : c = 2 : 3 : 4 +const a_k = 40; // Given value of a (corresponding to r[0]) +const k = 0; // Index of the known value (a corresponds to r[0]) + +const result = calculateRatios(r, a_k, k); +console.log(result); // Output: [40, 60, 80] diff --git a/client/node_modules/fraction.js/examples/rational-pow.js b/client/node_modules/fraction.js/examples/rational-pow.js new file mode 100644 index 0000000..1268e27 --- /dev/null +++ b/client/node_modules/fraction.js/examples/rational-pow.js @@ -0,0 +1,29 @@ +/* +Fraction.js v5.0.0 10/1/2024 +https://raw.org/article/rational-numbers-in-javascript/ + +Copyright (c) 2024, Robert Eisele (https://raw.org/) +Licensed under the MIT license. +*/ +const Fraction = require('fraction.js'); + +// Calculates (a/b)^(c/d) if result is rational +// Derivation: https://raw.org/book/analysis/rational-numbers/ +function root(a, b, c, d) { + + // Initial estimate + let x = Fraction(100 * (Math.floor(Math.pow(a / b, c / d)) || 1), 100); + const abc = Fraction(a, b).pow(c); + + for (let i = 0; i < 30; i++) { + const n = abc.mul(x.pow(1 - d)).sub(x).div(d).add(x) + + if (x.n === n.n && x.d === n.d) { + return n; + } + x = n; + } + return null; +} + +root(18, 2, 1, 2); // 3/1 diff --git a/client/node_modules/fraction.js/examples/tape-measure.js b/client/node_modules/fraction.js/examples/tape-measure.js new file mode 100644 index 0000000..14ec524 --- /dev/null +++ b/client/node_modules/fraction.js/examples/tape-measure.js @@ -0,0 +1,16 @@ +/* +Fraction.js v5.0.0 10/1/2024 +https://raw.org/article/rational-numbers-in-javascript/ + +Copyright (c) 2024, Robert Eisele (https://raw.org/) +Licensed under the MIT license. +*/ +const Fraction = require('fraction.js'); + +function closestTapeMeasure(frac) { + + // A tape measure is usually divided in parts of 1/16 + + return Fraction(frac).roundTo("1/16"); +} +console.log(closestTapeMeasure("1/3")); // 5/16 diff --git a/client/node_modules/fraction.js/examples/toFraction.js b/client/node_modules/fraction.js/examples/toFraction.js new file mode 100644 index 0000000..f935e47 --- /dev/null +++ b/client/node_modules/fraction.js/examples/toFraction.js @@ -0,0 +1,35 @@ +/* +Fraction.js v5.0.0 10/1/2024 +https://raw.org/article/rational-numbers-in-javascript/ + +Copyright (c) 2024, Robert Eisele (https://raw.org/) +Licensed under the MIT license. +*/ + +const Fraction = require('fraction.js'); + +function toFraction(frac) { + + var map = { + '1:4': "¼", + '1:2': "½", + '3:4': "¾", + '1:7': "⅐", + '1:9': "⅑", + '1:10': "⅒", + '1:3': "⅓", + '2:3': "⅔", + '1:5': "⅕", + '2:5': "⅖", + '3:5': "⅗", + '4:5': "⅘", + '1:6': "⅙", + '5:6': "⅚", + '1:8': "⅛", + '3:8': "⅜", + '5:8': "⅝", + '7:8': "⅞" + }; + return map[frac.n + ":" + frac.d] || frac.toFraction(false); +} +console.log(toFraction(Fraction(0.25))); // ¼ diff --git a/client/node_modules/fraction.js/examples/valueOfPi.js b/client/node_modules/fraction.js/examples/valueOfPi.js new file mode 100644 index 0000000..8fc877e --- /dev/null +++ b/client/node_modules/fraction.js/examples/valueOfPi.js @@ -0,0 +1,42 @@ +/* +Fraction.js v5.0.0 10/1/2024 +https://raw.org/article/rational-numbers-in-javascript/ + +Copyright (c) 2024, Robert Eisele (https://raw.org/) +Licensed under the MIT license. +*/ + +var Fraction = require("fraction.js") + +function valueOfPi(val) { + + let minLen = Infinity, minI = 0, min = null; + const choose = [val, val * Math.PI, val / Math.PI]; + for (let i = 0; i < choose.length; i++) { + let el = new Fraction(choose[i]).simplify(1e-13); + let len = Math.log(Number(el.n) + 1) + Math.log(Number(el.d)); + if (len < minLen) { + minLen = len; + minI = i; + min = el; + } + } + + if (minI == 2) { + return min.toFraction().replace(/(\d+)(\/\d+)?/, (_, p, q) => + (p == "1" ? "" : p) + "π" + (q || "")); + } + + if (minI == 1) { + return min.toFraction().replace(/(\d+)(\/\d+)?/, (_, p, q) => + p + (!q ? "/π" : "/(" + q.slice(1) + "π)")); + } + return min.toFraction(); +} + +console.log(valueOfPi(-3)); // -3 +console.log(valueOfPi(4 * Math.PI)); // 4π +console.log(valueOfPi(3.14)); // 157/50 +console.log(valueOfPi(3 / 2 * Math.PI)); // 3π/2 +console.log(valueOfPi(Math.PI / 2)); // π/2 +console.log(valueOfPi(-1 / (2 * Math.PI))); // -1/(2π) diff --git a/client/node_modules/fraction.js/fraction.d.mts b/client/node_modules/fraction.js/fraction.d.mts new file mode 100644 index 0000000..0604ad7 --- /dev/null +++ b/client/node_modules/fraction.js/fraction.d.mts @@ -0,0 +1,79 @@ +/** + * Interface representing a fraction with numerator and denominator. + */ +export interface NumeratorDenominator { + n: number | bigint; + d: number | bigint; +} + +/** + * Type for handling multiple types of input for Fraction operations. + */ +export type FractionInput = + | Fraction + | number + | bigint + | string + | [number | bigint | string, number | bigint | string] + | NumeratorDenominator; + +/** + * Function signature for Fraction operations like add, sub, mul, etc. + */ +export type FractionParam = { + (numerator: number | bigint, denominator: number | bigint): Fraction; + (num: FractionInput): Fraction; +}; + +/** + * Fraction class representing a rational number with numerator and denominator. + */ +declare class Fraction { + constructor(); + constructor(num: FractionInput); + constructor(numerator: number | bigint, denominator: number | bigint); + + s: bigint; + n: bigint; + d: bigint; + + abs(): Fraction; + neg(): Fraction; + + add: FractionParam; + sub: FractionParam; + mul: FractionParam; + div: FractionParam; + pow: FractionParam; + log: FractionParam; + gcd: FractionParam; + lcm: FractionParam; + + mod(): Fraction; + mod(num: FractionInput): Fraction; + + ceil(places?: number): Fraction; + floor(places?: number): Fraction; + round(places?: number): Fraction; + roundTo: FractionParam; + + inverse(): Fraction; + simplify(eps?: number): Fraction; + + equals(num: FractionInput): boolean; + lt(num: FractionInput): boolean; + lte(num: FractionInput): boolean; + gt(num: FractionInput): boolean; + gte(num: FractionInput): boolean; + compare(num: FractionInput): number; + divisible(num: FractionInput): boolean; + + valueOf(): number; + toString(decimalPlaces?: number): string; + toLatex(showMixed?: boolean): string; + toFraction(showMixed?: boolean): string; + toContinued(): bigint[]; + clone(): Fraction; +} + +export { Fraction as default, Fraction }; \ No newline at end of file diff --git a/client/node_modules/fraction.js/fraction.d.ts b/client/node_modules/fraction.js/fraction.d.ts new file mode 100644 index 0000000..97222b9 --- /dev/null +++ b/client/node_modules/fraction.js/fraction.d.ts @@ -0,0 +1,79 @@ +declare class Fraction { + constructor(); + constructor(num: Fraction.FractionInput); + constructor(numerator: number | bigint, denominator: number | bigint); + + s: bigint; + n: bigint; + d: bigint; + + abs(): Fraction; + neg(): Fraction; + + add: Fraction.FractionParam; + sub: Fraction.FractionParam; + mul: Fraction.FractionParam; + div: Fraction.FractionParam; + pow: Fraction.FractionParam; + log: Fraction.FractionParam; + gcd: Fraction.FractionParam; + lcm: Fraction.FractionParam; + + mod(): Fraction; + mod(num: Fraction.FractionInput): Fraction; + + ceil(places?: number): Fraction; + floor(places?: number): Fraction; + round(places?: number): Fraction; + roundTo: Fraction.FractionParam; + + inverse(): Fraction; + simplify(eps?: number): Fraction; + + equals(num: Fraction.FractionInput): boolean; + lt(num: Fraction.FractionInput): boolean; + lte(num: Fraction.FractionInput): boolean; + gt(num: Fraction.FractionInput): boolean; + gte(num: Fraction.FractionInput): boolean; + compare(num: Fraction.FractionInput): number; + divisible(num: Fraction.FractionInput): boolean; + + valueOf(): number; + toString(decimalPlaces?: number): string; + toLatex(showMixed?: boolean): string; + toFraction(showMixed?: boolean): string; + toContinued(): bigint[]; + clone(): Fraction; + + static default: typeof Fraction; + static Fraction: typeof Fraction; +} + +declare namespace Fraction { + interface NumeratorDenominator { n: number | bigint; d: number | bigint; } + type FractionInput = + | Fraction + | number + | bigint + | string + | [number | bigint | string, number | bigint | string] + | NumeratorDenominator; + + type FractionParam = { + (numerator: number | bigint, denominator: number | bigint): Fraction; + (num: FractionInput): Fraction; + }; +} + +/** + * Export matches CJS runtime: + * module.exports = Fraction; + * module.exports.default = Fraction; + * module.exports.Fraction = Fraction; + */ +declare const FractionExport: typeof Fraction & { + default: typeof Fraction; + Fraction: typeof Fraction; +}; + +export = FractionExport; \ No newline at end of file diff --git a/client/node_modules/fraction.js/package.json b/client/node_modules/fraction.js/package.json new file mode 100644 index 0000000..03f7986 --- /dev/null +++ b/client/node_modules/fraction.js/package.json @@ -0,0 +1,81 @@ +{ + "name": "fraction.js", + "title": "Fraction.js", + "version": "5.3.4", + "description": "The RAW rational numbers library", + "homepage": "https://raw.org/article/rational-numbers-in-javascript/", + "bugs": "https://github.com/rawify/Fraction.js/issues", + "keywords": [ + "math", + "numbers", + "parser", + "ratio", + "fraction", + "fractions", + "rational", + "rationals", + "rational numbers", + "bigint", + "arbitrary precision", + "mixed numbers", + "decimal", + "numerator", + "denominator", + "simplification" + ], + "private": false, + "main": "./dist/fraction.js", + "module": "./dist/fraction.mjs", + "browser": "./dist/fraction.min.js", + "unpkg": "./dist/fraction.min.js", + "types": "./fraction.d.mts", + "exports": { + ".": { + "types": { + "import": "./fraction.d.mts", + "require": "./fraction.d.ts" + }, + "import": "./dist/fraction.mjs", + "require": "./dist/fraction.js", + "browser": "./dist/fraction.min.js" + }, + "./package.json": "./package.json" + }, + "typesVersions": { + "<4.7": { + "*": [ + "fraction.d.ts" + ] + } + }, + "sideEffects": false, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/rawify/Fraction.js.git" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/rawify" + }, + "author": { + "name": "Robert Eisele", + "email": "robert@raw.org", + "url": "https://raw.org/" + }, + "license": "MIT", + "engines": { + "node": "*" + }, + "directories": { + "example": "examples", + "test": "tests" + }, + "scripts": { + "build": "crude-build Fraction", + "test": "mocha tests/*.js" + }, + "devDependencies": { + "crude-build": "^0.1.2", + "mocha": "*" + } +} \ No newline at end of file diff --git a/client/node_modules/fraction.js/src/fraction.js b/client/node_modules/fraction.js/src/fraction.js new file mode 100644 index 0000000..4292c48 --- /dev/null +++ b/client/node_modules/fraction.js/src/fraction.js @@ -0,0 +1,1046 @@ +/** + * @license Fraction.js v5.3.4 8/22/2025 + * https://raw.org/article/rational-numbers-in-javascript/ + * + * Copyright (c) 2025, Robert Eisele (https://raw.org/) + * Licensed under the MIT license. + **/ + +/** + * + * This class offers the possibility to calculate fractions. + * You can pass a fraction in different formats. Either as array, as double, as string or as an integer. + * + * Array/Object form + * [ 0 => , 1 => ] + * { n => , d => } + * + * Integer form + * - Single integer value as BigInt or Number + * + * Double form + * - Single double value as Number + * + * String form + * 123.456 - a simple double + * 123/456 - a string fraction + * 123.'456' - a double with repeating decimal places + * 123.(456) - synonym + * 123.45'6' - a double with repeating last place + * 123.45(6) - synonym + * + * Example: + * let f = new Fraction("9.4'31'"); + * f.mul([-4, 3]).div(4.9); + * + */ + +// Set Identity function to downgrade BigInt to Number if needed +if (typeof BigInt === 'undefined') BigInt = function (n) { if (isNaN(n)) throw new Error(""); return n; }; + +const C_ZERO = BigInt(0); +const C_ONE = BigInt(1); +const C_TWO = BigInt(2); +const C_THREE = BigInt(3); +const C_FIVE = BigInt(5); +const C_TEN = BigInt(10); +const MAX_INTEGER = BigInt(Number.MAX_SAFE_INTEGER); + +// Maximum search depth for cyclic rational numbers. 2000 should be more than enough. +// Example: 1/7 = 0.(142857) has 6 repeating decimal places. +// If MAX_CYCLE_LEN gets reduced, long cycles will not be detected and toString() only gets the first 10 digits +const MAX_CYCLE_LEN = 2000; + +// Parsed data to avoid calling "new" all the time +const P = { + "s": C_ONE, + "n": C_ZERO, + "d": C_ONE +}; + +function assign(n, s) { + + try { + n = BigInt(n); + } catch (e) { + throw InvalidParameter(); + } + return n * s; +} + +function ifloor(x) { + return typeof x === 'bigint' ? x : Math.floor(x); +} + +// Creates a new Fraction internally without the need of the bulky constructor +function newFraction(n, d) { + + if (d === C_ZERO) { + throw DivisionByZero(); + } + + const f = Object.create(Fraction.prototype); + f["s"] = n < C_ZERO ? -C_ONE : C_ONE; + + n = n < C_ZERO ? -n : n; + + const a = gcd(n, d); + + f["n"] = n / a; + f["d"] = d / a; + return f; +} + +const FACTORSTEPS = [C_TWO * C_TWO, C_TWO, C_TWO * C_TWO, C_TWO, C_TWO * C_TWO, C_TWO * C_THREE, C_TWO, C_TWO * C_THREE]; // repeats +function factorize(n) { + + const factors = Object.create(null); + if (n <= C_ONE) { + factors[n] = C_ONE; + return factors; + } + + const add = (p) => { factors[p] = (factors[p] || C_ZERO) + C_ONE; }; + + while (n % C_TWO === C_ZERO) { add(C_TWO); n /= C_TWO; } + while (n % C_THREE === C_ZERO) { add(C_THREE); n /= C_THREE; } + while (n % C_FIVE === C_ZERO) { add(C_FIVE); n /= C_FIVE; } + + // 30-wheel trial division: test only residues coprime to 2*3*5 + // Residue step pattern after 5: 7,11,13,17,19,23,29,31, ... + for (let si = 0, p = C_TWO + C_FIVE; p * p <= n;) { + while (n % p === C_ZERO) { add(p); n /= p; } + p += FACTORSTEPS[si]; + si = (si + 1) & 7; // fast modulo 8 + } + if (n > C_ONE) add(n); + return factors; +} + +const parse = function (p1, p2) { + + let n = C_ZERO, d = C_ONE, s = C_ONE; + + if (p1 === undefined || p1 === null) { // No argument + /* void */ + } else if (p2 !== undefined) { // Two arguments + + if (typeof p1 === "bigint") { + n = p1; + } else if (isNaN(p1)) { + throw InvalidParameter(); + } else if (p1 % 1 !== 0) { + throw NonIntegerParameter(); + } else { + n = BigInt(p1); + } + + if (typeof p2 === "bigint") { + d = p2; + } else if (isNaN(p2)) { + throw InvalidParameter(); + } else if (p2 % 1 !== 0) { + throw NonIntegerParameter(); + } else { + d = BigInt(p2); + } + + s = n * d; + + } else if (typeof p1 === "object") { + if ("d" in p1 && "n" in p1) { + n = BigInt(p1["n"]); + d = BigInt(p1["d"]); + if ("s" in p1) + n *= BigInt(p1["s"]); + } else if (0 in p1) { + n = BigInt(p1[0]); + if (1 in p1) + d = BigInt(p1[1]); + } else if (typeof p1 === "bigint") { + n = p1; + } else { + throw InvalidParameter(); + } + s = n * d; + } else if (typeof p1 === "number") { + + if (isNaN(p1)) { + throw InvalidParameter(); + } + + if (p1 < 0) { + s = -C_ONE; + p1 = -p1; + } + + if (p1 % 1 === 0) { + n = BigInt(p1); + } else { + + let z = 1; + + let A = 0, B = 1; + let C = 1, D = 1; + + let N = 10000000; + + if (p1 >= 1) { + z = 10 ** Math.floor(1 + Math.log10(p1)); + p1 /= z; + } + + // Using Farey Sequences + + while (B <= N && D <= N) { + let M = (A + C) / (B + D); + + if (p1 === M) { + if (B + D <= N) { + n = A + C; + d = B + D; + } else if (D > B) { + n = C; + d = D; + } else { + n = A; + d = B; + } + break; + + } else { + + if (p1 > M) { + A += C; + B += D; + } else { + C += A; + D += B; + } + + if (B > N) { + n = C; + d = D; + } else { + n = A; + d = B; + } + } + } + n = BigInt(n) * BigInt(z); + d = BigInt(d); + } + + } else if (typeof p1 === "string") { + + let ndx = 0; + + let v = C_ZERO, w = C_ZERO, x = C_ZERO, y = C_ONE, z = C_ONE; + + let match = p1.replace(/_/g, '').match(/\d+|./g); + + if (match === null) + throw InvalidParameter(); + + if (match[ndx] === '-') {// Check for minus sign at the beginning + s = -C_ONE; + ndx++; + } else if (match[ndx] === '+') {// Check for plus sign at the beginning + ndx++; + } + + if (match.length === ndx + 1) { // Check if it's just a simple number "1234" + w = assign(match[ndx++], s); + } else if (match[ndx + 1] === '.' || match[ndx] === '.') { // Check if it's a decimal number + + if (match[ndx] !== '.') { // Handle 0.5 and .5 + v = assign(match[ndx++], s); + } + ndx++; + + // Check for decimal places + if (ndx + 1 === match.length || match[ndx + 1] === '(' && match[ndx + 3] === ')' || match[ndx + 1] === "'" && match[ndx + 3] === "'") { + w = assign(match[ndx], s); + y = C_TEN ** BigInt(match[ndx].length); + ndx++; + } + + // Check for repeating places + if (match[ndx] === '(' && match[ndx + 2] === ')' || match[ndx] === "'" && match[ndx + 2] === "'") { + x = assign(match[ndx + 1], s); + z = C_TEN ** BigInt(match[ndx + 1].length) - C_ONE; + ndx += 3; + } + + } else if (match[ndx + 1] === '/' || match[ndx + 1] === ':') { // Check for a simple fraction "123/456" or "123:456" + w = assign(match[ndx], s); + y = assign(match[ndx + 2], C_ONE); + ndx += 3; + } else if (match[ndx + 3] === '/' && match[ndx + 1] === ' ') { // Check for a complex fraction "123 1/2" + v = assign(match[ndx], s); + w = assign(match[ndx + 2], s); + y = assign(match[ndx + 4], C_ONE); + ndx += 5; + } + + if (match.length <= ndx) { // Check for more tokens on the stack + d = y * z; + s = /* void */ + n = x + d * v + z * w; + } else { + throw InvalidParameter(); + } + + } else if (typeof p1 === "bigint") { + n = p1; + s = p1; + d = C_ONE; + } else { + throw InvalidParameter(); + } + + if (d === C_ZERO) { + throw DivisionByZero(); + } + + P["s"] = s < C_ZERO ? -C_ONE : C_ONE; + P["n"] = n < C_ZERO ? -n : n; + P["d"] = d < C_ZERO ? -d : d; +}; + +function modpow(b, e, m) { + + let r = C_ONE; + for (; e > C_ZERO; b = (b * b) % m, e >>= C_ONE) { + + if (e & C_ONE) { + r = (r * b) % m; + } + } + return r; +} + +function cycleLen(n, d) { + + for (; d % C_TWO === C_ZERO; + d /= C_TWO) { + } + + for (; d % C_FIVE === C_ZERO; + d /= C_FIVE) { + } + + if (d === C_ONE) // Catch non-cyclic numbers + return C_ZERO; + + // If we would like to compute really large numbers quicker, we could make use of Fermat's little theorem: + // 10^(d-1) % d == 1 + // However, we don't need such large numbers and MAX_CYCLE_LEN should be the capstone, + // as we want to translate the numbers to strings. + + let rem = C_TEN % d; + let t = 1; + + for (; rem !== C_ONE; t++) { + rem = rem * C_TEN % d; + + if (t > MAX_CYCLE_LEN) + return C_ZERO; // Returning 0 here means that we don't print it as a cyclic number. It's likely that the answer is `d-1` + } + return BigInt(t); +} + +function cycleStart(n, d, len) { + + let rem1 = C_ONE; + let rem2 = modpow(C_TEN, len, d); + + for (let t = 0; t < 300; t++) { // s < ~log10(Number.MAX_VALUE) + // Solve 10^s == 10^(s+t) (mod d) + + if (rem1 === rem2) + return BigInt(t); + + rem1 = rem1 * C_TEN % d; + rem2 = rem2 * C_TEN % d; + } + return 0; +} + +function gcd(a, b) { + + if (!a) + return b; + if (!b) + return a; + + while (1) { + a %= b; + if (!a) + return b; + b %= a; + if (!b) + return a; + } +} + +/** + * Module constructor + * + * @constructor + * @param {number|Fraction=} a + * @param {number=} b + */ +function Fraction(a, b) { + + parse(a, b); + + if (this instanceof Fraction) { + a = gcd(P["d"], P["n"]); // Abuse a + this["s"] = P["s"]; + this["n"] = P["n"] / a; + this["d"] = P["d"] / a; + } else { + return newFraction(P['s'] * P['n'], P['d']); + } +} + +const DivisionByZero = function () { return new Error("Division by Zero"); }; +const InvalidParameter = function () { return new Error("Invalid argument"); }; +const NonIntegerParameter = function () { return new Error("Parameters must be integer"); }; + +Fraction.prototype = { + + "s": C_ONE, + "n": C_ZERO, + "d": C_ONE, + + /** + * Calculates the absolute value + * + * Ex: new Fraction(-4).abs() => 4 + **/ + "abs": function () { + + return newFraction(this["n"], this["d"]); + }, + + /** + * Inverts the sign of the current fraction + * + * Ex: new Fraction(-4).neg() => 4 + **/ + "neg": function () { + + return newFraction(-this["s"] * this["n"], this["d"]); + }, + + /** + * Adds two rational numbers + * + * Ex: new Fraction({n: 2, d: 3}).add("14.9") => 467 / 30 + **/ + "add": function (a, b) { + + parse(a, b); + return newFraction( + this["s"] * this["n"] * P["d"] + P["s"] * this["d"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Subtracts two rational numbers + * + * Ex: new Fraction({n: 2, d: 3}).add("14.9") => -427 / 30 + **/ + "sub": function (a, b) { + + parse(a, b); + return newFraction( + this["s"] * this["n"] * P["d"] - P["s"] * this["d"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Multiplies two rational numbers + * + * Ex: new Fraction("-17.(345)").mul(3) => 5776 / 111 + **/ + "mul": function (a, b) { + + parse(a, b); + return newFraction( + this["s"] * P["s"] * this["n"] * P["n"], + this["d"] * P["d"] + ); + }, + + /** + * Divides two rational numbers + * + * Ex: new Fraction("-17.(345)").inverse().div(3) + **/ + "div": function (a, b) { + + parse(a, b); + return newFraction( + this["s"] * P["s"] * this["n"] * P["d"], + this["d"] * P["n"] + ); + }, + + /** + * Clones the actual object + * + * Ex: new Fraction("-17.(345)").clone() + **/ + "clone": function () { + return newFraction(this['s'] * this['n'], this['d']); + }, + + /** + * Calculates the modulo of two rational numbers - a more precise fmod + * + * Ex: new Fraction('4.(3)').mod([7, 8]) => (13/3) % (7/8) = (5/6) + * Ex: new Fraction(20, 10).mod().equals(0) ? "is Integer" + **/ + "mod": function (a, b) { + + if (a === undefined) { + return newFraction(this["s"] * this["n"] % this["d"], C_ONE); + } + + parse(a, b); + if (C_ZERO === P["n"] * this["d"]) { + throw DivisionByZero(); + } + + /** + * I derived the rational modulo similar to the modulo for integers + * + * https://raw.org/book/analysis/rational-numbers/ + * + * n1/d1 = (n2/d2) * q + r, where 0 ≤ r < n2/d2 + * => d2 * n1 = n2 * d1 * q + d1 * d2 * r + * => r = (d2 * n1 - n2 * d1 * q) / (d1 * d2) + * = (d2 * n1 - n2 * d1 * floor((d2 * n1) / (n2 * d1))) / (d1 * d2) + * = ((d2 * n1) % (n2 * d1)) / (d1 * d2) + */ + return newFraction( + this["s"] * (P["d"] * this["n"]) % (P["n"] * this["d"]), + P["d"] * this["d"]); + }, + + /** + * Calculates the fractional gcd of two rational numbers + * + * Ex: new Fraction(5,8).gcd(3,7) => 1/56 + */ + "gcd": function (a, b) { + + parse(a, b); + + // https://raw.org/book/analysis/rational-numbers/ + // gcd(a / b, c / d) = gcd(a, c) / lcm(b, d) + + return newFraction(gcd(P["n"], this["n"]) * gcd(P["d"], this["d"]), P["d"] * this["d"]); + }, + + /** + * Calculates the fractional lcm of two rational numbers + * + * Ex: new Fraction(5,8).lcm(3,7) => 15 + */ + "lcm": function (a, b) { + + parse(a, b); + + // https://raw.org/book/analysis/rational-numbers/ + // lcm(a / b, c / d) = lcm(a, c) / gcd(b, d) + + if (P["n"] === C_ZERO && this["n"] === C_ZERO) { + return newFraction(C_ZERO, C_ONE); + } + return newFraction(P["n"] * this["n"], gcd(P["n"], this["n"]) * gcd(P["d"], this["d"])); + }, + + /** + * Gets the inverse of the fraction, means numerator and denominator are exchanged + * + * Ex: new Fraction([-3, 4]).inverse() => -4 / 3 + **/ + "inverse": function () { + return newFraction(this["s"] * this["d"], this["n"]); + }, + + /** + * Calculates the fraction to some integer exponent + * + * Ex: new Fraction(-1,2).pow(-3) => -8 + */ + "pow": function (a, b) { + + parse(a, b); + + // Trivial case when exp is an integer + + if (P['d'] === C_ONE) { + + if (P['s'] < C_ZERO) { + return newFraction((this['s'] * this["d"]) ** P['n'], this["n"] ** P['n']); + } else { + return newFraction((this['s'] * this["n"]) ** P['n'], this["d"] ** P['n']); + } + } + + // Negative roots become complex + // (-a/b)^(c/d) = x + // ⇔ (-1)^(c/d) * (a/b)^(c/d) = x + // ⇔ (cos(pi) + i*sin(pi))^(c/d) * (a/b)^(c/d) = x + // ⇔ (cos(c*pi/d) + i*sin(c*pi/d)) * (a/b)^(c/d) = x # DeMoivre's formula + // From which follows that only for c=0 the root is non-complex + if (this['s'] < C_ZERO) return null; + + // Now prime factor n and d + let N = factorize(this['n']); + let D = factorize(this['d']); + + // Exponentiate and take root for n and d individually + let n = C_ONE; + let d = C_ONE; + for (let k in N) { + if (k === '1') continue; + if (k === '0') { + n = C_ZERO; + break; + } + N[k] *= P['n']; + + if (N[k] % P['d'] === C_ZERO) { + N[k] /= P['d']; + } else return null; + n *= BigInt(k) ** N[k]; + } + + for (let k in D) { + if (k === '1') continue; + D[k] *= P['n']; + + if (D[k] % P['d'] === C_ZERO) { + D[k] /= P['d']; + } else return null; + d *= BigInt(k) ** D[k]; + } + + if (P['s'] < C_ZERO) { + return newFraction(d, n); + } + return newFraction(n, d); + }, + + /** + * Calculates the logarithm of a fraction to a given rational base + * + * Ex: new Fraction(27, 8).log(9, 4) => 3/2 + */ + "log": function (a, b) { + + parse(a, b); + + if (this['s'] <= C_ZERO || P['s'] <= C_ZERO) return null; + + const allPrimes = Object.create(null); + + const baseFactors = factorize(P['n']); + const T1 = factorize(P['d']); + + const numberFactors = factorize(this['n']); + const T2 = factorize(this['d']); + + for (const prime in T1) { + baseFactors[prime] = (baseFactors[prime] || C_ZERO) - T1[prime]; + } + for (const prime in T2) { + numberFactors[prime] = (numberFactors[prime] || C_ZERO) - T2[prime]; + } + + for (const prime in baseFactors) { + if (prime === '1') continue; + allPrimes[prime] = true; + } + for (const prime in numberFactors) { + if (prime === '1') continue; + allPrimes[prime] = true; + } + + let retN = null; + let retD = null; + + // Iterate over all unique primes to determine if a consistent ratio exists + for (const prime in allPrimes) { + + const baseExponent = baseFactors[prime] || C_ZERO; + const numberExponent = numberFactors[prime] || C_ZERO; + + if (baseExponent === C_ZERO) { + if (numberExponent !== C_ZERO) { + return null; // Logarithm cannot be expressed as a rational number + } + continue; // Skip this prime since both exponents are zero + } + + // Calculate the ratio of exponents for this prime + let curN = numberExponent; + let curD = baseExponent; + + // Simplify the current ratio + const gcdValue = gcd(curN, curD); + curN /= gcdValue; + curD /= gcdValue; + + // Check if this is the first ratio; otherwise, ensure ratios are consistent + if (retN === null && retD === null) { + retN = curN; + retD = curD; + } else if (curN * retD !== retN * curD) { + return null; // Ratios do not match, logarithm cannot be rational + } + } + + return retN !== null && retD !== null + ? newFraction(retN, retD) + : null; + }, + + /** + * Check if two rational numbers are the same + * + * Ex: new Fraction(19.6).equals([98, 5]); + **/ + "equals": function (a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] === P["s"] * P["n"] * this["d"]; + }, + + /** + * Check if this rational number is less than another + * + * Ex: new Fraction(19.6).lt([98, 5]); + **/ + "lt": function (a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] < P["s"] * P["n"] * this["d"]; + }, + + /** + * Check if this rational number is less than or equal another + * + * Ex: new Fraction(19.6).lt([98, 5]); + **/ + "lte": function (a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] <= P["s"] * P["n"] * this["d"]; + }, + + /** + * Check if this rational number is greater than another + * + * Ex: new Fraction(19.6).lt([98, 5]); + **/ + "gt": function (a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] > P["s"] * P["n"] * this["d"]; + }, + + /** + * Check if this rational number is greater than or equal another + * + * Ex: new Fraction(19.6).lt([98, 5]); + **/ + "gte": function (a, b) { + + parse(a, b); + return this["s"] * this["n"] * P["d"] >= P["s"] * P["n"] * this["d"]; + }, + + /** + * Compare two rational numbers + * < 0 iff this < that + * > 0 iff this > that + * = 0 iff this = that + * + * Ex: new Fraction(19.6).compare([98, 5]); + **/ + "compare": function (a, b) { + + parse(a, b); + let t = this["s"] * this["n"] * P["d"] - P["s"] * P["n"] * this["d"]; + + return (C_ZERO < t) - (t < C_ZERO); + }, + + /** + * Calculates the ceil of a rational number + * + * Ex: new Fraction('4.(3)').ceil() => (5 / 1) + **/ + "ceil": function (places) { + + places = C_TEN ** BigInt(places || 0); + + return newFraction(ifloor(this["s"] * places * this["n"] / this["d"]) + + (places * this["n"] % this["d"] > C_ZERO && this["s"] >= C_ZERO ? C_ONE : C_ZERO), + places); + }, + + /** + * Calculates the floor of a rational number + * + * Ex: new Fraction('4.(3)').floor() => (4 / 1) + **/ + "floor": function (places) { + + places = C_TEN ** BigInt(places || 0); + + return newFraction(ifloor(this["s"] * places * this["n"] / this["d"]) - + (places * this["n"] % this["d"] > C_ZERO && this["s"] < C_ZERO ? C_ONE : C_ZERO), + places); + }, + + /** + * Rounds a rational numbers + * + * Ex: new Fraction('4.(3)').round() => (4 / 1) + **/ + "round": function (places) { + + places = C_TEN ** BigInt(places || 0); + + /* Derivation: + + s >= 0: + round(n / d) = ifloor(n / d) + (n % d) / d >= 0.5 ? 1 : 0 + = ifloor(n / d) + 2(n % d) >= d ? 1 : 0 + s < 0: + round(n / d) =-ifloor(n / d) - (n % d) / d > 0.5 ? 1 : 0 + =-ifloor(n / d) - 2(n % d) > d ? 1 : 0 + + =>: + + round(s * n / d) = s * ifloor(n / d) + s * (C + 2(n % d) > d ? 1 : 0) + where C = s >= 0 ? 1 : 0, to fix the >= for the positve case. + */ + + return newFraction(ifloor(this["s"] * places * this["n"] / this["d"]) + + this["s"] * ((this["s"] >= C_ZERO ? C_ONE : C_ZERO) + C_TWO * (places * this["n"] % this["d"]) > this["d"] ? C_ONE : C_ZERO), + places); + }, + + /** + * Rounds a rational number to a multiple of another rational number + * + * Ex: new Fraction('0.9').roundTo("1/8") => 7 / 8 + **/ + "roundTo": function (a, b) { + + /* + k * x/y ≤ a/b < (k+1) * x/y + ⇔ k ≤ a/b / (x/y) < (k+1) + ⇔ k = floor(a/b * y/x) + ⇔ k = floor((a * y) / (b * x)) + */ + + parse(a, b); + + const n = this['n'] * P['d']; + const d = this['d'] * P['n']; + const r = n % d; + + // round(n / d) = ifloor(n / d) + 2(n % d) >= d ? 1 : 0 + let k = ifloor(n / d); + if (r + r >= d) { + k++; + } + return newFraction(this['s'] * k * P['n'], P['d']); + }, + + /** + * Check if two rational numbers are divisible + * + * Ex: new Fraction(19.6).divisible(1.5); + */ + "divisible": function (a, b) { + + parse(a, b); + if (P['n'] === C_ZERO) return false; + return (this['n'] * P['d']) % (P['n'] * this['d']) === C_ZERO; + }, + + /** + * Returns a decimal representation of the fraction + * + * Ex: new Fraction("100.'91823'").valueOf() => 100.91823918239183 + **/ + 'valueOf': function () { + //if (this['n'] <= MAX_INTEGER && this['d'] <= MAX_INTEGER) { + return Number(this['s'] * this['n']) / Number(this['d']); + //} + }, + + /** + * Creates a string representation of a fraction with all digits + * + * Ex: new Fraction("100.'91823'").toString() => "100.(91823)" + **/ + 'toString': function (dec = 15) { + + let N = this["n"]; + let D = this["d"]; + + let cycLen = cycleLen(N, D); // Cycle length + let cycOff = cycleStart(N, D, cycLen); // Cycle start + + let str = this['s'] < C_ZERO ? "-" : ""; + + // Append integer part + str += ifloor(N / D); + + N %= D; + N *= C_TEN; + + if (N) + str += "."; + + if (cycLen) { + + for (let i = cycOff; i--;) { + str += ifloor(N / D); + N %= D; + N *= C_TEN; + } + str += "("; + for (let i = cycLen; i--;) { + str += ifloor(N / D); + N %= D; + N *= C_TEN; + } + str += ")"; + } else { + for (let i = dec; N && i--;) { + str += ifloor(N / D); + N %= D; + N *= C_TEN; + } + } + return str; + }, + + /** + * Returns a string-fraction representation of a Fraction object + * + * Ex: new Fraction("1.'3'").toFraction() => "4 1/3" + **/ + 'toFraction': function (showMixed = false) { + + let n = this["n"]; + let d = this["d"]; + let str = this['s'] < C_ZERO ? "-" : ""; + + if (d === C_ONE) { + str += n; + } else { + const whole = ifloor(n / d); + if (showMixed && whole > C_ZERO) { + str += whole; + str += " "; + n %= d; + } + + str += n; + str += '/'; + str += d; + } + return str; + }, + + /** + * Returns a latex representation of a Fraction object + * + * Ex: new Fraction("1.'3'").toLatex() => "\frac{4}{3}" + **/ + 'toLatex': function (showMixed = false) { + + let n = this["n"]; + let d = this["d"]; + let str = this['s'] < C_ZERO ? "-" : ""; + + if (d === C_ONE) { + str += n; + } else { + const whole = ifloor(n / d); + if (showMixed && whole > C_ZERO) { + str += whole; + n %= d; + } + + str += "\\frac{"; + str += n; + str += '}{'; + str += d; + str += '}'; + } + return str; + }, + + /** + * Returns an array of continued fraction elements + * + * Ex: new Fraction("7/8").toContinued() => [0,1,7] + */ + 'toContinued': function () { + + let a = this['n']; + let b = this['d']; + const res = []; + + while (b) { + res.push(ifloor(a / b)); + const t = a % b; + a = b; + b = t; + } + return res; + }, + + "simplify": function (eps = 1e-3) { + + // Continued fractions give best approximations for a max denominator, + // generally outperforming mediants in denominator–accuracy trade-offs. + // Semiconvergents can further reduce the denominator within tolerance. + + const ieps = BigInt(Math.ceil(1 / eps)); + + const thisABS = this['abs'](); + const cont = thisABS['toContinued'](); + + for (let i = 1; i < cont.length; i++) { + + let s = newFraction(cont[i - 1], C_ONE); + for (let k = i - 2; k >= 0; k--) { + s = s['inverse']()['add'](cont[k]); + } + + let t = s['sub'](thisABS); + if (t['n'] * ieps < t['d']) { // More robust than Math.abs(t.valueOf()) < eps + return s['mul'](this['s']); + } + } + return this; + } +}; diff --git a/client/node_modules/fraction.js/tests/fraction.test.js b/client/node_modules/fraction.js/tests/fraction.test.js new file mode 100644 index 0000000..b65833c --- /dev/null +++ b/client/node_modules/fraction.js/tests/fraction.test.js @@ -0,0 +1,1806 @@ +const Fraction = require('fraction.js'); +const assert = require('assert'); + +var DivisionByZero = function () { return new Error("Division by Zero"); }; +var InvalidParameter = function () { return new Error("Invalid argument"); }; +var NonIntegerParameter = function () { return new Error("Parameters must be integer"); }; + +var tests = [{ + set: "", + expectError: InvalidParameter() +}, { + set: "foo", + expectError: InvalidParameter() +}, { + set: " 123", + expectError: InvalidParameter() +}, { + set: 0, + expect: 0 +}, { + set: .2, + expect: "0.2" +}, { + set: .333, + expect: "0.333" +}, { + set: 1.1, + expect: "1.1" +}, { + set: 1.2, + expect: "1.2" +}, { + set: 1.3, + expect: "1.3" +}, { + set: 1.4, + expect: "1.4" +}, { + set: 1.5, + expect: "1.5" +}, { + set: 2.555, + expect: "2.555" +}, { + set: 1e12, + expect: "1000000000000" +}, { + set: " - ", + expectError: InvalidParameter() +}, { + set: ".5", + expect: "0.5" +}, { + set: "2_000_000", + expect: "2000000" +}, { + set: "-.5", + expect: "-0.5" +}, { + set: "123", + expect: "123" +}, { + set: "-123", + expect: "-123" +}, { + set: "123.4", + expect: "123.4" +}, { + set: "-123.4", + expect: "-123.4" +}, { + set: "123.", + expect: "123" +}, { + set: "-123.", + expect: "-123" +}, { + set: "123.4(56)", + expect: "123.4(56)" +}, { + set: "-123.4(56)", + expect: "-123.4(56)" +}, { + set: "123.(4)", + expect: "123.(4)" +}, { + set: "-123.(4)", + expect: "-123.(4)" +}, { + set: "0/0", + expectError: DivisionByZero() +}, { + set: "9/0", + expectError: DivisionByZero() +}, { + label: "0/1+0/1", + set: "0/1", + param: "0/1", + expect: "0" +}, { + label: "1/9+0/1", + set: "1/9", + param: "0/1", + expect: "0.(1)" +}, { + set: "123/456", + expect: "0.269(736842105263157894)" +}, { + set: "-123/456", + expect: "-0.269(736842105263157894)" +}, { + set: "19 123/456", + expect: "19.269(736842105263157894)" +}, { + set: "-19 123/456", + expect: "-19.269(736842105263157894)" +}, { + set: "123.(22)123", + expectError: InvalidParameter() +}, { + set: "+33.3(3)", + expect: "33.(3)" +}, { + set: "3.'09009'", + expect: "3.(09009)" +}, { + set: "123.(((", + expectError: InvalidParameter() +}, { + set: "123.((", + expectError: InvalidParameter() +}, { + set: "123.()", + expectError: InvalidParameter() +}, { + set: null, + expect: "0" // I would say it's just fine +}, { + set: [22, 7], + expect: '3.(142857)' // We got Pi! - almost ;o +}, { + set: "355/113", + expect: "3.(1415929203539823008849557522123893805309734513274336283185840707964601769911504424778761061946902654867256637168)" // Yay, a better PI +}, { + set: "3 1/7", + expect: '3.(142857)' +}, { + set: [36, -36], + expect: "-1" +}, { + set: [1n, 3n], + expect: "0.(3)" +}, { + set: 1n, + set2: 3n, + expect: "0.(3)" +}, { + set: { n: 1n, d: 3n }, + expect: "0.(3)" +}, { + set: { n: 1n, d: 3n }, + expect: "0.(3)" +}, { + set: [1n, 3n], + expect: "0.(3)" +}, { + set: "9/12", + expect: "0.75" +}, { + set: "0.09(33)", + expect: "0.09(3)" +}, { + set: 1 / 2, + expect: "0.5" +}, { + set: 1 / 3, + expect: "0.(3)" +}, { + set: "0.'3'", + expect: "0.(3)" +}, { + set: "0.00002", + expect: "0.00002" +}, { + set: 7 / 8, + expect: "0.875" +}, { + set: 0.003, + expect: "0.003" +}, { + set: 4, + expect: "4" +}, { + set: -99, + expect: "-99" +}, { + set: "-92332.1192", + expect: "-92332.1192" +}, { + set: '88.92933(12111)', + expect: "88.92933(12111)" +}, { + set: '-192322.823(123)', + expect: "-192322.8(231)" +}, { + label: "-99.12 % 0.09(34)", + set: '-99.12', + fn: "mod", + param: "0.09(34)", + expect: "-0.07(95)" +}, { + label: "0.4 / 0.1", + set: .4, + fn: "div", + param: ".1", + expect: "4" +}, { + label: "1 / -.1", + set: 1, + fn: "div", + param: "-.1", + expect: "-10" +}, { + label: "1 - (-1)", + set: 1, + fn: "sub", + param: "-1", + expect: "2" +}, { + label: "1 + (-1)", + set: 1, + fn: "add", + param: "-1", + expect: "0" +}, { + label: "-187 % 12", + set: '-187', + fn: "mod", + param: "12", + expect: "-7" +}, { + label: "Negate by 99 * -1", + set: '99', + fn: "mul", + param: "-1", + expect: "-99" +}, { + label: "0.5050000000000000000000000", + set: "0.5050000000000000000000000", + expect: "101/200", + fn: "toFraction", + param: true +}, { + label: "0.505000000(0000000000)", + set: "0.505000000(0000000000)", + expect: "101/200", + fn: "toFraction", + param: true +}, { + set: [20, -5], + expect: "-4", + fn: "toFraction", + param: true +}, { + set: [-10, -7], + expect: "1 3/7", + fn: "toFraction", + param: true +}, { + set: [21, -6], + expect: "-3 1/2", + fn: "toFraction", + param: true +}, { + set: "10/78", + expect: "5/39", + fn: "toFraction", + param: true +}, { + set: "0/91", + expect: "0", + fn: "toFraction", + param: true +}, { + set: "-0/287", + expect: "0", + fn: "toFraction", + param: true +}, { + set: "-5/20", + expect: "-1/4", + fn: "toFraction", + param: true +}, { + set: "42/9", + expect: "4 2/3", + fn: "toFraction", + param: true +}, { + set: "71/23", + expect: "3 2/23", + fn: "toFraction", + param: true +}, { + set: "6/3", + expect: "2", + fn: "toFraction", + param: true +}, { + set: "28/4", + expect: "7", + fn: "toFraction", + param: true +}, { + set: "105/35", + expect: "3", + fn: "toFraction", + param: true +}, { + set: "4/6", + expect: "2/3", + fn: "toFraction", + param: true +}, { + label: "99.(9) + 66", + set: '99.(999999)', + fn: "add", + param: "66", + expect: "166" +}, { + label: "123.32 / 33.'9821'", + set: '123.32', + fn: "div", + param: "33.'9821'", + expect: "3.628958880242975" +}, { + label: "-82.124 / 66.(3)", + set: '-82.124', + fn: "div", + param: "66.(3)", + expect: "-1.238(050251256281407035175879396984924623115577889447236180904522613065326633165829145728643216080402010)" +}, { + label: "100 - .91", + set: '100', + fn: "sub", + param: ".91", + expect: "99.09" +}, { + label: "381.(33411) % 11.119(356)", + set: '381.(33411)', + fn: "mod", + param: "11.119(356)", + expect: "3.275(997225017295217)" +}, { + label: "13/26 mod 1", + set: '13/26', + fn: "mod", + param: "1.000", + expect: "0.5" +}, { + label: "381.(33411) % 1", // Extract fraction part of a number + set: '381.(33411)', + fn: "mod", + param: "1", + expect: "0.(33411)" +}, { + label: "-222/3", + set: { + n: 3, + d: 222, + s: -1 + }, + fn: "inverse", + param: null, + expect: "-74" +}, { + label: "inverse", + set: 1 / 2, + fn: "inverse", + param: null, + expect: "2" +}, { + label: "abs(-222/3)", + set: { + n: -222, + d: 3 + }, + fn: "abs", + param: null, + expect: "74" +}, { + label: "9 % -2", + set: 9, + fn: "mod", + param: "-2", + expect: "1" +}, { + label: "-9 % 2", + set: '-9', + fn: "mod", + param: "-2", + expect: "-1" +}, { + label: "1 / 195312500", + set: '1', + fn: "div", + param: "195312500", + expect: "0.00000000512" +}, { + label: "10 / 0", + set: 10, + fn: "div", + param: 0, + expectError: DivisionByZero() +}, { + label: "-3 / 4", + set: [-3, 4], + fn: "inverse", + param: null, + expect: "-1.(3)" +}, { + label: "-19.6", + set: [-98, 5], + fn: "equals", + param: '-19.6', + expect: "true" // actually, we get a real bool but we call toString() in the test below +}, { + label: "-19.6", + set: [98, -5], + fn: "equals", + param: '-19.6', + expect: "true" +}, { + label: "99/88", + set: [99, 88], + fn: "equals", + param: [88, 99], + expect: "false" +}, { + label: "99/88", + set: [99, -88], + fn: "equals", + param: [9, 8], + expect: "false" +}, { + label: "12.5", + set: 12.5, + fn: "add", + param: 0, + expect: "12.5" +}, { + label: "0/1 -> 1/0", + set: 0, + fn: "inverse", + param: null, + expectError: DivisionByZero() +}, { + label: "abs(-100.25)", + set: -100.25, + fn: "abs", + param: null, + expect: "100.25" +}, { + label: "0.022222222", + set: '0.0(22222222)', + fn: "abs", + param: null, + expect: "0.0(2)" +}, { + label: "1.5 | 100.5", + set: 100.5, + fn: "divisible", + param: '1.5', + expect: "true" +}, { + label: "1.5 | 100.6", + set: 100.6, + fn: "divisible", + param: 1.6, + expect: "false" +}, { + label: "(1/6) | (2/3)", // == 4 + set: [2, 3], + fn: "divisible", + param: [1, 6], + expect: "true" +}, { + label: "(1/6) | (2/5)", + set: [2, 5], + fn: "divisible", + param: [1, 6], + expect: "false" +}, { + label: "0 | (2/5)", + set: [2, 5], + fn: "divisible", + param: 0, + expect: "false" +}, { + label: "6 | 0", + set: 0, + fn: "divisible", + param: 6, + expect: "true" +}, { + label: "fmod(4.55, 0.05)", // http://phpjs.org/functions/fmod/ (comment section) + set: 4.55, + fn: "mod", + param: 0.05, + expect: "0" +}, { + label: "fmod(99.12, 0.4)", + set: 99.12, + fn: "mod", + param: "0.4", + expect: "0.32" +}, { + label: "fmod(fmod(1.0,0.1))", // http://stackoverflow.com/questions/4218961/why-fmod1-0-0-1-1 + set: 1.0, + fn: "mod", + param: 0.1, + expect: "0" +}, { + label: "bignum", + set: [5385020324, 1673196525], + fn: "add", + param: 0, + expect: "3.21(840276592733181776121606516006839065124164060763872313206005492988936251824931324190982287630557922656455433410609073551596098372245902196097377144624418820138297860736950789447760776337973807350574075570710380240599651018280712721418065340531352107607323652551812465663589637206543923464101146157950573080469432602963360804254598843372567965379918536467197121390148715495330113717514444395585868193217769203770011415724163065662594535928766646225254382476081224230369471990147720394052336440275597631903998844367669243157195775313960803259497565595290726533154854597848271290188102679689703515252041298615534717298077104242133182771222884293284077911887845930112722413166618308629346454087334421161315763550250022184333666363549254920906556389124702491239037207539024741878423396797336762338781453063321417070239253574830368476888869943116813489676593728283053898883754853602746993512910863832926021645903191198654921901657666901979730085800889408373591978384009612977172541043856160291750546158945674358246709841810124486123947693472528578195558946669459524487119048971249805817042322628538808374587079661786890216019304725725509141850506771761314768448972244907094819599867385572056456428511886850828834945135927771544947477105237234460548500123140047759781236696030073335228807028510891749551057667897081007863078128255137273847732859712937785356684266362554153643129279150277938809369688357439064129062782986595074359241811119587401724970711375341877428295519559485099934689381452068220139292962014728066686607540019843156200674036183526020650801913421377683054893985032630879985)" +}, { + label: "ceil(0.4)", + set: 0.4, + fn: "ceil", + param: null, + expect: "1" +}, + + +{ + label: "1 < 2", + set: 1, + fn: "lt", + param: 2, + expect: "true" +}, { + label: "2 < 2", + set: 2, + fn: "lt", + param: 2, + expect: "false" +}, { + label: "3 > 2", + set: 3, + fn: "gt", + param: 2, + expect: "true" +}, { + label: "2 > 2", + set: 2, + fn: "gt", + param: 2, + expect: "false" +}, { + label: "1 <= 2", + set: 1, + fn: "lte", + param: 2, + expect: "true" +}, { + label: "2 <= 2", + set: 2, + fn: "lte", + param: 2, + expect: "true" +}, { + label: "3 <= 2", + set: 3, + fn: "lte", + param: 2, + expect: "false" +}, { + label: "3 >= 2", + set: 3, + fn: "gte", + param: 2, + expect: "true" +}, { + label: "2 >= 2", + set: 2, + fn: "gte", + param: 2, + expect: "true" +}, { + label: "ceil(0.5)", + set: 0.5, + fn: "ceil", + param: null, + expect: "1" +}, { + label: "ceil(0.23, 2)", + set: 0.23, + fn: "ceil", + param: 2, + expect: "0.23" +}, { + label: "ceil(0.6)", + set: 0.6, + fn: "ceil", + param: null, + expect: "1" +}, { + label: "ceil(-0.4)", + set: -0.4, + fn: "ceil", + param: null, + expect: "0" +}, { + label: "ceil(-0.5)", + set: -0.5, + fn: "ceil", + param: null, + expect: "0" +}, { + label: "ceil(-0.6)", + set: -0.6, + fn: "ceil", + param: null, + expect: "0" +}, { + label: "floor(0.4)", + set: 0.4, + fn: "floor", + param: null, + expect: "0" +}, { + label: "floor(0.4, 1)", + set: 0.4, + fn: "floor", + param: 1, + expect: "0.4" +}, { + label: "floor(0.5)", + set: 0.5, + fn: "floor", + param: null, + expect: "0" +}, { + label: "floor(0.6)", + set: 0.6, + fn: "floor", + param: null, + expect: "0" +}, { + label: "floor(-0.4)", + set: -0.4, + fn: "floor", + param: null, + expect: "-1" +}, { + label: "floor(-0.5)", + set: -0.5, + fn: "floor", + param: null, + expect: "-1" +}, { + label: "floor(-0.6)", + set: -0.6, + fn: "floor", + param: null, + expect: "-1" +}, { + label: "floor(10.4)", + set: 10.4, + fn: "floor", + param: null, + expect: "10" +}, { + label: "floor(10.4, 1)", + set: 10.4, + fn: "floor", + param: 1, + expect: "10.4" +}, { + label: "floor(10.5)", + set: 10.5, + fn: "floor", + param: null, + expect: "10" +}, { + label: "floor(10.6)", + set: 10.6, + fn: "floor", + param: null, + expect: "10" +}, { + label: "floor(-10.4)", + set: -10.4, + fn: "floor", + param: null, + expect: "-11" +}, { + label: "floor(-10.5)", + set: -10.5, + fn: "floor", + param: null, + expect: "-11" +}, { + label: "floor(-10.6)", + set: -10.6, + fn: "floor", + param: null, + expect: "-11" +}, { + label: "floor(-10.543,3)", + set: -10.543, + fn: "floor", + param: 3, + expect: "-10.543" +}, { + label: "floor(10.543,3)", + set: 10.543, + fn: "floor", + param: 3, + expect: "10.543" +}, { + label: "round(-10.543,3)", + set: -10.543, + fn: "round", + param: 3, + expect: "-10.543" +}, { + label: "round(10.543,3)", + set: 10.543, + fn: "round", + param: 3, + expect: "10.543" +}, { + label: "round(10.4)", + set: 10.4, + fn: "round", + param: null, + expect: "10" +}, { + label: "round(10.5)", + set: 10.5, + fn: "round", + param: null, + expect: "11" +}, { + label: "round(10.5, 1)", + set: 10.5, + fn: "round", + param: 1, + expect: "10.5" +}, { + label: "round(10.6)", + set: 10.6, + fn: "round", + param: null, + expect: "11" +}, { + label: "round(-10.4)", + set: -10.4, + fn: "round", + param: null, + expect: "-10" +}, { + label: "round(-10.5)", + set: -10.5, + fn: "round", + param: null, + expect: "-10" +}, { + label: "round(-10.6)", + set: -10.6, + fn: "round", + param: null, + expect: "-11" +}, { + label: "round(-0.4)", + set: -0.4, + fn: "round", + param: null, + expect: "0" +}, { + label: "round(-0.5)", + set: -0.5, + fn: "round", + param: null, + expect: "0" +}, { + label: "round(-0.6)", + set: -0.6, + fn: "round", + param: null, + expect: "-1" +}, { + label: "round(-0)", + set: -0, + fn: "round", + param: null, + expect: "0" +}, { + label: "round(big fraction)", + set: [ + '409652136432929109317120'.repeat(100), + '63723676445298091081155'.repeat(100) + ], + fn: "round", + param: null, + expect: "6428570341270001560623330590225448467479093479780591305451264291405695842465355472558570608574213642" +}, { + label: "round(big numerator)", + set: ['409652136432929109317'.repeat(100), 10], + fn: "round", + param: null, + expect: '409652136432929109317'.repeat(99) + '40965213643292910932' +}, { + label: "17402216385200408/5539306332998545", + set: [17402216385200408, 5539306332998545], + fn: "add", + param: 0, + expect: "3.141587653589870" +}, { + label: "17402216385200401/553930633299855", + set: [17402216385200401, 553930633299855], + fn: "add", + param: 0, + expect: "31.415876535898660" +}, { + label: "1283191/418183", + set: [1283191, 418183], + fn: "add", + param: 0, + expect: "3.068491545567371" +}, { + label: "1.001", + set: "1.001", + fn: "add", + param: 0, + expect: "1.001" +}, { + label: "99+1", + set: [99, 1], + fn: "add", + param: 1, + expect: "100" +}, { + label: "gcd(5/8, 3/7)", + set: [5, 8], + fn: "gcd", + param: [3, 7], + expect: "0.017(857142)" // == 1/56 +}, { + label: "gcd(52, 39)", + set: 52, + fn: "gcd", + param: 39, + expect: "13" +}, { + label: "gcd(51357, 3819)", + set: 51357, + fn: "gcd", + param: 3819, + expect: "57" +}, { + label: "gcd(841, 299)", + set: 841, + fn: "gcd", + param: 299, + expect: "1" +}, { + label: "gcd(2/3, 7/5)", + set: [2, 3], + fn: "gcd", + param: [7, 5], + expect: "0.0(6)" // == 1/15 +}, { + label: "lcm(-3, 3)", + set: -3, + fn: "lcm", + param: 3, + expect: "3" +}, { + label: "lcm(3,-3)", + set: 3, + fn: "lcm", + param: -3, + expect: "3" +}, { + label: "lcm(0,3)", + set: 0, + fn: "lcm", + param: 3, + expect: "0" +}, { + label: "lcm(3, 0)", + set: 3, + fn: "lcm", + param: 0, + expect: "0" +}, { + label: "lcm(0, 0)", + set: 0, + fn: "lcm", + param: 0, + expect: "0" +}, { + label: "lcm(200, 333)", + set: 200, + fn: "lcm", + param: 333, expect: "66600" +}, +{ + label: "1 + -1", + set: 1, + fn: "add", + param: -1, + expect: "0" +}, { + label: "3/10+3/14", + set: "3/10", + fn: "add", + param: "3/14", + expect: "0.5(142857)" +}, { + label: "3/10-3/14", + set: "3/10", + fn: "sub", + param: "3/14", + expect: "0.0(857142)" +}, { + label: "3/10*3/14", + set: "3/10", + fn: "mul", + param: "3/14", + expect: "0.06(428571)" +}, { + label: "3/10 / 3/14", + set: "3/10", + fn: "div", + param: "3/14", + expect: "1.4" +}, { + label: "1-2", + set: "1", + fn: "sub", + param: "2", + expect: "-1" +}, { + label: "1--1", + set: "1", + fn: "sub", + param: "-1", + expect: "2" +}, { + label: "0/1*1/3", + set: "0/1", + fn: "mul", + param: "1/3", + expect: "0" +}, { + label: "3/10 * 8/12", + set: "3/10", + fn: "mul", + param: "8/12", + expect: "0.2" +}, { + label: ".5+5", + set: ".5", + fn: "add", + param: 5, expect: "5.5" +}, +{ + label: "10/12-5/60", + set: "10/12", + fn: "sub", + param: "5/60", + expect: "0.75" +}, { + label: "10/15 / 3/4", + set: "10/15", + fn: "div", + param: "3/4", + expect: "0.(8)" +}, { + label: "1/4 + 3/8", + set: "1/4", + fn: "add", + param: "3/8", + expect: "0.625" +}, { + label: "2-1/3", + set: "2", + fn: "sub", + param: "1/3", + expect: "1.(6)" +}, { + label: "5*6", + set: "5", + fn: "mul", + param: 6, + expect: "30" +}, { + label: "1/2-1/5", + set: "1/2", + fn: "sub", + param: "1/5", + expect: "0.3" +}, { + label: "1/2-5", + set: "1/2", + fn: "add", + param: -5, + expect: "-4.5" +}, { + label: "1*-1", + set: "1", + fn: "mul", + param: -1, + expect: "-1" +}, { + label: "5/10", + set: 5.0, + fn: "div", + param: 10, + expect: "0.5" +}, { + label: "1/-1", + set: "1", + fn: "div", + param: -1, + expect: "-1" +}, { + label: "4/5 + 13/2", + set: "4/5", + fn: "add", + param: "13/2", + expect: "7.3" +}, { + label: "4/5 + 61/2", + set: "4/5", + fn: "add", + param: "61/2", + expect: "31.3" +}, { + label: "0.8 + 6.5", + set: "0.8", + fn: "add", + param: "6.5", + expect: "7.3" +}, { + label: "2/7 inverse", + set: "2/7", + fn: "inverse", + param: null, + expect: "3.5" +}, { + label: "neg 1/3", + set: "1/3", + fn: "neg", + param: null, + expect: "-0.(3)" +}, { + label: "1/2+1/3", + set: "1/2", + fn: "add", + param: "1/3", + expect: "0.8(3)" +}, { + label: "1/2+3", + set: ".5", + fn: "add", + param: 3, + expect: "3.5" +}, { + label: "1/2+3.14", + set: "1/2", + fn: "add", + param: "3.14", + expect: "3.64" +}, { + label: "3.5 < 4.1", + set: 3.5, + fn: "compare", + param: 4.1, + expect: "-1" +}, { + label: "3.5 > 4.1", + set: 4.1, + fn: "compare", + param: 3.1, + expect: "1" +}, { + label: "-3.5 > -4.1", + set: -3.5, + fn: "compare", + param: -4.1, + expect: "1" +}, { + label: "-3.5 > -4.1", + set: -4.1, + fn: "compare", + param: -3.5, + expect: "-1" +}, { + label: "4.3 == 4.3", + set: 4.3, + fn: "compare", + param: 4.3, + expect: "0" +}, { + label: "-4.3 == -4.3", + set: -4.3, + fn: "compare", + param: -4.3, + expect: "0" +}, { + label: "-4.3 < 4.3", + set: -4.3, + fn: "compare", + param: 4.3, + expect: "-1" +}, { + label: "4.3 == -4.3", + set: 4.3, + fn: "compare", + param: -4.3, + expect: "1" +}, { + label: "2^0.5", + set: 2, + fn: "pow", + param: 0.5, + expect: "null" +}, { + label: "(-8/27)^(1/3)", + set: [-8, 27], + fn: "pow", + param: [1, 3], + expect: "null" +}, { + label: "(-8/27)^(2/3)", + set: [-8, 27], + fn: "pow", + param: [2, 3], + expect: "null" +}, { + label: "(-32/243)^(5/3)", + set: [-32, 243], + fn: "pow", + param: [5, 3], + expect: "null" +}, { + label: "sqrt(0)", + set: 0, + fn: "pow", + param: 0.5, + expect: "0" +}, { + label: "27^(2/3)", + set: 27, + fn: "pow", + param: "2/3", + expect: "9" +}, { + label: "(243/1024)^(2/5)", + set: "243/1024", + fn: "pow", + param: "2/5", + expect: "0.5625" +}, { + label: "-0.5^-3", + set: -0.5, + fn: "pow", + param: -3, + expect: "-8" +}, { + label: "", + set: -3, + fn: "pow", + param: -3, + expect: "-0.(037)" +}, { + label: "-3", + set: -3, + fn: "pow", + param: 2, + expect: "9" +}, { + label: "-3", + set: -3, + fn: "pow", + param: 3, + expect: "-27" +}, { + label: "0^0", + set: 0, + fn: "pow", + param: 0, + expect: "1" +}, { + label: "2/3^7", + set: [2, 3], + fn: "pow", + param: 7, + expect: "0.(058527663465935070873342478280749885688157293095564700502972107910379515317786922725194330132601737540009144947416552354823959762231367169638774577046181984453589391860996799268404206675811614083219021490626428898033836305441243712848651120256)" +}, { + label: "-0.6^4", + set: -0.6, + fn: "pow", + param: 4, + expect: "0.1296" +}, { + label: "8128371:12394 - 8128371/12394", + set: "8128371:12394", + fn: "sub", + param: "8128371/12394", + expect: "0" +}, { + label: "3/4 + 1/4", + set: "3/4", + fn: "add", + param: "1/4", + expect: "1" +}, { + label: "1/10 + 2/10", + set: "1/10", + fn: "add", + param: "2/10", + expect: "0.3" +}, { + label: "5/10 + 2/10", + set: "5/10", + fn: "add", + param: "2/10", + expect: "0.7" +}, { + label: "18/10 + 2/10", + set: "18/10", + fn: "add", + param: "2/10", + expect: "2" +}, { + label: "1/3 + 1/6", + set: "1/3", + fn: "add", + param: "1/6", + expect: "0.5" +}, { + label: "1/3 + 2/6", + set: "1/3", + fn: "add", + param: "2/6", + expect: "0.(6)" +}, { + label: "3/4 / 1/4", + set: "3/4", + fn: "div", + param: "1/4", + expect: "3" +}, { + label: "1/10 / 2/10", + set: "1/10", + fn: "div", + param: "2/10", + expect: "0.5" +}, { + label: "5/10 / 2/10", + set: "5/10", + fn: "div", + param: "2/10", + expect: "2.5" +}, { + label: "18/10 / 2/10", + set: "18/10", + fn: "div", + param: "2/10", + expect: "9" +}, { + label: "1/3 / 1/6", + set: "1/3", + fn: "div", + param: "1/6", + expect: "2" +}, { + label: "1/3 / 2/6", + set: "1/3", + fn: "div", + param: "2/6", + expect: "1" +}, { + label: "3/4 * 1/4", + set: "3/4", + fn: "mul", + param: "1/4", + expect: "0.1875" +}, { + label: "1/10 * 2/10", + set: "1/10", + fn: "mul", + param: "2/10", + expect: "0.02" +}, { + label: "5/10 * 2/10", + set: "5/10", + fn: "mul", + param: "2/10", + expect: "0.1" +}, { + label: "18/10 * 2/10", + set: "18/10", + fn: "mul", + param: "2/10", + expect: "0.36" +}, { + label: "1/3 * 1/6", + set: "1/3", + fn: "mul", + param: "1/6", + expect: "0.0(5)" +}, { + label: "1/3 * 2/6", + set: "1/3", + fn: "mul", + param: "2/6", + expect: "0.(1)" +}, { + label: "5/4 - 1/4", + set: "5/4", + fn: "sub", + param: "1/4", + expect: "1" +}, { + label: "5/10 - 2/10", + set: "5/10", + fn: "sub", + param: "2/10", + expect: "0.3" +}, { + label: "9/10 - 2/10", + set: "9/10", + fn: "sub", + param: "2/10", + expect: "0.7" +}, { + label: "22/10 - 2/10", + set: "22/10", + fn: "sub", + param: "2/10", + expect: "2" +}, { + label: "2/3 - 1/6", + set: "2/3", + fn: "sub", + param: "1/6", + expect: "0.5" +}, { + label: "3/3 - 2/6", + set: "3/3", + fn: "sub", + param: "2/6", + expect: "0.(6)" +}, { + label: "0.006999999999999999", + set: 0.006999999999999999, + fn: "add", + param: 0, + expect: "0.007" +}, { + label: "1/7 - 1", + set: 1 / 7, + fn: "add", + param: -1, + expect: "-0.(857142)" +}, { + label: "0.0065 + 0.0005", + set: 0.0065, + fn: "add", + param: 0.0005, + expect: "0.007" +}, { + label: "6.5/.5", + set: 6.5, + fn: "div", + param: .5, + expect: "13" +}, { + label: "0.999999999999999999999999999", + set: 0.999999999999999999999999999, + fn: "sub", + param: 1, + expect: "0" +}, { + label: "0.5833333333333334", + set: 0.5833333333333334, + fn: "add", + param: 0, + expect: "0.58(3)" +}, { + label: "1.75/3", + set: 1.75 / 3, + fn: "add", + param: 0, + expect: "0.58(3)" +}, { + label: "3.3333333333333", + set: 3.3333333333333, + fn: "add", + param: 0, + expect: "3.(3)" +}, { + label: "4.285714285714285714285714", + set: 4.285714285714285714285714, + fn: "add", + param: 0, + expect: "4.(285714)" +}, { + label: "-4", + set: -4, + fn: "neg", + param: 0, + expect: "4" +}, { + label: "4", + set: 4, + fn: "neg", + param: 0, + expect: "-4" +}, { + label: "0", + set: 0, + fn: "neg", + param: 0, + expect: "0" +}, { + label: "6869570742453802/5329686054127205", + set: "6869570742453802/5329686054127205", + fn: "neg", + param: 0, + expect: "-1.288925965373540" +}, { + label: "686970702/53212205", + set: "686970702/53212205", + fn: "neg", + param: 0, + expect: "-12.910021338149772" +}, { + label: "1/3000000000000000", + set: "1/3000000000000000", + fn: "add", + param: 0, + expect: "0.000000000000000(3)" +}, { + label: "toString(15) .0000000000000003", + set: ".0000000000000003", + fn: "toString", + param: 15, + expect: "0.000000000000000" +}, { + label: "toString(16) .0000000000000003", + set: ".0000000000000003", + fn: "toString", + param: 16, + expect: "0.0000000000000003" +}, { + label: "12 / 4.3", + set: 12, + set2: 4.3, + fn: "toString", + param: null, + expectError: NonIntegerParameter() +}, { + label: "12.5 / 4", + set: 12.5, + set2: 4, + fn: "toString", + param: null, + expectError: NonIntegerParameter() +}, { + label: "0.9 round to multiple of 1/8", + set: .9, + fn: "roundTo", + param: "1/8", + expect: "0.875" +}, { + label: "1/3 round to multiple of 1/16", + set: 1 / 3, + fn: "roundTo", + param: "1/16", + expect: "0.3125" +}, { + label: "1/3 round to multiple of 1/16", + set: -1 / 3, + fn: "roundTo", + param: "1/16", + expect: "-0.3125" +}, { + label: "1/2 round to multiple of 1/4", + set: 1 / 2, + fn: "roundTo", + param: "1/4", + expect: "0.5" +}, { + label: "1/4 round to multiple of 1/2", + set: 1 / 4, + fn: "roundTo", + param: "1/2", + expect: "0.5" +}, { + label: "10/3 round to multiple of 1/2", + set: "10/3", + fn: "roundTo", + param: "1/2", + expect: "3.5" +}, { + label: "-10/3 round to multiple of 1/2", + set: "-10/3", + fn: "roundTo", + param: "1/2", + expect: "-3.5" +}, { + label: "log_2(8)", + set: "8", + fn: "log", + param: "2", + expect: "3" // because 2^3 = 8 +}, { + label: "log_2(3)", + set: "3", + fn: "log", + param: "2", + expect: 'null' // because 2^(p/q) != 3 +}, { + label: "log_10(1000)", + set: "1000", + fn: "log", + param: "10", + expect: "3" // because 10^3 = 1000 +}, { + label: "log_27(81)", + set: "81", + fn: "log", + param: "27", + expect: "1.(3)" // because 27^(4/3) = 81 +}, { + label: "log_27(9)", + set: "9", + fn: "log", + param: "27", + expect: "0.(6)" // because 27^(2/3) = 9 +}, { + label: "log_9/4(27/8)", + set: "27/8", + fn: "log", + param: "9/4", + expect: "1.5" // because (9/4)^(3/2) = 27/8 +}]; + +describe('Fraction', function () { + for (var i = 0; i < tests.length; i++) { + + (function (i) { + var action; + + if (tests[i].fn) { + action = function () { + var x = Fraction(tests[i].set, tests[i].set2)[tests[i].fn](tests[i].param); + if (x === null) return "null"; + return x.toString(); + }; + } else { + action = function () { + var x = new Fraction(tests[i].set, tests[i].set2); + if (x === null) return "null"; + return x.toString(); + }; + } + + it(String(tests[i].label || tests[i].set), function () { + if (tests[i].expectError) { + assert.throws(action, tests[i].expectError); + } else { + assert.equal(action(), tests[i].expect); + } + }); + + })(i); + } +}); + +describe('JSON', function () { + + it("Should be possible to stringify the object", function () { + + if (typeof Fraction(1).n !== 'number') { + return; + } + assert.equal('{"s":1,"n":14623,"d":330}', JSON.stringify(new Fraction("44.3(12)"))); + assert.equal('{"s":-1,"n":2,"d":1}', JSON.stringify(new Fraction(-1 / 2).inverse())); + }); +}); + +describe('Arguments', function () { + + it("Should be possible to use different kind of params", function () { + + // String + var fraction = new Fraction("0.1"); + assert.equal("1/10", fraction.n + "/" + fraction.d); + + var fraction = new Fraction("6234/6460"); + assert.equal("3117/3230", fraction.n + "/" + fraction.d); + + // Two params + var fraction = new Fraction(1, 2); + assert.equal("1/2", fraction.n + "/" + fraction.d); + + // Object + var fraction = new Fraction({ n: 1, d: 3 }); + assert.equal("1/3", fraction.n + "/" + fraction.d); + + // Array + var fraction = new Fraction([1, 4]); + assert.equal("1/4", fraction.n + "/" + fraction.d); + }); +}); + +describe('fractions', function () { + + it("Should pass 0.08 = 2/25", function () { + + var fraction = new Fraction("0.08"); + assert.equal("2/25", fraction.n + "/" + fraction.d); + }); + + it("Should pass 0.200 = 1/5", function () { + + var fraction = new Fraction("0.200"); + assert.equal("1/5", fraction.n + "/" + fraction.d); + }); + + it("Should pass 0.125 = 1/8", function () { + + var fraction = new Fraction("0.125"); + assert.equal("1/8", fraction.n + "/" + fraction.d); + }); + + it("Should pass 8.36 = 209/25", function () { + + var fraction = new Fraction(8.36); + assert.equal("209/25", fraction.n + "/" + fraction.d); + }); + +}); + +describe('constructors', function () { + + it("Should pass 0.08 = 2/25", function () { + + var tmp = new Fraction({ d: 4, n: 2, s: -1 }); + assert.equal("-1/2", tmp.s * tmp.n + "/" + tmp.d); + + var tmp = new Fraction(-88.3); + assert.equal("-883/10", tmp.s * tmp.n + "/" + tmp.d); + + var tmp = new Fraction(-88.3).clone(); + assert.equal("-883/10", tmp.s * tmp.n + "/" + tmp.d); + + var tmp = new Fraction("123.'3'"); + assert.equal("370/3", tmp.s * tmp.n + "/" + tmp.d); + + var tmp = new Fraction("123.'3'").clone(); + assert.equal("370/3", tmp.s * tmp.n + "/" + tmp.d); + + var tmp = new Fraction([-1023461776, 334639305]); + tmp = tmp.add([4, 25]); + assert.equal("-4849597436/1673196525", tmp.s * tmp.n + "/" + tmp.d); + }); +}); + +describe('Latex Output', function () { + + it("Should pass 123.'3' = \\frac{370}{3}", function () { + + var tmp = new Fraction("123.'3'"); + assert.equal("\\frac{370}{3}", tmp.toLatex()); + }); + + it("Should pass 1.'3' = \\frac{4}{3}", function () { + + var tmp = new Fraction("1.'3'"); + assert.equal("\\frac{4}{3}", tmp.toLatex()); + }); + + it("Should pass -1.0000000000 = -1", function () { + + var tmp = new Fraction("-1.0000000000"); + assert.equal('-1', tmp.toLatex()); + }); + + it("Should pass -0.0000000000 = 0", function () { + + var tmp = new Fraction("-0.0000000000"); + assert.equal('0', tmp.toLatex()); + }); +}); + +describe('Fraction Output', function () { + + it("Should pass 123.'3' = 123 1/3", function () { + + var tmp = new Fraction("123.'3'"); + assert.equal('370/3', tmp.toFraction()); + }); + + it("Should pass 1.'3' = 1 1/3", function () { + + var tmp = new Fraction("1.'3'"); + assert.equal('4/3', tmp.toFraction()); + }); + + it("Should pass -1.0000000000 = -1", function () { + + var tmp = new Fraction("-1.0000000000"); + assert.equal('-1', tmp.toFraction()); + }); + + it("Should pass -0.0000000000 = 0", function () { + + var tmp = new Fraction("-0.0000000000"); + assert.equal('0', tmp.toFraction()); + }); + + it("Should pass 1/-99/293 = -1/29007", function () { + + var tmp = new Fraction(-99).inverse().div(293); + assert.equal('-1/29007', tmp.toFraction()); + }); + + it('Should work with large calculations', function () { + var x = Fraction(1123875); + var y = Fraction(1238750184); + var z = Fraction(1657134); + var r = Fraction(77344464613500, 92063); + assert.equal(x.mul(y).div(z).toFraction(), r.toFraction()); + }); +}); + +describe('Fraction toContinued', function () { + + it("Should pass 415/93", function () { + + var tmp = new Fraction(415, 93); + assert.equal('4,2,6,7', tmp.toContinued().toString()); + }); + + it("Should pass 0/2", function () { + + var tmp = new Fraction(0, 2); + assert.equal('0', tmp.toContinued().toString()); + }); + + it("Should pass 1/7", function () { + + var tmp = new Fraction(1, 7); + assert.equal('0,7', tmp.toContinued().toString()); + }); + + it("Should pass 23/88", function () { + + var tmp = new Fraction('23/88'); + assert.equal('0,3,1,4,1,3', tmp.toContinued().toString()); + }); + + it("Should pass 1/99", function () { + + var tmp = new Fraction('1/99'); + assert.equal('0,99', tmp.toContinued().toString()); + }); + + it("Should pass 1768/99", function () { + + var tmp = new Fraction('1768/99'); + assert.equal('17,1,6,14', tmp.toContinued().toString()); + }); + + it("Should pass 1768/99", function () { + + var tmp = new Fraction('7/8'); + assert.equal('0,1,7', tmp.toContinued().toString()); + }); + +}); + + +describe('Fraction simplify', function () { + + it("Should pass 415/93", function () { + + var tmp = new Fraction(415, 93); + assert.equal('9/2', tmp.simplify(0.1).toFraction()); + assert.equal('58/13', tmp.simplify(0.01).toFraction()); + assert.equal('415/93', tmp.simplify(0.0001).toFraction()); + }); + +}); diff --git a/client/node_modules/graceful-fs/LICENSE b/client/node_modules/graceful-fs/LICENSE new file mode 100644 index 0000000..e906a25 --- /dev/null +++ b/client/node_modules/graceful-fs/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/client/node_modules/graceful-fs/README.md b/client/node_modules/graceful-fs/README.md new file mode 100644 index 0000000..82d6e4d --- /dev/null +++ b/client/node_modules/graceful-fs/README.md @@ -0,0 +1,143 @@ +# graceful-fs + +graceful-fs functions as a drop-in replacement for the fs module, +making various improvements. + +The improvements are meant to normalize behavior across different +platforms and environments, and to make filesystem access more +resilient to errors. + +## Improvements over [fs module](https://nodejs.org/api/fs.html) + +* Queues up `open` and `readdir` calls, and retries them once + something closes if there is an EMFILE error from too many file + descriptors. +* fixes `lchmod` for Node versions prior to 0.6.2. +* implements `fs.lutimes` if possible. Otherwise it becomes a noop. +* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or + `lchown` if the user isn't root. +* makes `lchmod` and `lchown` become noops, if not available. +* retries reading a file if `read` results in EAGAIN error. + +On Windows, it retries renaming a file for up to one second if `EACCESS` +or `EPERM` error occurs, likely because antivirus software has locked +the directory. + +## USAGE + +```javascript +// use just like fs +var fs = require('graceful-fs') + +// now go and do stuff with it... +fs.readFile('some-file-or-whatever', (err, data) => { + // Do stuff here. +}) +``` + +## Sync methods + +This module cannot intercept or handle `EMFILE` or `ENFILE` errors from sync +methods. If you use sync methods which open file descriptors then you are +responsible for dealing with any errors. + +This is a known limitation, not a bug. + +## Global Patching + +If you want to patch the global fs module (or any other fs-like +module) you can do this: + +```javascript +// Make sure to read the caveat below. +var realFs = require('fs') +var gracefulFs = require('graceful-fs') +gracefulFs.gracefulify(realFs) +``` + +This should only ever be done at the top-level application layer, in +order to delay on EMFILE errors from any fs-using dependencies. You +should **not** do this in a library, because it can cause unexpected +delays in other parts of the program. + +## Changes + +This module is fairly stable at this point, and used by a lot of +things. That being said, because it implements a subtle behavior +change in a core part of the node API, even modest changes can be +extremely breaking, and the versioning is thus biased towards +bumping the major when in doubt. + +The main change between major versions has been switching between +providing a fully-patched `fs` module vs monkey-patching the node core +builtin, and the approach by which a non-monkey-patched `fs` was +created. + +The goal is to trade `EMFILE` errors for slower fs operations. So, if +you try to open a zillion files, rather than crashing, `open` +operations will be queued up and wait for something else to `close`. + +There are advantages to each approach. Monkey-patching the fs means +that no `EMFILE` errors can possibly occur anywhere in your +application, because everything is using the same core `fs` module, +which is patched. However, it can also obviously cause undesirable +side-effects, especially if the module is loaded multiple times. + +Implementing a separate-but-identical patched `fs` module is more +surgical (and doesn't run the risk of patching multiple times), but +also imposes the challenge of keeping in sync with the core module. + +The current approach loads the `fs` module, and then creates a +lookalike object that has all the same methods, except a few that are +patched. It is safe to use in all versions of Node from 0.8 through +7.0. + +### v4 + +* Do not monkey-patch the fs module. This module may now be used as a + drop-in dep, and users can opt into monkey-patching the fs builtin + if their app requires it. + +### v3 + +* Monkey-patch fs, because the eval approach no longer works on recent + node. +* fixed possible type-error throw if rename fails on windows +* verify that we *never* get EMFILE errors +* Ignore ENOSYS from chmod/chown +* clarify that graceful-fs must be used as a drop-in + +### v2.1.0 + +* Use eval rather than monkey-patching fs. +* readdir: Always sort the results +* win32: requeue a file if error has an OK status + +### v2.0 + +* A return to monkey patching +* wrap process.cwd + +### v1.1 + +* wrap readFile +* Wrap fs.writeFile. +* readdir protection +* Don't clobber the fs builtin +* Handle fs.read EAGAIN errors by trying again +* Expose the curOpen counter +* No-op lchown/lchmod if not implemented +* fs.rename patch only for win32 +* Patch fs.rename to handle AV software on Windows +* Close #4 Chown should not fail on einval or eperm if non-root +* Fix isaacs/fstream#1 Only wrap fs one time +* Fix #3 Start at 1024 max files, then back off on EMFILE +* lutimes that doens't blow up on Linux +* A full on-rewrite using a queue instead of just swallowing the EMFILE error +* Wrap Read/Write streams as well + +### 1.0 + +* Update engines for node 0.6 +* Be lstat-graceful on Windows +* first diff --git a/client/node_modules/graceful-fs/clone.js b/client/node_modules/graceful-fs/clone.js new file mode 100644 index 0000000..dff3cc8 --- /dev/null +++ b/client/node_modules/graceful-fs/clone.js @@ -0,0 +1,23 @@ +'use strict' + +module.exports = clone + +var getPrototypeOf = Object.getPrototypeOf || function (obj) { + return obj.__proto__ +} + +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj + + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) } + else + var copy = Object.create(null) + + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) + + return copy +} diff --git a/client/node_modules/graceful-fs/graceful-fs.js b/client/node_modules/graceful-fs/graceful-fs.js new file mode 100644 index 0000000..8d5b89e --- /dev/null +++ b/client/node_modules/graceful-fs/graceful-fs.js @@ -0,0 +1,448 @@ +var fs = require('fs') +var polyfills = require('./polyfills.js') +var legacy = require('./legacy-streams.js') +var clone = require('./clone.js') + +var util = require('util') + +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol + +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' +} + +function noop () {} + +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue + } + }) +} + +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } + +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) + + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + resetQueue() + } + + if (typeof cb === 'function') + cb.apply(this, arguments) + }) + } + + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) + + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + resetQueue() + } + + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) + + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + require('assert').equal(fs[gracefulQueue].length, 0) + }) + } +} + +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); +} + +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} + +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch + + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$readFile(path, options, cb) + + function go$readFile (path, options, cb, startTime) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$writeFile(path, data, options, cb) + + function go$writeFile (path, data, options, cb, startTime) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$appendFile(path, data, options, cb) + + function go$appendFile (path, data, options, cb, startTime) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$copyFile = fs.copyFile + if (fs$copyFile) + fs.copyFile = copyFile + function copyFile (src, dest, flags, cb) { + if (typeof flags === 'function') { + cb = flags + flags = 0 + } + return go$copyFile(src, dest, flags, cb) + + function go$copyFile (src, dest, flags, cb, startTime) { + return fs$copyFile(src, dest, flags, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$readdir = fs.readdir + fs.readdir = readdir + var noReaddirOptionVersions = /^v[0-5]\./ + function readdir (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + var go$readdir = noReaddirOptionVersions.test(process.version) + ? function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, fs$readdirCallback( + path, options, cb, startTime + )) + } + : function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, options, fs$readdirCallback( + path, options, cb, startTime + )) + } + + return go$readdir(path, options, cb) + + function fs$readdirCallback (path, options, cb, startTime) { + return function (err, files) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([ + go$readdir, + [path, options, cb], + err, + startTime || Date.now(), + Date.now() + ]) + else { + if (files && files.sort) + files.sort() + + if (typeof cb === 'function') + cb.call(this, err, files) + } + } + } + } + + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } + + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } + + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } + + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) + + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) + + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } + + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() + + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } + + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } + + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } + + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } + + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } + + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null + + return go$open(path, flags, mode, cb) + + function go$open (path, flags, mode, cb, startTime) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + return fs +} + +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) + retry() +} + +// keep track of the timeout between retry() calls +var retryTimer + +// reset the startTime and lastTime to now +// this resets the start of the 60 second overall timeout as well as the +// delay between attempts so that we'll retry these jobs sooner +function resetQueue () { + var now = Date.now() + for (var i = 0; i < fs[gracefulQueue].length; ++i) { + // entries that are only a length of 2 are from an older version, don't + // bother modifying those since they'll be retried anyway. + if (fs[gracefulQueue][i].length > 2) { + fs[gracefulQueue][i][3] = now // startTime + fs[gracefulQueue][i][4] = now // lastTime + } + } + // call retry to make sure we're actively processing the queue + retry() +} + +function retry () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer) + retryTimer = undefined + + if (fs[gracefulQueue].length === 0) + return + + var elem = fs[gracefulQueue].shift() + var fn = elem[0] + var args = elem[1] + // these items may be unset if they were added by an older graceful-fs + var err = elem[2] + var startTime = elem[3] + var lastTime = elem[4] + + // if we don't have a startTime we have no way of knowing if we've waited + // long enough, so go ahead and retry this item now + if (startTime === undefined) { + debug('RETRY', fn.name, args) + fn.apply(null, args) + } else if (Date.now() - startTime >= 60000) { + // it's been more than 60 seconds total, bail now + debug('TIMEOUT', fn.name, args) + var cb = args.pop() + if (typeof cb === 'function') + cb.call(null, err) + } else { + // the amount of time between the last attempt and right now + var sinceAttempt = Date.now() - lastTime + // the amount of time between when we first tried, and when we last tried + // rounded up to at least 1 + var sinceStart = Math.max(lastTime - startTime, 1) + // backoff. wait longer than the total time we've been retrying, but only + // up to a maximum of 100ms + var desiredDelay = Math.min(sinceStart * 1.2, 100) + // it's been long enough since the last retry, do it again + if (sinceAttempt >= desiredDelay) { + debug('RETRY', fn.name, args) + fn.apply(null, args.concat([startTime])) + } else { + // if we can't do this job yet, push it to the end of the queue + // and let the next iteration check again + fs[gracefulQueue].push(elem) + } + } + + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0) + } +} diff --git a/client/node_modules/graceful-fs/legacy-streams.js b/client/node_modules/graceful-fs/legacy-streams.js new file mode 100644 index 0000000..d617b50 --- /dev/null +++ b/client/node_modules/graceful-fs/legacy-streams.js @@ -0,0 +1,118 @@ +var Stream = require('stream').Stream + +module.exports = legacy + +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } + + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); + + Stream.call(this); + + var self = this; + + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; + + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.encoding) this.setEncoding(this.encoding); + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } + + if (this.start > this.end) { + throw new Error('start must be <= end'); + } + + this.pos = this.start; + } + + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } + + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } + + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } + + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); + + Stream.call(this); + + this.path = path; + this.fd = null; + this.writable = true; + + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } + + this.pos = this.start; + } + + this.busy = false; + this._queue = []; + + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } +} diff --git a/client/node_modules/graceful-fs/package.json b/client/node_modules/graceful-fs/package.json new file mode 100644 index 0000000..87babf0 --- /dev/null +++ b/client/node_modules/graceful-fs/package.json @@ -0,0 +1,53 @@ +{ + "name": "graceful-fs", + "description": "A drop-in replacement for fs, making various improvements.", + "version": "4.2.11", + "repository": { + "type": "git", + "url": "https://github.com/isaacs/node-graceful-fs" + }, + "main": "graceful-fs.js", + "directories": { + "test": "test" + }, + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --follow-tags", + "test": "nyc --silent node test.js | tap -c -", + "posttest": "nyc report" + }, + "keywords": [ + "fs", + "module", + "reading", + "retry", + "retries", + "queue", + "error", + "errors", + "handling", + "EMFILE", + "EAGAIN", + "EINVAL", + "EPERM", + "EACCESS" + ], + "license": "ISC", + "devDependencies": { + "import-fresh": "^2.0.0", + "mkdirp": "^0.5.0", + "rimraf": "^2.2.8", + "tap": "^16.3.4" + }, + "files": [ + "fs.js", + "graceful-fs.js", + "legacy-streams.js", + "polyfills.js", + "clone.js" + ], + "tap": { + "reporter": "classic" + } +} diff --git a/client/node_modules/graceful-fs/polyfills.js b/client/node_modules/graceful-fs/polyfills.js new file mode 100644 index 0000000..453f1a9 --- /dev/null +++ b/client/node_modules/graceful-fs/polyfills.js @@ -0,0 +1,355 @@ +var constants = require('constants') + +var origCwd = process.cwd +var cwd = null + +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform + +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +try { + process.cwd() +} catch (er) {} + +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir = process.chdir + process.chdir = function (d) { + cwd = null + chdir.call(process, d) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) +} + +module.exports = patch + +function patch (fs) { + // (re-)implement some things that are known busted or missing. + + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } + + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } + + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. + + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) + + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) + + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) + + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) + + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) + + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) + + // if lchmod/lchown do not exist, then make them no-ops + if (fs.chmod && !fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} + } + if (fs.chown && !fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} + } + + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. + + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = typeof fs.rename !== 'function' ? fs.rename + : (function (fs$rename) { + function rename (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) + return rename + })(fs.rename) + } + + // if read() returns EAGAIN, then just try it again. + fs.read = typeof fs.read !== 'function' ? fs.read + : (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + + // This ensures `util.promisify` works as it does for native `fs.read`. + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) + return read + })(fs.read) + + fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync + : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) + + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } + + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + } + + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } + + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + + } else if (fs.futimes) { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } + } + + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } + + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + + + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } + + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } + } + + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + return stats; + } + } + + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true + + if (er.code === "ENOSYS") + return true + + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } + + return false + } +} diff --git a/client/node_modules/jiti/LICENSE b/client/node_modules/jiti/LICENSE new file mode 100644 index 0000000..e739abc --- /dev/null +++ b/client/node_modules/jiti/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Pooya Parsa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/client/node_modules/jiti/README.md b/client/node_modules/jiti/README.md new file mode 100644 index 0000000..b3af483 --- /dev/null +++ b/client/node_modules/jiti/README.md @@ -0,0 +1,258 @@ +# jiti + + + +[![npm version](https://img.shields.io/npm/v/jiti?color=F0DB4F)](https://npmjs.com/package/jiti) +[![npm downloads](https://img.shields.io/npm/dm/jiti?color=F0DB4F)](https://npmjs.com/package/jiti) +[![bundle size](https://img.shields.io/bundlephobia/minzip/jiti?color=F0DB4F)](https://bundlephobia.com/package/jiti) + + + +> This is the active development branch. Check out [jiti/v1](https://github.com/unjs/jiti/tree/v1) for legacy v1 docs and code. + +## 🌟 Used in + +[Docusaurus](https://docusaurus.io/), [ESLint](https://github.com/eslint/eslint), [FormKit](https://formkit.com/), [Histoire](https://histoire.dev/), [Knip](https://knip.dev/), [Nitro](https://nitro.unjs.io/), [Nuxt](https://nuxt.com/), [PostCSS loader](https://github.com/webpack-contrib/postcss-loader), [Rsbuild](https://rsbuild.dev/), [Size Limit](https://github.com/ai/size-limit), [Slidev](https://sli.dev/), [Tailwindcss](https://tailwindcss.com/), [Tokenami](https://github.com/tokenami/tokenami), [UnoCSS](https://unocss.dev/), [WXT](https://wxt.dev/), [Winglang](https://www.winglang.io/), [Graphql code generator](https://the-guild.dev/graphql/codegen), [Lingui](https://lingui.dev/), [Scaffdog](https://scaff.dog/), [Storybook](https://storybook.js.org), [...UnJS ecosystem](https://unjs.io/), [...60M+ npm monthly downloads](https://npm.chart.dev/jiti), [...6M+ public repositories](https://github.com/unjs/jiti/network/dependents). + +## ✅ Features + +- Seamless TypeScript and ESM syntax support for Node.js +- Seamless interoperability between ESM and CommonJS +- Asynchronous API to replace `import()` +- Synchronous API to replace `require()` (deprecated) +- Super slim and zero dependency +- Custom resolve aliases +- Smart syntax detection to avoid extra transforms +- Node.js native `require.cache` integration +- Filesystem transpile with hard disk caches +- ESM Loader support +- JSX support (opt-in) + +> [!IMPORTANT] +> To enhance compatibility, jiti `>=2.1` enabled [`interopDefault`](#interopdefault) using a new Proxy method. If you migrated to `2.0.0` earlier, this might have caused behavior changes. In case of any issues during the upgrade, please [report](https://github.com/unjs/jiti/issues) so we can investigate to solve them. 🙏🏼 + +## 💡 Usage + +### CLI + +You can use `jiti` CLI to quickly run any script with TypeScript and native ESM support! + +```bash +npx jiti ./index.ts +``` + +### Programmatic + +Initialize a jiti instance: + +```js +// ESM +import { createJiti } from "jiti"; +const jiti = createJiti(import.meta.url); + +// CommonJS (deprecated) +const { createJiti } = require("jiti"); +const jiti = createJiti(__filename); +``` + +Import (async) and resolve with ESM compatibility: + +```js +// jiti.import(id) is similar to import(id) +const mod = await jiti.import("./path/to/file.ts"); + +// jiti.esmResolve(id) is similar to import.meta.resolve(id) +const resolvedPath = jiti.esmResolve("./src"); +``` + +If you need the default export of module, you can use `jiti.import(id, { default: true })` as shortcut to `mod?.default ?? mod`. + +```js +// shortcut to mod?.default ?? mod +const modDefault = await jiti.import("./path/to/file.ts", { default: true }); +``` + +CommonJS (sync & deprecated): + +```js +// jiti() is similar to require(id) +const mod = jiti("./path/to/file.ts"); + +// jiti.resolve() is similar to require.resolve(id) +const resolvedPath = jiti.resolve("./src"); +``` + +You can also pass options as the second argument: + +```js +const jiti = createJiti(import.meta.url, { debug: true }); +``` + +### Register global ESM loader + +You can globally register jiti using [global hooks](https://nodejs.org/api/module.html#initialize). (Important: Requires Node.js > 20) + +```js +import "jiti/register"; +``` + +Or: + +```bash +node --import jiti/register index.ts +``` + +## 🎈 `jiti/native` + +You can alias `jiti` to `jiti/native` to directly depend on runtime's [`import.meta.resolve`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta/resolve) and dynamic [`import()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) support. This allows easing up the ecosystem transition to runtime native support by giving the same API of jiti. + +## ⚙️ Options + +### `debug` + +- Type: Boolean +- Default: `false` +- Environment variable: `JITI_DEBUG` + +Enable verbose logging. You can use `JITI_DEBUG=1 ` to enable it. + +### `fsCache` + +- Type: Boolean | String +- Default: `true` +- Environment variable: `JITI_FS_CACHE` + +Filesystem source cache (enabled by default) + +By default (when is `true`), jiti uses `node_modules/.cache/jiti` (if exists) or `{TMP_DIR}/jiti`. + +**Note:** It is recommended that this option be enabled for better performance. + +### `rebuildFsCache` + +- Type: Boolean +- Default: `false` +- Environment variable: `JITI_REBUILD_FS_CACHE` + +Rebuild filesystem source cache created by `fsCache`. + +### `moduleCache` + +- Type: String +- Default: `true` +- Environment variable: `JITI_MODULE_CACHE` + +Runtime module cache (enabled by default). + +Disabling allows editing code and importing the same module multiple times. + +When enabled, jiti integrates with Node.js native CommonJS cache-store. + +### `transform` + +- Type: Function +- Default: Babel (lazy loaded) + +Transform function. See [src/babel](./src/babel.ts) for more details + +### `sourceMaps` + +- Type: Boolean +- Default `false` +- Environment variable: `JITI_SOURCE_MAPS` + +Add inline source map to transformed source for better debugging. + +### `interopDefault` + +- Type: Boolean +- Default: `true` +- Environment variable: `JITI_INTEROP_DEFAULT` + +Jiti combines module exports with the `default` export using an internal Proxy to improve compatibility with mixed CJS/ESM usage. You can check the current implementation [here](https://github.com/unjs/jiti/blob/main/src/utils.ts#L105). + +> [!WARNING] +> This option wraps **all imported modules** in a Proxy, which adds ~25-50ns overhead per property access. For performance-critical hot paths where you access module exports very frequently, consider setting `interopDefault: false` or `JITI_INTEROP_DEFAULT=false`. + +### `alias` + +- Type: Object +- Default: - +- Environment variable: `JITI_ALIAS` + +You can also pass an object to the environment variable for inline config. Example: `JITI_ALIAS='{"~/*": "./src/*"}' jiti ...`. + +Custom alias map used to resolve IDs. + +### `tsconfigPaths` + +- Type: Boolean | String +- Default: `false` +- Environment variable: `JITI_TSCONFIG_PATHS` + +Enable TypeScript [`paths`](https://www.typescriptlang.org/tsconfig/#paths) resolution using [`get-tsconfig`](https://github.com/privatenumber/get-tsconfig). + +- `true`: Auto-discover `tsconfig.json` by walking up from the jiti instance's parent path. +- `string`: Explicit path to a `tsconfig.json` file. +- `false` (default): Disabled. + +### `nativeModules` + +- Type: Array +- Default: ['typescript'] +- Environment variable: `JITI_NATIVE_MODULES` + +List of modules (within `node_modules`) to always use native `require()` for them. + +### `transformModules` + +- Type: Array +- Default: [] +- Environment variable: `JITI_TRANSFORM_MODULES` + +List of modules (within `node_modules`) to transform them regardless of syntax. + +### `importMeta` + +Parent module's [`import.meta`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta) context to use for ESM resolution. (only used for `jiti/native` import). + +### `tryNative` + +- Type: Boolean +- Default: Enabled if bun is detected +- Environment variable: `JITI_TRY_NATIVE` + +Try to use native require and import without jiti transformations first. + +### `jsx` + +- Type: Boolean | {options} +- Default: `false` +- Environment Variable: `JITI_JSX` + +Enable JSX support using [`@babel/plugin-transform-react-jsx`](https://babeljs.io/docs/babel-plugin-transform-react-jsx). + +See [`test/fixtures/jsx`](./test/fixtures/jsx) for framework integration examples. + +## Development + +- Clone this repository +- Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable` +- Install dependencies using `pnpm install` +- Run `pnpm dev` +- Run `pnpm jiti ./test/path/to/file.ts` + +## License + + + +Published under the [MIT](https://github.com/unjs/jiti/blob/main/LICENSE) license. +Made by [@pi0](https://github.com/pi0) and [community](https://github.com/unjs/jiti/graphs/contributors) 💛 +

+ + + + + + + diff --git a/client/node_modules/jiti/dist/babel.cjs b/client/node_modules/jiti/dist/babel.cjs new file mode 100644 index 0000000..1e6b684 --- /dev/null +++ b/client/node_modules/jiti/dist/babel.cjs @@ -0,0 +1,257 @@ +(()=>{var e={"./node_modules/.pnpm/@babel+core@7.29.0/node_modules/@babel/core/lib/config/files lazy recursive"(e){function webpackEmptyAsyncContext(e){return Promise.resolve().then(function(){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}webpackEmptyAsyncContext.keys=()=>[],webpackEmptyAsyncContext.resolve=webpackEmptyAsyncContext,webpackEmptyAsyncContext.id="./node_modules/.pnpm/@babel+core@7.29.0/node_modules/@babel/core/lib/config/files lazy recursive",e.exports=webpackEmptyAsyncContext},"./node_modules/.pnpm/@babel+core@7.29.0/node_modules/@babel/core/lib/config/files sync recursive"(e){function webpackEmptyContext(e){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}webpackEmptyContext.keys=()=>[],webpackEmptyContext.resolve=webpackEmptyContext,webpackEmptyContext.id="./node_modules/.pnpm/@babel+core@7.29.0/node_modules/@babel/core/lib/config/files sync recursive",e.exports=webpackEmptyContext},"./node_modules/.pnpm/@babel+plugin-syntax-class-properties@7.12.13_@babel+core@7.29.0/node_modules/@babel/plugin-syntax-class-properties/lib/index.js"(e,t,r){"use strict";t.A=void 0;var n=(0,r("./node_modules/.pnpm/@babel+helper-plugin-utils@7.28.6/node_modules/@babel/helper-plugin-utils/lib/index.js").declare)(e=>(e.assertVersion(7),{name:"syntax-class-properties",manipulateOptions(e,t){t.plugins.push("classProperties","classPrivateProperties","classPrivateMethods")}}));t.A=n},"./node_modules/.pnpm/@jridgewell+gen-mapping@0.3.13/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js"(e,t,r){var n;!function(e,t,r){"use strict";var n=Object.create,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,a=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty,__commonJS=(e,t)=>function(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},__export=(e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})},__copyProps=(e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let a of o(t))l.call(e,a)||a===r||s(e,a,{get:()=>t[a],enumerable:!(n=i(t,a))||n.enumerable});return e},__toESM=(e,t,r)=>(r=null!=e?n(a(e)):{},__copyProps(!t&&e&&e.__esModule?r:s(r,"default",{value:e,enumerable:!0}),e)),__toCommonJS=e=>__copyProps(s({},"__esModule",{value:!0}),e),p=__commonJS({"umd:@jridgewell/sourcemap-codec"(e,r){r.exports=t}}),c=__commonJS({"umd:@jridgewell/trace-mapping"(e,t){t.exports=r}}),u={};__export(u,{GenMapping:()=>E,addMapping:()=>addMapping,addSegment:()=>addSegment,allMappings:()=>allMappings,fromMap:()=>fromMap,maybeAddMapping:()=>maybeAddMapping,maybeAddSegment:()=>maybeAddSegment,setIgnore:()=>setIgnore,setSourceContent:()=>setSourceContent,toDecodedMap:()=>toDecodedMap,toEncodedMap:()=>toEncodedMap}),e.exports=__toCommonJS(u);var d=class{constructor(){this._indexes={__proto__:null},this.array=[]}};function cast(e){return e}function get(e,t){return cast(e)._indexes[t]}function put(e,t){const r=get(e,t);if(void 0!==r)return r;const{array:n,_indexes:s}=cast(e),i=n.push(t);return s[t]=i-1}function remove(e,t){const r=get(e,t);if(void 0===r)return;const{array:n,_indexes:s}=cast(e);for(let e=r+1;eaddSegmentInternal(!0,e,t,r,n,s,i,o,a),maybeAddMapping=(e,t)=>addMappingInternal(!0,e,t);function setSourceContent(e,t,r){const{_sources:n,_sourcesContent:s}=cast2(e);s[put(n,t)]=r}function setIgnore(e,t,r=!0){const{_sources:n,_sourcesContent:s,_ignoreList:i}=cast2(e),o=put(n,t);o===s.length&&(s[o]=null),r?put(i,o):remove(i,o)}function toDecodedMap(e){const{_mappings:t,_sources:r,_sourcesContent:n,_names:s,_ignoreList:i}=cast2(e);return removeEmptyFinalLines(t),{version:3,file:e.file||void 0,names:s.array,sourceRoot:e.sourceRoot||void 0,sources:r.array,sourcesContent:n,mappings:t,ignoreList:i.array}}function toEncodedMap(e){const t=toDecodedMap(e);return Object.assign({},t,{mappings:(0,h.encode)(t.mappings)})}function fromMap(e){const t=new m.TraceMap(e),r=new E({file:t.file,sourceRoot:t.sourceRoot});return putAll(cast2(r)._names,t.names),putAll(cast2(r)._sources,t.sources),cast2(r)._sourcesContent=t.sourcesContent||t.sources.map(()=>null),cast2(r)._mappings=(0,m.decodedMappings)(t),t.ignoreList&&putAll(cast2(r)._ignoreList,t.ignoreList),r}function allMappings(e){const t=[],{_mappings:r,_sources:n,_names:s}=cast2(e);for(let e=0;e=0&&!(t>=e[n][f]);r=n--);return r}function insert(e,t,r){for(let r=e.length;r>t;r--)e[r]=e[r-1];e[t]=r}function removeEmptyFinalLines(e){const{length:t}=e;let r=t;for(let t=r-1;t>=0&&!(e[t].length>0);r=t,t--);rfunction(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},__export=(e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})},__copyProps=(e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let a of o(t))l.call(e,a)||a===r||s(e,a,{get:()=>t[a],enumerable:!(n=i(t,a))||n.enumerable});return e},__toESM=(e,t,r)=>(r=null!=e?n(a(e)):{},__copyProps(!t&&e&&e.__esModule?r:s(r,"default",{value:e,enumerable:!0}),e)),__toCommonJS=e=>__copyProps(s({},"__esModule",{value:!0}),e),p=__commonJS({"umd:@jridgewell/trace-mapping"(e,t){t.exports=r}}),c=__commonJS({"umd:@jridgewell/gen-mapping"(e,r){r.exports=t}}),u={};__export(u,{default:()=>remapping}),e.exports=__toCommonJS(u);var d=__toESM(p()),h=__toESM(c()),m=__toESM(p()),f=SegmentObject("",-1,-1,"",null,!1),y=[];function SegmentObject(e,t,r,n,s,i){return{source:e,line:t,column:r,name:n,content:s,ignore:i}}function Source(e,t,r,n,s){return{map:e,sources:t,source:r,content:n,ignore:s}}function MapSource(e,t){return Source(e,t,"",null,!1)}function OriginalSource(e,t,r){return Source(null,y,e,t,r)}function traceMappings(e){const t=new h.GenMapping({file:e.map.file}),{sources:r,map:n}=e,s=n.names,i=(0,m.decodedMappings)(n);for(let e=0;enew d.TraceMap(e,"")),n=r.pop();for(let e=0;e1)throw new Error(`Transformation map ${e} must have exactly one source file.\nDid you specify these with the most recent transformation maps first?`);let s=build(n,t,"",0);for(let e=r.length-1;e>=0;e--)s=MapSource(r[e],[s]);return s}function build(e,t,r,n){const{resolvedSources:s,sourcesContent:i,ignoreList:o}=e,a=n+1;return MapSource(e,s.map((e,n)=>{const s={importer:r,depth:a,source:e||"",content:void 0,ignore:void 0},l=t(s.source,s),{source:p,content:c,ignore:u}=s;return l?build(new d.TraceMap(l,p),t,p,a):OriginalSource(p,void 0!==c?c:i?i[n]:null,void 0!==u?u:!!o&&o.includes(n))}))}var b=__toESM(c()),g=class{constructor(e,t){const r=t.decodedMappings?(0,b.toDecodedMap)(e):(0,b.toEncodedMap)(e);this.version=r.version,this.file=r.file,this.mappings=r.mappings,this.names=r.names,this.ignoreList=r.ignoreList,this.sourceRoot=r.sourceRoot,this.sources=r.sources,t.excludeContent||(this.sourcesContent=r.sourcesContent)}toString(){return JSON.stringify(this)}};function remapping(e,t,r){const n="object"==typeof r?r:{excludeContent:!!r,decodedMappings:!1},s=buildSourceMapTree(e,t);return new g(traceMappings(s),n)}}(e=r.nmd(e),r("./node_modules/.pnpm/@jridgewell+gen-mapping@0.3.13/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js"),r("./node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js")),e.exports="default"in(n=e).exports?n.exports.default:n.exports},"./node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js"(e){e.exports=function(){"use strict";const e=/^[\w+.-]+:\/\//,t=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,r=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function isAbsoluteUrl(t){return e.test(t)}function isSchemeRelativeUrl(e){return e.startsWith("//")}function isAbsolutePath(e){return e.startsWith("/")}function isFileUrl(e){return e.startsWith("file:")}function isRelative(e){return/^[.?#]/.test(e)}function parseAbsoluteUrl(e){const r=t.exec(e);return makeUrl(r[1],r[2]||"",r[3],r[4]||"",r[5]||"/",r[6]||"",r[7]||"")}function parseFileUrl(e){const t=r.exec(e),n=t[2];return makeUrl("file:","",t[1]||"","",isAbsolutePath(n)?n:"/"+n,t[3]||"",t[4]||"")}function makeUrl(e,t,r,n,s,i,o){return{scheme:e,user:t,host:r,port:n,path:s,query:i,hash:o,type:7}}function parseUrl(e){if(isSchemeRelativeUrl(e)){const t=parseAbsoluteUrl("http:"+e);return t.scheme="",t.type=6,t}if(isAbsolutePath(e)){const t=parseAbsoluteUrl("http://foo.com"+e);return t.scheme="",t.host="",t.type=5,t}if(isFileUrl(e))return parseFileUrl(e);if(isAbsoluteUrl(e))return parseAbsoluteUrl(e);const t=parseAbsoluteUrl("http://foo.com/"+e);return t.scheme="",t.host="",t.type=e?e.startsWith("?")?3:e.startsWith("#")?2:4:1,t}function stripPathFilename(e){if(e.endsWith("/.."))return e;const t=e.lastIndexOf("/");return e.slice(0,t+1)}function mergePaths(e,t){normalizePath(t,t.type),"/"===e.path?e.path=t.path:e.path=stripPathFilename(t.path)+e.path}function normalizePath(e,t){const r=t<=4,n=e.path.split("/");let s=1,i=0,o=!1;for(let e=1;en&&(n=s)}normalizePath(r,n);const s=r.query+r.hash;switch(n){case 2:case 3:return s;case 4:{const n=r.path.slice(1);return n?isRelative(t||e)&&!isRelative(n)?"./"+n+s:n+s:s||"."}case 5:return r.path+s;default:return r.scheme+"//"+r.user+r.host+r.port+r.path+s}}return resolve}()},"./node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js"(e,t,r){var n;!function(e){"use strict";var t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,__copyProps=(e,i,o,a)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let l of n(i))s.call(e,l)||l===o||t(e,l,{get:()=>i[l],enumerable:!(a=r(i,l))||a.enumerable});return e},__toCommonJS=e=>__copyProps(t({},"__esModule",{value:!0}),e),i={};((e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:!0})})(i,{decode:()=>decode,decodeGeneratedRanges:()=>decodeGeneratedRanges,decodeOriginalScopes:()=>decodeOriginalScopes,encode:()=>encode,encodeGeneratedRanges:()=>encodeGeneratedRanges,encodeOriginalScopes:()=>encodeOriginalScopes}),e.exports=__toCommonJS(i);var o=",".charCodeAt(0),a=";".charCodeAt(0),l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=new Uint8Array(64),c=new Uint8Array(128);for(let e=0;e>>=1,i&&(r=-2147483648|-r),t+r}function encodeInteger(e,t,r){let n=t-r;n=n<0?-n<<1|1:n<<1;do{let t=31&n;n>>>=5,n>0&&(t|=32),e.write(p[t])}while(n>0);return t}function hasMoreVlq(e,t){return!(e.pos>=t)&&e.peek()!==o}var u=16384,d="undefined"!=typeof TextDecoder?new TextDecoder:"undefined"!=typeof Buffer?{decode:e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString()}:{decode(e){let t="";for(let r=0;r0?t+d.decode(e.subarray(0,r)):t}},m=class{constructor(e){this.pos=0,this.buffer=e}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(e){const{buffer:t,pos:r}=this,n=t.indexOf(e,r);return-1===n?t.length:n}},f=[];function decodeOriginalScopes(e){const{length:t}=e,r=new m(e),n=[],s=[];let i=0;for(;r.pos0&&r.write(o),n[0]=encodeInteger(r,i,n[0]),encodeInteger(r,a,0),encodeInteger(r,c,0),encodeInteger(r,6===s.length?1:0,0),6===s.length&&encodeInteger(r,s[5],0);for(const e of u)encodeInteger(r,e,0);for(t++;tl||i===l&&o>=p)break;t=_encodeOriginalScopes(e,t,r,n)}return r.write(o),n[0]=encodeInteger(r,l,n[0]),encodeInteger(r,p,0),t}function decodeGeneratedRanges(e){const{length:t}=e,r=new m(e),n=[],s=[];let i=0,o=0,a=0,l=0,p=0,c=0,u=0,d=0;do{const e=r.indexOf(";");let t=0;for(;r.pose;t--){const e=u;u=decodeInteger(r,u),d=decodeInteger(r,u===e?d:0);const t=decodeInteger(r,0);n.push([t,u,d])}}else n=[[e]];x.push(n)}while(hasMoreVlq(r,e))}b.bindings=x,n.push(b),s.push(b)}i++,r.pos=e+1}while(r.pos0&&r.write(o),n[1]=encodeInteger(r,s[1],n[1]),encodeInteger(r,(6===s.length?1:0)|(u?2:0)|(c?4:0),0),6===s.length){const{4:e,5:t}=s;e!==n[2]&&(n[3]=0),n[2]=encodeInteger(r,e,n[2]),n[3]=encodeInteger(r,t,n[3])}if(u){const{0:e,1:t,2:i}=s.callsite;e!==n[4]?(n[5]=0,n[6]=0):t!==n[5]&&(n[6]=0),n[4]=encodeInteger(r,e,n[4]),n[5]=encodeInteger(r,t,n[5]),n[6]=encodeInteger(r,i,n[6])}if(d)for(const e of d){e.length>1&&encodeInteger(r,-e.length,0),encodeInteger(r,e[0][0],0);let t=i,n=a;for(let s=1;sl||i===l&&o>=p)break;t=_encodeGeneratedRanges(e,t,r,n)}return n[0]0&&t.write(a),0===p.length)continue;let c=0;for(let e=0;e0&&t.write(o),c=encodeInteger(t,a[0],c),1!==a.length&&(r=encodeInteger(t,a[1],r),n=encodeInteger(t,a[2],n),s=encodeInteger(t,a[3],s),4!==a.length&&(i=encodeInteger(t,a[4],i)))}}return t.flush()}}(e=r.nmd(e)),e.exports="default"in(n=e).exports?n.exports.default:n.exports},"./node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js"(e,t,r){var n;!function(e,t,r){"use strict";var n=Object.create,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,a=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty,__commonJS=(e,t)=>function(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},__export=(e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})},__copyProps=(e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let a of o(t))l.call(e,a)||a===r||s(e,a,{get:()=>t[a],enumerable:!(n=i(t,a))||n.enumerable});return e},__toESM=(e,t,r)=>(r=null!=e?n(a(e)):{},__copyProps(!t&&e&&e.__esModule?r:s(r,"default",{value:e,enumerable:!0}),e)),__toCommonJS=e=>__copyProps(s({},"__esModule",{value:!0}),e),p=__commonJS({"umd:@jridgewell/sourcemap-codec"(e,t){t.exports=r}}),c=__commonJS({"umd:@jridgewell/resolve-uri"(e,r){r.exports=t}}),u={};__export(u,{AnyMap:()=>FlattenMap,FlattenMap:()=>FlattenMap,GREATEST_LOWER_BOUND:()=>_,LEAST_UPPER_BOUND:()=>P,TraceMap:()=>A,allGeneratedPositionsFor:()=>allGeneratedPositionsFor,decodedMap:()=>decodedMap,decodedMappings:()=>decodedMappings,eachMapping:()=>eachMapping,encodedMap:()=>encodedMap,encodedMappings:()=>encodedMappings,generatedPositionFor:()=>generatedPositionFor,isIgnored:()=>isIgnored,originalPositionFor:()=>originalPositionFor,presortedDecodedMap:()=>presortedDecodedMap,sourceContentFor:()=>sourceContentFor,traceSegment:()=>traceSegment}),e.exports=__toCommonJS(u);var d=__toESM(p()),h=__toESM(c());function stripFilename(e){if(!e)return"";const t=e.lastIndexOf("/");return e.slice(0,t+1)}function resolver(e,t){const r=stripFilename(e),n=t?t+"/":"";return e=>(0,h.default)(n+(e||""),r)}var m=0,f=1,y=2,b=3,g=4,x=1,v=2;function maybeSort(e,t){const r=nextUnsortedSegmentLine(e,0);if(r===e.length)return e;t||(e=e.slice());for(let n=r;n[]);for(let t=0;t>1),i=e[s][m]-t;if(0===i)return E=!0,s;i<0?r=s+1:n=s-1}return E=!1,r-1}function upperBound(e,t,r){for(let n=r+1;n=0&&e[n][m]===t;r=n--);return r}function memoizedState(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function memoizedBinarySearch(e,t,r,n){const{lastKey:s,lastNeedle:i,lastIndex:o}=r;let a=0,l=e.length-1;if(n===s){if(t===i)return E=-1!==o&&e[o][m]===t,o;t>=i?a=-1===o?0:o:l=o}return r.lastKey=n,r.lastNeedle=t,r.lastIndex=binarySearch(e,t,a,l)}function parse(e){return"string"==typeof e?JSON.parse(e):e}var FlattenMap=function(e,t){const r=parse(e);if(!("sections"in r))return new A(r,t);const n=[],s=[],i=[],o=[],a=[];return recurse(r,t,n,s,i,o,a,0,0,1/0,1/0),presortedDecodedMap({version:3,file:r.file,names:o,sources:s,sourcesContent:i,mappings:n,ignoreList:a})};function recurse(e,t,r,n,s,i,o,a,l,p,c){const{sections:u}=e;for(let e=0;ep)return;const n=getLine(r,t),s=0===e?l:0,i=v[e];for(let e=0;e=c)return;if(1===r.length){n.push([o]);continue}const a=h+r[f],l=r[y],u=r[b];n.push(4===r.length?[o,a,l,u]:[o,a,l,u,x+r[g]])}}}function append(e,t){for(let r=0;r=n.length)return null;const s=n[t],i=traceSegmentInternal(s,cast(e)._decodedMemo,t,r,_);return-1===i?null:s[i]}function originalPositionFor(e,t){let{line:r,column:n,bias:s}=t;if(r--,r<0)throw new Error(T);if(n<0)throw new Error(S);const i=decodedMappings(e);if(r>=i.length)return OMapping(null,null,null,null);const o=i[r],a=traceSegmentInternal(o,cast(e)._decodedMemo,r,n,s||_);if(-1===a)return OMapping(null,null,null,null);const l=o[a];if(1===l.length)return OMapping(null,null,null,null);const{names:p,resolvedSources:c}=e;return OMapping(c[l[f]],l[y]+1,l[b],5===l.length?p[l[g]]:null)}function generatedPositionFor(e,t){const{source:r,line:n,column:s,bias:i}=t;return generatedPosition(e,r,n,s,i||_,!1)}function allGeneratedPositionsFor(e,t){const{source:r,line:n,column:s,bias:i}=t;return generatedPosition(e,r,n,s,i||P,!0)}function eachMapping(e,t){const r=decodedMappings(e),{names:n,resolvedSources:s}=e;for(let e=0;e{"%%"!==e&&(n++,"%c"===e&&(s=n))}),t.splice(s,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r("./node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js")(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},"./node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js"(e,t,r){e.exports=function(e){function createDebug(e){let t,r,n,s=null;function debug(...e){if(!debug.enabled)return;const r=debug,n=Number(new Date),s=n-(t||n);r.diff=s,r.prev=t,r.curr=n,t=n,e[0]=createDebug.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,n)=>{if("%%"===t)return"%";i++;const s=createDebug.formatters[n];if("function"==typeof s){const n=e[i];t=s.call(r,n),e.splice(i,1),i--}return t}),createDebug.formatArgs.call(r,e);(r.log||createDebug.log).apply(r,e)}return debug.namespace=e,debug.useColors=createDebug.useColors(),debug.color=createDebug.selectColor(e),debug.extend=extend,debug.destroy=createDebug.destroy,Object.defineProperty(debug,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(r!==createDebug.namespaces&&(r=createDebug.namespaces,n=createDebug.enabled(e)),n),set:e=>{s=e}}),"function"==typeof createDebug.init&&createDebug.init(debug),debug}function extend(e,t){const r=createDebug(this.namespace+(void 0===t?":":t)+e);return r.log=this.log,r}function matchesTemplate(e,t){let r=0,n=0,s=-1,i=0;for(;r"-"+e)].join(",");return createDebug.enable(""),e},createDebug.enable=function(e){createDebug.save(e),createDebug.namespaces=e,createDebug.names=[],createDebug.skips=[];const t=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of t)"-"===e[0]?createDebug.skips.push(e.slice(1)):createDebug.names.push(e)},createDebug.enabled=function(e){for(const t of createDebug.skips)if(matchesTemplate(e,t))return!1;for(const t of createDebug.names)if(matchesTemplate(e,t))return!0;return!1},createDebug.humanize=r("./node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js"),createDebug.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(t=>{createDebug[t]=e[t]}),createDebug.names=[],createDebug.skips=[],createDebug.formatters={},createDebug.selectColor=function(e){let t=0;for(let r=0;r{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=r("./node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js");e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}t.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{const r=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase());let n=process.env[t];return n=!!/^(yes|on|true|enabled)$/i.test(n)||!/^(no|off|false|disabled)$/i.test(n)&&("null"===n?null:Number(n)),e[r]=n,e},{}),e.exports=r("./node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js")(t);const{formatters:i}=e.exports;i.o=function(e){return this.inspectOpts.colors=this.useColors,s.inspect(e,this.inspectOpts).split("\n").map(e=>e.trim()).join(" ")},i.O=function(e){return this.inspectOpts.colors=this.useColors,s.inspect(e,this.inspectOpts)}},"./node_modules/.pnpm/gensync@1.0.0-beta.2/node_modules/gensync/index.js"(e){"use strict";const t=Symbol.for("gensync:v1:start"),r=Symbol.for("gensync:v1:suspend"),n="GENSYNC_OPTIONS_ERROR",s="GENSYNC_RACE_NONEMPTY",i="GENSYNC_ERRBACK_NO_CALLBACK";function assertTypeof(e,t,r,s){if(typeof r===e||s&&void 0===r)return;let i;throw i=s?`Expected opts.${t} to be either a ${e}, or undefined.`:`Expected opts.${t} to be a ${e}.`,makeError(i,n)}function makeError(e,t){return Object.assign(new Error(e),{code:t})}function buildOperation({name:e,arity:n,sync:s,async:i}){return setFunctionMetadata(e,n,function*(...e){const n=yield t;if(!n){return s.call(this,e)}let o;try{i.call(this,e,e=>{o||(o={value:e},n())},e=>{o||(o={err:e},n())})}catch(e){o={err:e},n()}if(yield r,o.hasOwnProperty("err"))throw o.err;return o.value})}function evaluateSync(e){let t;for(;!({value:t}=e.next()).done;)assertStart(t,e);return t}function evaluateAsync(e,t,r){!function step(){try{let r;for(;!({value:r}=e.next()).done;){assertStart(r,e);let t=!0,n=!1;const s=e.next(()=>{t?n=!0:step()});if(t=!1,assertSuspend(s,e),!n)return}return t(r)}catch(e){return r(e)}}()}function assertStart(e,r){e!==t&&throwError(r,makeError(`Got unexpected yielded value in gensync generator: ${JSON.stringify(e)}. Did you perhaps mean to use 'yield*' instead of 'yield'?`,"GENSYNC_EXPECTED_START"))}function assertSuspend({value:e,done:t},n){(t||e!==r)&&throwError(n,makeError(t?"Unexpected generator completion. If you get this, it is probably a gensync bug.":`Expected GENSYNC_SUSPEND, got ${JSON.stringify(e)}. If you get this, it is probably a gensync bug.`,"GENSYNC_EXPECTED_SUSPEND"))}function throwError(e,t){throw e.throw&&e.throw(t),t}function setFunctionMetadata(e,t,r){if("string"==typeof e){const t=Object.getOwnPropertyDescriptor(r,"name");t&&!t.configurable||Object.defineProperty(r,"name",Object.assign(t||{},{configurable:!0,value:e}))}if("number"==typeof t){const e=Object.getOwnPropertyDescriptor(r,"length");e&&!e.configurable||Object.defineProperty(r,"length",Object.assign(e||{},{configurable:!0,value:t}))}return r}e.exports=Object.assign(function(e){let t=e;return t="function"!=typeof e?function({name:e,arity:t,sync:r,async:s,errback:i}){if(assertTypeof("string","name",e,!0),assertTypeof("number","arity",t,!0),assertTypeof("function","sync",r),assertTypeof("function","async",s,!0),assertTypeof("function","errback",i,!0),s&&i)throw makeError("Expected one of either opts.async or opts.errback, but got _both_.",n);if("string"!=typeof e){let t;i&&i.name&&"errback"!==i.name&&(t=i.name),s&&s.name&&"async"!==s.name&&(t=s.name.replace(/Async$/,"")),r&&r.name&&"sync"!==r.name&&(t=r.name.replace(/Sync$/,"")),"string"==typeof t&&(e=t)}"number"!=typeof t&&(t=r.length);return buildOperation({name:e,arity:t,sync:function(e){return r.apply(this,e)},async:function(e,t,n){s?s.apply(this,e).then(t,n):i?i.call(this,...e,(e,r)=>{null==e?t(r):n(e)}):t(r.apply(this,e))}})}(e):function(e){return setFunctionMetadata(e.name,e.length,function(...t){return e.apply(this,t)})}(e),Object.assign(t,function(e){const t={sync:function(...t){return evaluateSync(e.apply(this,t))},async:function(...t){return new Promise((r,n)=>{evaluateAsync(e.apply(this,t),r,n)})},errback:function(...t){const r=t.pop();if("function"!=typeof r)throw makeError("Asynchronous function called without callback",i);let n;try{n=e.apply(this,t)}catch(e){return void r(e)}evaluateAsync(n,e=>r(void 0,e),e=>r(e))}};return t}(t))},{all:buildOperation({name:"all",arity:1,sync:function(e){return Array.from(e[0]).map(e=>evaluateSync(e))},async:function(e,t,r){const n=Array.from(e[0]);if(0===n.length)return void Promise.resolve().then(()=>t([]));let s=0;const i=n.map(()=>{});n.forEach((e,n)=>{evaluateAsync(e,e=>{i[n]=e,s+=1,s===i.length&&t(i)},r)})}}),race:buildOperation({name:"race",arity:1,sync:function(e){const t=Array.from(e[0]);if(0===t.length)throw makeError("Must race at least 1 item",s);return evaluateSync(t[0])},async:function(e,t,r){const n=Array.from(e[0]);if(0===n.length)throw makeError("Must race at least 1 item",s);for(const e of n)evaluateAsync(e,t,r)}})})},"./node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js"(e){"use strict";e.exports=(e,t=process.argv)=>{const r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),s=t.indexOf("--");return-1!==n&&(-1===s||n{for(const n in e)r.call(e,n)&&t(n,e[n])},fourHexEscape=e=>"\\u"+("0000"+e).slice(-4),hexadecimal=(e,t)=>{let r=e.toString(16);return t?r:r.toUpperCase()},n=t.toString,s=Array.isArray,isBigInt=e=>"bigint"==typeof e,i={"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t"},o=/[\\\b\f\n\r\t]/,a=/[0-9]/,l=/[\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/,p=/([\uD800-\uDBFF][\uDC00-\uDFFF])|([\uD800-\uDFFF])|(['"`])|[^]/g,c=/([\uD800-\uDBFF][\uDC00-\uDFFF])|([\uD800-\uDFFF])|(['"`])|[^ !#-&\(-\[\]-_a-~]/g,jsesc=(e,t)=>{const increaseIndentation=()=>{g=b,++t.indentLevel,b=t.indent.repeat(t.indentLevel)},r={escapeEverything:!1,minimal:!1,isScriptContext:!1,quotes:"single",wrap:!1,es6:!1,json:!1,compact:!0,lowercaseHex:!1,numbers:"decimal",indent:"\t",indentLevel:0,__inline1__:!1,__inline2__:!1},u=t&&t.json;var d,h;u&&(r.quotes="double",r.wrap=!0),d=r,"single"!=(t=(h=t)?(forOwn(h,(e,t)=>{d[e]=t}),d):d).quotes&&"double"!=t.quotes&&"backtick"!=t.quotes&&(t.quotes="single");const m="double"==t.quotes?'"':"backtick"==t.quotes?"`":"'",f=t.compact,y=t.lowercaseHex;let b=t.indent.repeat(t.indentLevel),g="";const x=t.__inline1__,v=t.__inline2__,E=f?"":"\n";let T,S=!0;const P="binary"==t.numbers,_="octal"==t.numbers,A="decimal"==t.numbers,C="hexadecimal"==t.numbers;if(u&&e&&(e=>"function"==typeof e)(e.toJSON)&&(e=e.toJSON()),!(e=>"string"==typeof e||"[object String]"==n.call(e))(e)){if((e=>"[object Map]"==n.call(e))(e))return 0==e.size?"new Map()":(f||(t.__inline1__=!0,t.__inline2__=!1),"new Map("+jsesc(Array.from(e),t)+")");if((e=>"[object Set]"==n.call(e))(e))return 0==e.size?"new Set()":"new Set("+jsesc(Array.from(e),t)+")";if((e=>"function"==typeof Buffer&&Buffer.isBuffer(e))(e))return 0==e.length?"Buffer.from([])":"Buffer.from("+jsesc(Array.from(e),t)+")";if(s(e))return T=[],t.wrap=!0,x&&(t.__inline1__=!1,t.__inline2__=!0),v||increaseIndentation(),((e,t)=>{const r=e.length;let n=-1;for(;++n{S=!1,v&&(t.__inline2__=!1),T.push((f||v?"":b)+jsesc(e,t))}),S?"[]":v?"["+T.join(", ")+"]":"["+E+T.join(","+E)+E+(f?"":g)+"]";if((e=>"number"==typeof e||"[object Number]"==n.call(e))(e)||isBigInt(e)){if(u)return JSON.stringify(Number(e));let t;if(A)t=String(e);else if(C){let r=e.toString(16);y||(r=r.toUpperCase()),t="0x"+r}else P?t="0b"+e.toString(2):_&&(t="0o"+e.toString(8));return isBigInt(e)?t+"n":t}return isBigInt(e)?u?JSON.stringify(Number(e)):e+"n":(e=>"[object Object]"==n.call(e))(e)?(T=[],t.wrap=!0,increaseIndentation(),forOwn(e,(e,r)=>{S=!1,T.push((f?"":b)+jsesc(e,t)+":"+(f?"":" ")+jsesc(r,t))}),S?"{}":"{"+E+T.join(","+E)+E+(f?"":g)+"}"):u?JSON.stringify(e)||"null":String(e)}const w=t.escapeEverything?p:c;return T=e.replace(w,(e,r,n,s,p,c)=>{if(r){if(t.minimal)return r;const e=r.charCodeAt(0),n=r.charCodeAt(1);if(t.es6){return"\\u{"+hexadecimal(1024*(e-55296)+n-56320+65536,y)+"}"}return fourHexEscape(hexadecimal(e,y))+fourHexEscape(hexadecimal(n,y))}if(n)return fourHexEscape(hexadecimal(n.charCodeAt(0),y));if("\0"==e&&!u&&!a.test(c.charAt(p+1)))return"\\0";if(s)return s==m||t.escapeEverything?"\\"+s:s;if(o.test(e))return i[e];if(t.minimal&&!l.test(e))return e;const d=hexadecimal(e.charCodeAt(0),y);return u||d.length>2?fourHexEscape(d):"\\x"+("00"+d).slice(-2)}),"`"==m&&(T=T.replace(/\$\{/g,"\\${")),t.isScriptContext&&(T=T.replace(/<\/(script|style)/gi,"<\\/$1").replace(/