ranuts 0.4.0-alpha.4 → 0.4.1-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +25 -21
- package/README.md +5 -1
- package/README.zh-CN.md +17 -1
- package/dist/{color-DPV7TsVU.js → color-B_KMM8UX.js} +1 -1
- package/dist/i18n-BJIS1fR1.js +1 -0
- package/dist/index.js +1 -1
- package/dist/src/node/index.js +1 -1
- package/dist/src/utils/binary.d.ts +140 -0
- package/dist/src/utils/device.d.ts +8 -0
- package/dist/src/utils/i18n/index.js +1 -1
- package/dist/src/utils/index.d.ts +4 -2
- package/dist/src/utils/index.js +1 -1
- package/dist/src/utils/secure.d.ts +58 -0
- package/dist/src/utils/str.d.ts +75 -0
- package/dist/test/binary.test.d.ts +1 -0
- package/dist/test/utils/secure.test.d.ts +1 -0
- package/dist/test/utils/text-boundary.test.d.ts +1 -0
- package/dist/umd/index.umd.cjs +1 -1
- package/dist/umd/utils/utils.umd.cjs +1 -1
- package/dist/utils-BNwhohXq.js +1 -0
- package/docs/API.md +25 -5
- package/package.json +1 -1
- package/dist/i18n-Bq-f7htr.js +0 -1
- package/dist/utils-CYrYCt5o.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=(e,t=2)=>String(e).padStart(t,"0"),t=e=>null==e?/* @__PURE__ */new Date:new Date(e),n=/YYYY|YY|MM|M|DD|D|HH|H|hh|h|mm|m|ss|s|SSS|A|a|\[([^\]]*)]/g,r=(r,s="YYYY-MM-DD HH:mm:ss")=>{const a=t(r);if(Number.isNaN(a.getTime()))return"Invalid Date";const o=a.getHours(),i=o%12||12,c={YYYY:String(a.getFullYear()),YY:e(a.getFullYear()%100),MM:e(a.getMonth()+1),M:String(a.getMonth()+1),DD:e(a.getDate()),D:String(a.getDate()),HH:e(o),H:String(o),hh:e(i),h:String(i),mm:e(a.getMinutes()),m:String(a.getMinutes()),ss:e(a.getSeconds()),s:String(a.getSeconds()),SSS:e(a.getMilliseconds(),3),A:o<12?"AM":"PM",a:o<12?"am":"pm"};return s.replace(n,(e,t)=>void 0!==t?t:c[e])};function s(e){const t=e?new Date(e):/* @__PURE__ */new Date;return t.format=(e="YYYY-MM-DD HH:mm:ss")=>r(t,e),t}var a=t=>{if(!Number.isFinite(t))return"";const n=Math.max(0,Math.trunc(t)),r=Math.trunc(n/3600),s=Math.trunc(n%3600/60),a=e(n%60);return 0===r?`${e(s)}:${a}`:`${e(r)}:${e(s)}:${a}`},o=e=>a(e),i=/(?:(\d{2,}):)?(\d{2}):(\d{2})\.(\d{3})/,c=e=>{const t=e.trim().match(i);if(!t)return;const[,n,r,s,a]=t;return(n?3600*Number(n):0)+60*Number(r)+Number(s)+Number(a)/1e3},u=e=>{const[t,n]=e.split("--\x3e");if(!t||!n)return;const r=c(t),s=c(n.trim().split(/\s+/)[0]??"");return void 0!==r&&void 0!==s?{start:r,end:s}:void 0},l=[["year",315576e5],["month",26298e5],["week",6048e5],["day",864e5],["hour",36e5],["minute",6e4],["second",1e3]],d={year:"y",quarter:"q",month:"mo",week:"w",day:"d",hour:"h",minute:"m",second:"s"},f=/* @__PURE__ */new Map,h=(e,n={})=>{const{now:r,locale:s,style:a="long",numeric:o="auto"}=n,i=t(e).getTime(),c=t(r).getTime();if(Number.isNaN(i)||Number.isNaN(c))return"";const u=i-c,h=Math.abs(u);let g=l.findIndex(([,e])=>h>=e);-1===g&&(g=l.length-1);const m=u<0?-1:1;let[p,w]=l[g],y=m*Math.round(h/w);if(g>0&&Math.abs(y)*w>=l[g-1][1]&&([p,w]=l[g-1],y=m*Math.round(h/w)),"compact"===a)return`${Math.abs(y)}${d[p]??""}`;const _=((e,t,n)=>{if("undefined"==typeof Intl||"function"!=typeof Intl.RelativeTimeFormat)return;const r=`${String(e)}|${t}|${n}`;let s=f.get(r);return s||(s=new Intl.RelativeTimeFormat(e,{style:t,numeric:n}),f.set(r,s)),s})(s,a,o);if(!_){const e=d[p]??"";return y<0?`${Math.abs(y)}${e} ago`:`in ${y}${e}`}return _.format(y,p)},g=()=>{if("undefined"!=typeof document)return performance.now();if("undefined"!=typeof process){const[e,t]=process.hrtime();return 1e3*e+t/1e6}return Date.now()},m=e=>{const t=document.cookie.split("; ");for(let n=0;n<t.length;n++){const r=t[n].split("=");if(r[0]===e)return decodeURIComponent(r[1])}return""},p=(e,t)=>new Promise(function(n,r){const s=new XMLHttpRequest;s.open(t.method||"GET",e,!0),s.responseType=t.responseType||"arraybuffer",s.onload=function(){200===s.status?n({success:!0,data:s.response,message:""}):r({success:!1,data:s.status,message:`The request status is${s.status}`})},s.onerror=function(e){r({success:!1,data:e,message:""})},s.onprogress=e=>{t.onProgress&&t.onProgress(e)},s.withCredentials=t.withCredentials||!1,t.headers&&Object.keys(t.headers).forEach(function(e){t.headers?.[e]&&s.setRequestHeader(e,t.headers[e])}),s.send(t.body)}),w=e=>{const t=e.backingStorePixelRatio||e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||1;return(("undefined"==typeof window?1:window.devicePixelRatio)||1)/t},y=async e=>{if("string"==typeof e)return e;if(e instanceof Blob)return URL.createObjectURL(e);if(e instanceof ArrayBuffer)return URL.createObjectURL(new Blob([e]));if(e instanceof Response){const t=await e.blob();return URL.createObjectURL(t)}return e},_=(e=10)=>{const t=[];let n,r=0;return new Promise(s=>{const a=()=>{const o=g(),i=o-r;0!==r&&t.push(i),r=o,t.length>e&&(s(1/(t.reduce((e,t)=>e+t)/e)),cancelAnimationFrame(n)),n=requestAnimationFrame(a)};t.length<=e&&(n=requestAnimationFrame(a))})},b=e=>{const t={},n=(e=>{const t=e??("undefined"==typeof window?"":window.location.href),n=t.indexOf("?");if(-1===n)return"";const r=t.slice(n+1),s=r.indexOf("#");return-1===s?r:r.slice(0,s)})(e);if(!n)return t;for(const r of n.split("&")){if(!r)continue;const e=r.indexOf("="),n=-1===e?r:r.slice(0,e),s=-1===e?"":r.slice(e+1);if(n)try{t[decodeURIComponent(n.replace(/\+/g," "))]=decodeURIComponent(s.replace(/\+/g," "))}catch{t[n]=s}}return t},v=(e,t)=>{const n=b(t)[e];if(void 0===n)return!1;const r=n.toLowerCase();return""===r||"1"===r||"true"===r},M=()=>{if("undefined"==typeof window)return!1;try{return window.parent!==window}catch{return!0}};function S(e,t={}){let n=e;0===n.indexOf("//")&&(n=n.replace("//","https://"));const r=new URL(n);return t&&Object.keys(t).forEach(e=>{t[e]&&r.searchParams.set(e,t[e])}),r.href}function x(e){if("undefined"!=typeof window){const t=new RegExp(`(^| )${e}(?:=([^;]*))?(;|$)`).exec(document.cookie);if(t&&t[2])return t[2]}return""}var D=()=>"undefined"!=typeof window?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},k=()=>{if("undefined"!=typeof window)return window.navigator.connection},$=/(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x7E]|%(?:[^\da-f]|[\da-f][^\da-f]|$))+/gi,R=/(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g;function F(e){return String(e).replace(R,"$1�$2").replace($,encodeURI)}var Y=e=>new Promise((t,n)=>{const r=new Image,s=/* @__PURE__ */(new Date).getTime();r.src=e||`https://github.com/favicon.ico?d=${s}`,r.onload=()=>{t(/* @__PURE__ */(new Date).getTime()-s)},r.onerror=e=>{n(e)}}),N=(e,...t)=>n=>new Promise((r,s)=>{setTimeout(async()=>{try{r(await e(...t))}catch(n){s(n)}},n)}),O=async e=>{const{url:t,duration:n=3e3,count:r=5}=e;let s=0,a=0;const o=[];for(let i=0;i<r;i++){const e=await N(Y,t)(n);o.push(e)}return s=Math.max(...o)-Math.min(...o),a=o.reduce((e,t)=>e+t)/o.length,{ping:a,jitter:s}},L=()=>{if("undefined"!=typeof navigator)return navigator.vendor&&navigator.vendor.indexOf("Apple")>-1&&navigator.userAgent&&!navigator.userAgent.includes("CriOS")&&!navigator.userAgent.includes("FxiOS")},I=()=>{try{return"undefined"==typeof localStorage?null:localStorage}catch{return null}},P=(e,t)=>{try{I()?.setItem(e,t)}catch{}},C=e=>{try{return I()?.getItem(e)??""}catch{return""}},H=e=>{try{I()?.removeItem(e)}catch{}},A=(e="")=>{const t=t=>`${e}${t}`;return{keyOf:t,get:(e,n)=>{const r=C(t(e));if(!r)return n;try{return JSON.parse(r)}catch{return n}},set:(e,n)=>{let r;try{r=JSON.stringify(n)}catch{return!1}return P(t(e),r),C(t(e))===r},remove:e=>H(t(e))}},T=(e,t=2e4)=>{const n=e.slice(0,t);let r=0,s=0;for(const a of n){const e=a.codePointAt(0)??0;e>=19968&&e<=40959||e>=13312&&e<=19903?r++:(e>=65&&e<=90||e>=97&&e<=122)&&s++}return 0===r&&0===s?"other":r>=s?"zh":s>3*r?"en":"zh"},B=()=>{if("undefined"==typeof navigator)return"other";const e=(navigator.language||"").toLowerCase();return e.startsWith("zh")?"zh":e.startsWith("en")?"en":"other"},U=e=>{const{supported:t,query:n,cookie:r,storageKey:s,useNavigator:a=!0,url:o}=e,i=e.fallback??t[0]??"en";if(0===t.length)return i;const c=t.map(e=>e.toLowerCase()),u=e=>{if(!e)return;const n=e.trim().toLowerCase();if(!n)return;const r=c.indexOf(n);if(-1!==r)return t[r];const s=n.split("-")[0],a=c.findIndex(e=>e===s||e.split("-")[0]===s);return-1===a?void 0:t[a]},l=[];if(n&&l.push(b(o)[n]),r&&l.push(x(r)),s&&l.push(C(s)),a&&"undefined"!=typeof navigator){const{languages:e,language:t}=navigator;l.push(...e??[],t)}for(const d of l){const e=u(d);if(e)return e}return i},j=Object.freeze({}),q=class{_locale;_fallback;_messages;_persist;_storageKey;_handlers=/* @__PURE__ */new Set;constructor(e={}){this._messages={...e.messages},this._fallback=e.fallbackLocale??"en",this._persist=e.persist??!1,this._storageKey=e.storageKey??"ran-locale",this._locale=this._resolveInitialLocale(e)}_resolveInitialLocale(e){const t=Object.keys(this._messages),n=this._persist&&C(this._storageKey)||null;if(n&&(this._messages[n]||0===t.length))return n;if(e.locale)return e.locale;if(e.detectNavigator){const e=U({supported:t,useNavigator:!0,fallback:""});if(e)return e}return this._fallback}get locale(){return this._locale}getLocale(){return this._locale}setLocale(e){e!==this._locale&&(this._locale=e,this._persist&&P(this._storageKey,e),this._notify())}addMessages(e,t){this._messages[e]={...this._messages[e],...t}}getMessages(e=this._locale){return this._messages[e]??{}}get availableLocales(){return Object.keys(this._messages)}t(e,t){const n=this._messages[this._locale]?.[e]??this._messages[this._fallback]?.[e]??e;return this._interpolate(n,t)}_interpolate(e,t){const n=t??j;return e.replace(/\{\{|\}\}|\{(\w+)\}/g,(e,t)=>"{{"===e?"{":"}}"===e?"}":null!=n[t]?String(n[t]):e)}onChange(e){return this._handlers.add(e),()=>{this._handlers.delete(e)}}_notify(){for(const e of this._handlers)e(this._locale)}destroy(){this._handlers.clear()}},z=null;function E(e={}){const t=new q(e);return z=t,t}function K(){return z}export{h as A,M as C,p as D,v as E,s as F,c as M,g as N,r as O,o as P,Y as S,O as T,m as _,B as a,w as b,C as c,S as d,k as f,b as g,F as h,T as i,u as j,a as k,H as l,N as m,E as n,U as o,y as p,K as r,A as s,q as t,P as u,x as v,L as w,D as x,_ as y};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as s}from"./enums-BAgbyGdH.js";import{$ as a,A as t,B as n,C as o,D as r,E as m,F as i,G as p,H as f,I as j,J as c,K as l,L as u,M as
|
|
1
|
+
import{i as s}from"./enums-BAgbyGdH.js";import{$ as a,A as t,B as n,C as o,D as r,E as m,F as i,G as p,H as f,I as j,J as c,K as l,L as u,M as d,N as h,O as x,P as b,Q as e,R as g,S as k,T as v,U as w,V as y,W as A,X as C,Y as D,Z as E,_ as F,a as M,at as N,b as O,c as P,ct as S,d as T,dt as _,et as z,f as B,g as H,h as I,i as L,it as R,j as U,k as V,l as q,lt as G,m as J,n as K,nt as Q,o as W,ot as X,p as Y,q as Z,r as $,rt as ss,s as as,st as ts,t as ns,tt as os,u as rs,ut as ms,v as is,w as ps,x as fs,y as js,z as cs}from"./color-B_KMM8UX.js";import{$ as ls,$t as us,A as ds,An as hs,At as xs,B as bs,Bn as es,Bt as gs,C as ks,Cn as vs,Ct as ws,D as ys,Dn as As,Dt as Cs,E as Ds,En as Es,Et as Fs,F as Ms,Fn as Ns,Ft as Os,G as Ps,Gt as Ss,H as Ts,Hn as _s,Ht as zs,I as Bs,In as Hs,It as Is,J as Ls,Jt as Rs,K as Us,Kt as Vs,L as qs,Ln as Gs,Lt as Js,M as Ks,Mn as Qs,Mt as Ws,N as Xs,Nn as Ys,Nt as Zs,O as $s,On as sa,Ot as aa,P as ta,Pn as na,Pt as oa,Q as ra,Qt as ma,R as ia,Rn as pa,Rt as fa,S as ja,Sn as ca,St as la,T as ua,Tn as da,Tt as ha,U as xa,Un as ba,Ut as ea,V as ga,Vn as ka,Vt as va,W as wa,Wt as ya,X as Aa,Xt as Ca,Y as Da,Yt as Ea,Z as Fa,Zt as Ma,_ as Na,_n as Oa,_t as Pa,a as Sa,an as Ta,at as _a,b as za,bn as Ba,bt as Ha,c as Ia,cn as La,ct as Ra,d as Ua,dn as Va,dt as qa,en as Ga,et as Ja,f as Ka,fn as Qa,ft as Wa,g as Xa,gn as Ya,gt as Za,h as $a,hn as st,ht as at,i as tt,in as nt,it as ot,j as rt,jn as mt,jt as it,k as pt,kn as ft,kt as jt,l as ct,ln as lt,lt as ut,m as dt,mn as ht,mt as xt,n as bt,nn as et,nt as gt,o as kt,on as vt,ot as wt,p as yt,pn as At,pt as Ct,q as Dt,qt as Et,r as Ft,rn as Mt,rt as Nt,s as Ot,sn as Pt,st as St,t as Tt,tn as _t,tt as zt,u as Bt,un as Ht,ut as It,v as Lt,vn as Rt,vt as Ut,w as Vt,wn as qt,wt as Gt,x as Jt,xn as Kt,xt as Qt,y as Wt,yn as Xt,yt as Yt,z as Zt,zn as $t,zt as sn}from"./utils-BNwhohXq.js";import{A as an,C as tn,D as nn,E as on,F as rn,M as mn,N as pn,O as fn,P as jn,S as cn,T as ln,_ as un,a as dn,b as hn,c as xn,d as bn,f as en,g as gn,h as kn,i as vn,j as wn,k as yn,l as An,m as Cn,n as Dn,o as En,p as Fn,r as Mn,s as Nn,t as On,u as Pn,v as Sn,w as Tn,x as _n,y as zn}from"./i18n-BJIS1fR1.js";import{n as Bn,t as Hn}from"./chain-CTywmh_H.js";export{Wa as ADOPTED_SHEET_MARKER,Ct as ADOPTED_STYLE_MARKER,Mt as AudioRecorder,Ya as BRIDGE_MARKER,Oa as BridgeManager,Hn as Chain,Rt as Client,ns as Color,K as ColorScheme,Xt as DEFAULT_CHANNEL,Os as EventManager,$ as FMT,L as HEX_COLOR_REGEX,M as Hsl,W as Hsla,On as I18nCore,ya as MOBILE_MEDIA_QUERY,sa as Mathjs,l as MessageCodec,f as MimeType,kt as Monitor,Ba as Platform,Kt as PostMessageBridge,Ft as QuestQueue,as as RGBA_REGEX,P as RGB_REGEX,q as Rgb,rs as Rgba,s as SyncHook,Ga as TOTP,Vt as TimeoutError,ia as UNAMBIGUOUS_ALPHABET,It as WebDB,Bs as WorkerClient,$a as ZIP_DEFLATE,Xa as ZIP_STORED,ca as acceptPortBridge,fa as addClassToElement,ft as addNumSym,xt as adoptSheetText,at as adoptStyles,bn as appendUrl,Z as arrayBufferToString,sn as autosizeTextarea,Ts as base64ToBytes,xa as base64UrlToBytes,T as blendMultiply,B as blendOverlay,Y as blendScreen,vs as bridgeManager,J as brightnessContrast,St as buildOffsets,wa as bytesToBase64,Ps as bytesToBase64Url,c as checkEncoding,aa as circ,hs as clamp,D as clearBr,C as clearStr,nt as cloneDeep,I as componentToHex,us as compose,ot as computePlacement,Us as concatBytes,en as connection,Za as convertImageToBase64,H as cosinePalette,Na as crc32,Bn as create,Bt as createData,gs as createDocumentFragment,Is as createDoubleTapDetector,qa as createHandoff,Dn as createI18n,_a as createLocalePath,Fn as createObjectURL,qt as createPortBridge,ua as createRaceGuard,_t as createSignal,Es as createSpeechRecognizer,Nn as createStore,Lt as createZip,E as csvEscape,jt as cubic,Ss as currentDevice,Pa as cutRound,Ma as debounce,Dt as decodeTextBytes,Ds as deferred,ys as delay,vn as detectLanguage,Cn as durationHandler,kn as encodeUrl,va as escapeHtml,xs as expo,la as fanShapedByArc,e as fenceCode,Ls as fetchMaybeGzip,Ta as filterObj,mt as fit,fn as formatDate,yn as formatDuration,vt as formatJson,an as formatRelative,gn as getAllQueryString,ws as getAngle,Gt as getArcPointerByDeg,un as getCookie,Sn as getCookieByName,w as getExtensions,zn as getFrame,Ut as getImage,ha as getLinearGradient,a as getMatchingSentences,Yt as getMatrix,A as getMime,dt as getPerformance,hn as getPixelRatio,z as getRandomString,Ua as getReportUrl,tt as getStatus,Fs as getTangentByPointer,_n as getWindow,Da as gunzipMaybe,ma as handleConsole,Js as handleError,Ia as handleFetchHook,ct as handleXhrHook,F as hexToAlpha,is as hexToHsb,js as hexToHsv,O as hexToRgb,fs as hsbToHsl,k as hsbToRgb,o as hslToHsb,ps as hslToHsv,v as hslToRgb,m as hsvToHsl,r as hsvToRgb,x as hue2rgb,cn as imageRequest,Ra as indexForOffset,Wt as inflateRaw,Qs as inverseLerp,Vs as isClient,Pt as isEqual,Aa as isGzip,Fa as isHtmlDocument,Ha as isImageSize,tn as isInIframe,Et as isMobile,Tn as isSafari,As as isSpeechRecognitionSupported,os as isString,ds as isUrlCached,Rs as isWeiXin,ra as isZipContainer,Ys as lerp,V as linearToSrgb,na as linearstep,Tt as loadScript,xn as localStorageGetItem,An as localStorageRemoveItem,Pn as localStorageSetItem,t as luma,Ea as matchMediaQuery,Ns as mathjs,Q as md5,At as memoize,La as merge,lt as mergeExports,dn as navigatorLanguage,rt as networkAllowsDownload,ln as networkSpeed,Qa as noop,ht as once,Qt as opacity,da as openPortBridge,wt as paginateText,Hs as parseChineseNumber,Gs as parseEnglishNumber,pa as parseRomanNumber,wn as parseVttCueTiming,mn as parseVttTimestamp,$t as perToNum,pn as performanceTime,Ks as prefetchUrl,Xs as prefetchUrls,ta as prefetchWhenIdle,it as quad,Ws as quart,on as queryFlag,Ht as querystring,Zs as quint,U as randomColor,ss as randomString,es as range,Ja as readFileAsArrayBuffer,zt as readFileAsDataURL,gt as readFileAsText,Nt as readFileAsUint8Array,za as readZipEntries,Jt as readZipEntry,ka as remap,zs as removeClassToElement,Va as replaceOld,Ka as report,nn as requestUrlToBuffer,En as resolveLocale,ja as rewriteZip,d as rgbToHex,h as rgbToHsb,b as rgbToHsl,i as rgbToHsv,j as rgbaString,u as rgbaToHex,g as rgbaToRgb,Cs as roundRectByArc,Zt as safeEqual,cs as saturation,ls as saveFileToDisk,bt as scriptOnLoad,bs as secureRandomString,ga as secureToken,ut as segmentByRanges,qs as serveWorker,ea as setFontSize2html,p as setMime,yt as setReportUrl,oa as sine,st as singleFlight,R as slugify,_s as smoothstep,n as srgbToLinear,Sa as status,N as strParse,et as subscribers,Ot as throttle,jn as timeFormat,rn as timestampToTime,X as toFullWidth,ts as toHalfWidth,S as toString,ba as transformNumber,G as transformText,ms as truncate,_ as truncateWithMarker,Mn as useI18n,y as vibrance,Ca as watchMediaQuery,Ms as whenIdle,$s as withTimeout,pt as withTimeoutFallback,ks as zipHasEntry};
|
package/dist/src/node/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{G as e,W as t,nt as n,r}from"../../color-DPV7TsVU.js";import{Socket as o}from"node:net";import s from"node:http";import i from"node:os";import a,{createReadStream as c,createWriteStream as d,readdir as l,readdirSync as u,stat as f,statSync as h}from"node:fs";import p from"node:tty";import m,{hrtime as w}from"node:process";import g from"node:child_process";import y from"node:readline";import b from"node:https";import E,{join as v,resolve as x}from"node:path";import{promisify as T}from"node:util";import{Buffer as S}from"node:buffer";import O from"node:crypto";function P(){const e=i.networkInterfaces();for(const t in e){const n=e[t];if(n)for(let e=0;e<n.length;e++){const t=n[e];if("IPv4"===t.family&&"127.0.0.1"!==t.address&&!t.internal)return t.address}}}var q=class{middleware;ctx;constructor(){const e=new s.IncomingMessage(new o),t=new s.ServerResponse(e);this.ctx={ipv4:P,req:e,res:t},this.middleware=[]}use(e){if(!e)throw new Error("the use function has an incorrect argument");this.middleware.push(e)}listen(...e){const t=function(e){if(!Array.isArray(e))throw new TypeError("Middleware stack must be an array!");for(const t of e)if("function"!=typeof t)throw new TypeError("Middleware must be composed of functions!");return function(t,n){let r=-1;function o(s){if(s<=r)return Promise.reject(/* @__PURE__ */new Error("next() called multiple times"));r=s;let i=e[s];if(s===e.length&&n&&(i=n),!i)return Promise.resolve();try{return Promise.resolve(i(t,o.bind(null,s+1)))}catch(a){return Promise.reject(a)}}return o(0)}}(this.middleware);return s.createServer((e,n)=>{this.ctx.req=e,this.ctx.res=n,t(this.ctx).catch(C)}).listen(...e)}};function C(e){console.error(e.stack||e.toString())}var H=a,M=(e,t="utf-8")=>{const n=new AbortController,r=n.signal,o=new Promise((o,s)=>{H.readFile(e,{encoding:t,signal:r},(e,t)=>{e?(n.abort(),s({success:!1,_identification:!1,data:e})):o({success:!0,_identification:!0,data:t})})});return o.abort=n.abort,o},_=(e,t)=>new Promise((n,r)=>{H.appendFile(e,t,t=>{t?r({success:!1,_identification:!1,data:t}):M(e).then(e=>{n(e)})})}),F=m?.env&&!("NO_COLOR"in m.env||m.argv.includes("--no-color"))&&("FORCE_COLOR"in m.env||m.argv.includes("--color")||"win32"===m.platform||p.isatty(1)&&"dumb"!==m.env.TERM||"CI"in m.env),U=(e,t,n=e)=>r=>{const o=""+r,s=o.indexOf(t,e.length);return~s?e+j(o,t,n,s)+t:e+o+t},j=(e,t,n,r)=>{const o=e.substring(0,r)+n,s=e.substring(r+t.length),i=s.indexOf(t);return~i?o+j(s,t,n,i):o+s},k=Object.assign({},((e=F)=>{const t={};return Object.keys(r).forEach(n=>t[n]=e?U(r[n][0],r[n][1]):String),t})(),((e=F)=>({isColorSupported:e,reset:e?e=>`${r.reset[0]}${e}${r.reset[1]}`:String,bold:e?U(r.bold[0],r.bold[1],`${r.bold[1]}${r.bold[0]}`):String,dim:e?U(r.dim[0],r.dim[1],`${r.dim[1]}${r.dim[0]}`):String}))()),$=(e={})=>{const{uploadDir:t=".",encoding:r="",json:o=!0}=e;return(e,s)=>{const{req:i,res:c}=e,{url:d,method:l}=i,[u="",f=""]=d?.split("?")||[],h=f?new URLSearchParams(f):{};e.request||(e.request={}),e.request.method=l,e.request.path=u,e.request.url=d,e.request.query=h;const p=i.headers["content-type"];if("application/json"===p){r?i.setEncoding(r):i.setEncoding("utf-8");let t="";i.on("data",e=>{t+=e}),i.on("end",()=>{c.setHeader("content-type","application/json;charset=UTF-8");try{e.request.body=o?JSON.parse(t):t}catch{e.request.body=t}s()})}if(p?.includes("multipart/form-data;")){const[e,o]=i.headers["content-type"]?.split(";").map(e=>e.trim())||[],[d,l]=o.split("=");r?i.setEncoding(r):i.setEncoding("binary");let u="";i.on("data",e=>{u+=e}),i.on("end",()=>{const e={};u.split("\r\n").slice(0,4).forEach(t=>{Object.assign(e,n(t,";",/=|:/))});const r=e["Content-Type"],o=Buffer.from(e.filename,"latin1").toString("utf8"),i=u.indexOf(r)+r.length,d=u.substring(i).replace(/^\s+/,""),f=d.substring(0,d.indexOf(`--${l}--`));a.writeFile(`${t}/${o}`,f,{encoding:"binary"},e=>{if(e)throw e;c.setHeader("content-type","application/json;charset=UTF-8"),s()})})}}},I=(e,t)=>new Promise((n,r)=>{const o=g.spawn(e,t,{stdio:"inherit",shell:!1});o.on("error",e=>r(e)),o.on("exit",e=>0===e?n():r(/* @__PURE__ */new Error(`Command exited with code ${e}`)))}),A=({message:e,stream:t=process.stderr,defaultResponse:n="Y"})=>{const r=y.createInterface({input:process.stdin,output:t});return new Promise(t=>{r.question(`${e} `,e=>{r.close();const o=(e||n).toLowerCase();t("y"===o||"yes"===o)})})},B=()=>{};function D(e,t,n){return t(e.req,e.res,B),n()}function L(e,t,n){return new Promise((r,o)=>{t(e.req,e.res,e=>{e?o(e):r(n())})})}function R(e){const t=e.length<3?D:L;return function(n,r){return t(n,e,r)}}var N=e=>new Promise((t,n)=>{H.stat(e,(e,r)=>{e?n({success:!1,_identification:!1,data:e}):t({success:!0,_identification:!0,data:r})})}),K=({url:e})=>new Promise((t,n)=>{b.get(e,e=>{const n=[];e.on("data",e=>{n.push(e)}),e.on("end",()=>{const{data:e=[]}=JSON.parse(Buffer.concat(n).toString());e.forEach(e=>{}),t({success:!0,data:e,message:"request success"})})}).on("error",e=>{e.message,n({success:!1,data:e,message:e.message})})}),W=()=>{const e=i.networkInterfaces();for(const t in e){const n=e[t];for(let e=0;e<n.length;e++){const t=n[e];if("IPv4"===t.family&&"127.0.0.1"!==t.address&&!t.internal)return t.address}}};function z(e){const t=e.url;if(void 0===t)return;let n=e._parsedUrl;if(n&&n._raw===t)return n;n={},n.query=n.search=void 0,n.href=n.path=n.pathname=t;const r=t.indexOf("?",1);return-1!==r&&(n.search=t.substring(r),n.query=n.search.substring(1),n.pathname=t.substring(0,r)),n._raw=t,e._parsedUrl=n}var G=e=>{const{dirPath:t}=e;try{return H.readdirSync(t)}catch(n){throw n}},J=class{ctx;map;methods;paths;constructor(){this.map=/* @__PURE__ */new Map,this.methods=/* @__PURE__ */new Set,this.paths=/* @__PURE__ */new Set}get(e,t){this.addHandlerToMap("GET")(e,t)}post(e,t){this.addHandlerToMap("POST")(e,t)}put(e,t){this.addHandlerToMap("PUT")(e,t)}patch(e,t){this.addHandlerToMap("PATCH")(e,t)}del(e,t){this.addHandlerToMap("DELETE")(e,t)}head(e,t){this.addHandlerToMap("HEAD")(e,t)}options(e,t){this.addHandlerToMap("OPTIONS")(e,t)}addHandlerToMap(e){return this.methods.add(e),(t,n)=>{this.paths.add(t);let r=this.map.get(e);r||(r=/* @__PURE__ */new Map,this.map.set(e,r)),r.set(t,n)}}routes(){return(e,t)=>{this.ctx=e;const{path:n,method:r}=e.request,o=this.map.get(r),s=o?o.get(n):t;s&&s(e,t)}}allowedMethods(){return e=>{const{res:t}=e,{path:n,method:r}=e.request;!this.methods.has(r)&&this.paths.has(n)&&(t.statusCode=405,t.end("405, method is not allowed")),this.methods.has(r)&&!this.paths.has(n)&&(t.statusCode=404,t.end("404, the request address does not exist")),this.methods.has(r)||this.paths.has(n)||(t.statusCode=501,t.end("501, not support the functionality needed to satisfy the request"))}}},Y=(n={})=>{const{pathname:r,fileTypes:o={}}=n;return async(n,s)=>{try{const{req:i,res:c}=n;if(i.url){const n="text/html",s=r||process.cwd(),d=E.normalize(E.resolve(s)),l=E.extname(i.url).slice(1);Object.keys(o).forEach(t=>e(t,o[t]));const u=l?t(l):n;if(!Boolean(u))return c.writeHead(404,{"Content-Type":"text/html"}),void c.end("404: File not found");let f=i.url;if("/"===i.url)f="index.html";else if(!l)try{a.accessSync(E.join(d,i.url+".html"),a.constants.F_OK),f=i.url+".html"}catch{f=E.join(i.url,"index.html")}const h=E.join(d,f);if(!E.normalize(E.resolve(h)).startsWith(d))return c.writeHead(404,{"Content-Type":"text/html"}),void c.end("404: File not found");a.readFile(h,(e,t)=>{e?(c.writeHead(404,{"Content-Type":"text/html"}),c.end("404: File not found")):(c.writeHead(200,{"Content-Type":u}),c.end(t))})}await s()}catch{}}},Q=()=>{if("undefined"!=typeof window){const e=window.performance.now();return Symbol.for(`${e}`)}if("undefined"!=typeof process){const e=w.bigint();return Symbol.for(`${e}`)}return Symbol.for(`${Date.now()}`)},V=e=>{const{path:t}=e;if(t)return c(t);throw new Error("path is not defined")},X=e=>{const{path:t}=e;if(t)return d(t);throw new Error("path is not defined")},Z=e=>{const t=Symbol.keyFor(e);return"undefined"!=typeof window&&t?window.performance.now()-Number(t):"undefined"!=typeof process&&t?w.bigint()-BigInt(t):Date.now()-Number(t)},ee=T(f),te=T(l);async function ne(e,t,n=""){e=x(".",e);const r=await te(e);await Promise.all(r.map(async r=>{const o=v(e,r),s=await ee(o);return s.isDirectory()?ne(o,t,v(n,r)):t(v(n,r),o,s)}))}function re(e,t,n=""){e=x(".",e);const r=u(e);let o,s,i=0;for(;i<r.length;i++)o=v(e,r[i]),s=h(o),s.isDirectory()?re(o,t,v(n,r[i])):t(v(n,r[i]),o,s)}var oe=(e,t=20)=>new Promise(n=>{H.watchFile(e,{interval:t},(t,r)=>{t.mtime!==r.mtime?(H.unwatchFile(e),n({success:!0,_identification:!0,data:{},message:"file is changed"})):n({success:!1,_identification:!1,data:{},message:"file is not changed"})})});function se(e,t){const n=S.byteLength(e);let r=null;if(n>65535?(r=S.alloc(10+n),r[1]=127,r.writeUInt32BE(n,6),r.write(e,10)):n>125?(r=S.alloc(4+n),r[1]=126,r.writeUInt16BE(n,2),r.write(e,4)):(r=S.alloc(2+n),r[1]=n,r.write(e,2)),t){const e=t.opcode;e&&e<15&&e>=0&&(r[0]=128|e)}else r[0]=129;return r}function ie(e,t){if(!t)return e;const n=S.from(e);for(let r=0;r<n.length;++r)n[r]=n[r]^t[r%4];return n}function ae(){const e={};this.on=(t,n)=>{e[t]?e[t].push(n):e[t]=[n]},this.off=(t,n)=>{const r=e[t],o=r.indexOf(n);r&&-1!==o&&r.splice(o,1)},this.emit=(t,n)=>{e[t]&&e[t].forEach(e=>e(n))}}function ce(e){ae.call(this);const t=[];this.server=e,this.clients=t,this.broadcast=e=>{t.forEach(t=>{t.send(e)})},e.on("upgrade",(e,n)=>{n.write(["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade","Sec-WebSocket-Accept: "+O.createHash("sha1").update(e.headers["sec-websocket-key"]+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64")].join("\n")+"\n\n");const r={send(e,t){n.write(se(e,t))},ping(){n.write(se("",{opcode:9}))},pong(){n.write(se("",{opcode:10}))},close(){if(-1===t.indexOf(r))return!1;t.splice(t.indexOf(r),1),n.write(se("",{opcode:8})),r.emit("close"),n.destroy()},socket:n};ae.call(r),this.emit("connect",r),t.push(r);let o=S.allocUnsafe(0),s=S.allocUnsafe(0);const i=[];let a=!0;function c(){const e=function(e){const t=S.from(e),n=127&t[1];let r=0,o=0;const s=t[1]>=128;return 127===n?(r=t.readUInt32BE(6),o=10):126===n?(r=t.readUInt16BE(2),o=4):(r=n,o=2),{fin:t[0]>=128,opcode:15&t[0],mask:s,maskKey:s?t.subarray(o,o+(s?4:0)):null,len7:n,len:r,lenMeta:o+(s?4:0)}}(o);i.push({l:e.lenMeta,f:()=>{a=!1,i.push({l:e.len,f:t=>{if(s=S.concat([s,ie(t,e.maskKey)]),a=!0,e.fin){if(8===e.opcode)return r.close();if(9===e.opcode)return r.pong();r.emit("message",s),s=S.allocUnsafe(0)}}})}})}n.on("data",e=>{for(o=S.concat([o,e]),a&&c();i[0]&&o.byteLength>=i[0].l;){const e=i[0].l;i[0].f(o.subarray(0,e)),o=o.subarray(e),i.splice(0,1)}}),n.on("end",()=>{r.close()}),n.on("error",e=>{r.emit("error",e),r.close()})})}var de=(e,t)=>new Promise((n,r)=>{H.writeFile(e,t,{mode:438,flag:"w+",encoding:"utf-8"},o=>{if(o)throw r({success:!1,_identification:!1,data:o}),o;n({success:!0,_identification:!1,data:{path:e,content:t}})})});export{J as Router,q as Server,ce as WSS,_ as appendFile,$ as body,k as colors,R as connect,K as get,W as getIPAdress,F as isColorSupported,z as paresUrl,A as prompt,N as queryFileInfo,G as readDir,M as readFile,V as readStream,I as runCommand,Q as startTask,Y as staticMiddleware,Z as taskEnd,ne as traverse,re as traverseSync,oe as watchFile,de as writeFile,X as writeStream};
|
|
1
|
+
import{G as e,W as t,at as n,r}from"../../color-B_KMM8UX.js";import{Socket as o}from"node:net";import s from"node:http";import i from"node:os";import a,{createReadStream as c,createWriteStream as d,readdir as l,readdirSync as u,stat as f,statSync as h}from"node:fs";import p from"node:tty";import m,{hrtime as w}from"node:process";import g from"node:child_process";import y from"node:readline";import b from"node:https";import E,{join as v,resolve as x}from"node:path";import{promisify as T}from"node:util";import{Buffer as S}from"node:buffer";import O from"node:crypto";function P(){const e=i.networkInterfaces();for(const t in e){const n=e[t];if(n)for(let e=0;e<n.length;e++){const t=n[e];if("IPv4"===t.family&&"127.0.0.1"!==t.address&&!t.internal)return t.address}}}var q=class{middleware;ctx;constructor(){const e=new s.IncomingMessage(new o),t=new s.ServerResponse(e);this.ctx={ipv4:P,req:e,res:t},this.middleware=[]}use(e){if(!e)throw new Error("the use function has an incorrect argument");this.middleware.push(e)}listen(...e){const t=function(e){if(!Array.isArray(e))throw new TypeError("Middleware stack must be an array!");for(const t of e)if("function"!=typeof t)throw new TypeError("Middleware must be composed of functions!");return function(t,n){let r=-1;function o(s){if(s<=r)return Promise.reject(/* @__PURE__ */new Error("next() called multiple times"));r=s;let i=e[s];if(s===e.length&&n&&(i=n),!i)return Promise.resolve();try{return Promise.resolve(i(t,o.bind(null,s+1)))}catch(a){return Promise.reject(a)}}return o(0)}}(this.middleware);return s.createServer((e,n)=>{this.ctx.req=e,this.ctx.res=n,t(this.ctx).catch(C)}).listen(...e)}};function C(e){console.error(e.stack||e.toString())}var H=a,M=(e,t="utf-8")=>{const n=new AbortController,r=n.signal,o=new Promise((o,s)=>{H.readFile(e,{encoding:t,signal:r},(e,t)=>{e?(n.abort(),s({success:!1,_identification:!1,data:e})):o({success:!0,_identification:!0,data:t})})});return o.abort=n.abort,o},_=(e,t)=>new Promise((n,r)=>{H.appendFile(e,t,t=>{t?r({success:!1,_identification:!1,data:t}):M(e).then(e=>{n(e)})})}),F=m?.env&&!("NO_COLOR"in m.env||m.argv.includes("--no-color"))&&("FORCE_COLOR"in m.env||m.argv.includes("--color")||"win32"===m.platform||p.isatty(1)&&"dumb"!==m.env.TERM||"CI"in m.env),U=(e,t,n=e)=>r=>{const o=""+r,s=o.indexOf(t,e.length);return~s?e+j(o,t,n,s)+t:e+o+t},j=(e,t,n,r)=>{const o=e.substring(0,r)+n,s=e.substring(r+t.length),i=s.indexOf(t);return~i?o+j(s,t,n,i):o+s},k=Object.assign({},((e=F)=>{const t={};return Object.keys(r).forEach(n=>t[n]=e?U(r[n][0],r[n][1]):String),t})(),((e=F)=>({isColorSupported:e,reset:e?e=>`${r.reset[0]}${e}${r.reset[1]}`:String,bold:e?U(r.bold[0],r.bold[1],`${r.bold[1]}${r.bold[0]}`):String,dim:e?U(r.dim[0],r.dim[1],`${r.dim[1]}${r.dim[0]}`):String}))()),$=(e={})=>{const{uploadDir:t=".",encoding:r="",json:o=!0}=e;return(e,s)=>{const{req:i,res:c}=e,{url:d,method:l}=i,[u="",f=""]=d?.split("?")||[],h=f?new URLSearchParams(f):{};e.request||(e.request={}),e.request.method=l,e.request.path=u,e.request.url=d,e.request.query=h;const p=i.headers["content-type"];if("application/json"===p){r?i.setEncoding(r):i.setEncoding("utf-8");let t="";i.on("data",e=>{t+=e}),i.on("end",()=>{c.setHeader("content-type","application/json;charset=UTF-8");try{e.request.body=o?JSON.parse(t):t}catch{e.request.body=t}s()})}if(p?.includes("multipart/form-data;")){const[e,o]=i.headers["content-type"]?.split(";").map(e=>e.trim())||[],[d,l]=o.split("=");r?i.setEncoding(r):i.setEncoding("binary");let u="";i.on("data",e=>{u+=e}),i.on("end",()=>{const e={};u.split("\r\n").slice(0,4).forEach(t=>{Object.assign(e,n(t,";",/=|:/))});const r=e["Content-Type"],o=Buffer.from(e.filename,"latin1").toString("utf8"),i=u.indexOf(r)+r.length,d=u.substring(i).replace(/^\s+/,""),f=d.substring(0,d.indexOf(`--${l}--`));a.writeFile(`${t}/${o}`,f,{encoding:"binary"},e=>{if(e)throw e;c.setHeader("content-type","application/json;charset=UTF-8"),s()})})}}},I=(e,t)=>new Promise((n,r)=>{const o=g.spawn(e,t,{stdio:"inherit",shell:!1});o.on("error",e=>r(e)),o.on("exit",e=>0===e?n():r(/* @__PURE__ */new Error(`Command exited with code ${e}`)))}),A=({message:e,stream:t=process.stderr,defaultResponse:n="Y"})=>{const r=y.createInterface({input:process.stdin,output:t});return new Promise(t=>{r.question(`${e} `,e=>{r.close();const o=(e||n).toLowerCase();t("y"===o||"yes"===o)})})},B=()=>{};function D(e,t,n){return t(e.req,e.res,B),n()}function L(e,t,n){return new Promise((r,o)=>{t(e.req,e.res,e=>{e?o(e):r(n())})})}function R(e){const t=e.length<3?D:L;return function(n,r){return t(n,e,r)}}var N=e=>new Promise((t,n)=>{H.stat(e,(e,r)=>{e?n({success:!1,_identification:!1,data:e}):t({success:!0,_identification:!0,data:r})})}),K=({url:e})=>new Promise((t,n)=>{b.get(e,e=>{const n=[];e.on("data",e=>{n.push(e)}),e.on("end",()=>{const{data:e=[]}=JSON.parse(Buffer.concat(n).toString());e.forEach(e=>{}),t({success:!0,data:e,message:"request success"})})}).on("error",e=>{e.message,n({success:!1,data:e,message:e.message})})}),W=()=>{const e=i.networkInterfaces();for(const t in e){const n=e[t];for(let e=0;e<n.length;e++){const t=n[e];if("IPv4"===t.family&&"127.0.0.1"!==t.address&&!t.internal)return t.address}}};function z(e){const t=e.url;if(void 0===t)return;let n=e._parsedUrl;if(n&&n._raw===t)return n;n={},n.query=n.search=void 0,n.href=n.path=n.pathname=t;const r=t.indexOf("?",1);return-1!==r&&(n.search=t.substring(r),n.query=n.search.substring(1),n.pathname=t.substring(0,r)),n._raw=t,e._parsedUrl=n}var G=e=>{const{dirPath:t}=e;try{return H.readdirSync(t)}catch(n){throw n}},J=class{ctx;map;methods;paths;constructor(){this.map=/* @__PURE__ */new Map,this.methods=/* @__PURE__ */new Set,this.paths=/* @__PURE__ */new Set}get(e,t){this.addHandlerToMap("GET")(e,t)}post(e,t){this.addHandlerToMap("POST")(e,t)}put(e,t){this.addHandlerToMap("PUT")(e,t)}patch(e,t){this.addHandlerToMap("PATCH")(e,t)}del(e,t){this.addHandlerToMap("DELETE")(e,t)}head(e,t){this.addHandlerToMap("HEAD")(e,t)}options(e,t){this.addHandlerToMap("OPTIONS")(e,t)}addHandlerToMap(e){return this.methods.add(e),(t,n)=>{this.paths.add(t);let r=this.map.get(e);r||(r=/* @__PURE__ */new Map,this.map.set(e,r)),r.set(t,n)}}routes(){return(e,t)=>{this.ctx=e;const{path:n,method:r}=e.request,o=this.map.get(r),s=o?o.get(n):t;s&&s(e,t)}}allowedMethods(){return e=>{const{res:t}=e,{path:n,method:r}=e.request;!this.methods.has(r)&&this.paths.has(n)&&(t.statusCode=405,t.end("405, method is not allowed")),this.methods.has(r)&&!this.paths.has(n)&&(t.statusCode=404,t.end("404, the request address does not exist")),this.methods.has(r)||this.paths.has(n)||(t.statusCode=501,t.end("501, not support the functionality needed to satisfy the request"))}}},Y=(n={})=>{const{pathname:r,fileTypes:o={}}=n;return async(n,s)=>{try{const{req:i,res:c}=n;if(i.url){const n="text/html",s=r||process.cwd(),d=E.normalize(E.resolve(s)),l=E.extname(i.url).slice(1);Object.keys(o).forEach(t=>e(t,o[t]));const u=l?t(l):n;if(!Boolean(u))return c.writeHead(404,{"Content-Type":"text/html"}),void c.end("404: File not found");let f=i.url;if("/"===i.url)f="index.html";else if(!l)try{a.accessSync(E.join(d,i.url+".html"),a.constants.F_OK),f=i.url+".html"}catch{f=E.join(i.url,"index.html")}const h=E.join(d,f);if(!E.normalize(E.resolve(h)).startsWith(d))return c.writeHead(404,{"Content-Type":"text/html"}),void c.end("404: File not found");a.readFile(h,(e,t)=>{e?(c.writeHead(404,{"Content-Type":"text/html"}),c.end("404: File not found")):(c.writeHead(200,{"Content-Type":u}),c.end(t))})}await s()}catch{}}},Q=()=>{if("undefined"!=typeof window){const e=window.performance.now();return Symbol.for(`${e}`)}if("undefined"!=typeof process){const e=w.bigint();return Symbol.for(`${e}`)}return Symbol.for(`${Date.now()}`)},V=e=>{const{path:t}=e;if(t)return c(t);throw new Error("path is not defined")},X=e=>{const{path:t}=e;if(t)return d(t);throw new Error("path is not defined")},Z=e=>{const t=Symbol.keyFor(e);return"undefined"!=typeof window&&t?window.performance.now()-Number(t):"undefined"!=typeof process&&t?w.bigint()-BigInt(t):Date.now()-Number(t)},ee=T(f),te=T(l);async function ne(e,t,n=""){e=x(".",e);const r=await te(e);await Promise.all(r.map(async r=>{const o=v(e,r),s=await ee(o);return s.isDirectory()?ne(o,t,v(n,r)):t(v(n,r),o,s)}))}function re(e,t,n=""){e=x(".",e);const r=u(e);let o,s,i=0;for(;i<r.length;i++)o=v(e,r[i]),s=h(o),s.isDirectory()?re(o,t,v(n,r[i])):t(v(n,r[i]),o,s)}var oe=(e,t=20)=>new Promise(n=>{H.watchFile(e,{interval:t},(t,r)=>{t.mtime!==r.mtime?(H.unwatchFile(e),n({success:!0,_identification:!0,data:{},message:"file is changed"})):n({success:!1,_identification:!1,data:{},message:"file is not changed"})})});function se(e,t){const n=S.byteLength(e);let r=null;if(n>65535?(r=S.alloc(10+n),r[1]=127,r.writeUInt32BE(n,6),r.write(e,10)):n>125?(r=S.alloc(4+n),r[1]=126,r.writeUInt16BE(n,2),r.write(e,4)):(r=S.alloc(2+n),r[1]=n,r.write(e,2)),t){const e=t.opcode;e&&e<15&&e>=0&&(r[0]=128|e)}else r[0]=129;return r}function ie(e,t){if(!t)return e;const n=S.from(e);for(let r=0;r<n.length;++r)n[r]=n[r]^t[r%4];return n}function ae(){const e={};this.on=(t,n)=>{e[t]?e[t].push(n):e[t]=[n]},this.off=(t,n)=>{const r=e[t],o=r.indexOf(n);r&&-1!==o&&r.splice(o,1)},this.emit=(t,n)=>{e[t]&&e[t].forEach(e=>e(n))}}function ce(e){ae.call(this);const t=[];this.server=e,this.clients=t,this.broadcast=e=>{t.forEach(t=>{t.send(e)})},e.on("upgrade",(e,n)=>{n.write(["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade","Sec-WebSocket-Accept: "+O.createHash("sha1").update(e.headers["sec-websocket-key"]+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64")].join("\n")+"\n\n");const r={send(e,t){n.write(se(e,t))},ping(){n.write(se("",{opcode:9}))},pong(){n.write(se("",{opcode:10}))},close(){if(-1===t.indexOf(r))return!1;t.splice(t.indexOf(r),1),n.write(se("",{opcode:8})),r.emit("close"),n.destroy()},socket:n};ae.call(r),this.emit("connect",r),t.push(r);let o=S.allocUnsafe(0),s=S.allocUnsafe(0);const i=[];let a=!0;function c(){const e=function(e){const t=S.from(e),n=127&t[1];let r=0,o=0;const s=t[1]>=128;return 127===n?(r=t.readUInt32BE(6),o=10):126===n?(r=t.readUInt16BE(2),o=4):(r=n,o=2),{fin:t[0]>=128,opcode:15&t[0],mask:s,maskKey:s?t.subarray(o,o+(s?4:0)):null,len7:n,len:r,lenMeta:o+(s?4:0)}}(o);i.push({l:e.lenMeta,f:()=>{a=!1,i.push({l:e.len,f:t=>{if(s=S.concat([s,ie(t,e.maskKey)]),a=!0,e.fin){if(8===e.opcode)return r.close();if(9===e.opcode)return r.pong();r.emit("message",s),s=S.allocUnsafe(0)}}})}})}n.on("data",e=>{for(o=S.concat([o,e]),a&&c();i[0]&&o.byteLength>=i[0].l;){const e=i[0].l;i[0].f(o.subarray(0,e)),o=o.subarray(e),i.splice(0,1)}}),n.on("end",()=>{r.close()}),n.on("error",e=>{r.emit("error",e),r.close()})})}var de=(e,t)=>new Promise((n,r)=>{H.writeFile(e,t,{mode:438,flag:"w+",encoding:"utf-8"},o=>{if(o)throw r({success:!1,_identification:!1,data:o}),o;n({success:!0,_identification:!1,data:{path:e,content:t}})})});export{J as Router,q as Server,ce as WSS,_ as appendFile,$ as body,k as colors,R as connect,K as get,W as getIPAdress,F as isColorSupported,z as paresUrl,A as prompt,N as queryFileInfo,G as readDir,M as readFile,V as readStream,I as runCommand,Q as startTask,Y as staticMiddleware,Z as taskEnd,ne as traverse,re as traverseSync,oe as watchFile,de as writeFile,X as writeStream};
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Binary payload helpers: base64 without the call-stack trap, gzip that may or
|
|
3
|
+
* may not already be decoded, byte-signature sniffing, text decoding with an
|
|
4
|
+
* encoding fallback chain, and "save these bytes to disk".
|
|
5
|
+
*
|
|
6
|
+
* All of these were written (several times each) inside apps that move file
|
|
7
|
+
* bytes around — an Office editor, a converter, a downloader — before landing
|
|
8
|
+
* here.
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* @description: Encode bytes as base64 without blowing the call stack.
|
|
12
|
+
*
|
|
13
|
+
* `String.fromCharCode.apply(null, bytes)` is the usual one-liner and it throws
|
|
14
|
+
* `RangeError: Maximum call stack size exceeded` somewhere around a hundred
|
|
15
|
+
* thousand bytes — a limit real files pass routinely, so the naive version
|
|
16
|
+
* works in every test and fails on the first user document. Chunked here.
|
|
17
|
+
*
|
|
18
|
+
* @param {Uint8Array | ArrayBuffer} data
|
|
19
|
+
* @return {string} base64 (no data: prefix, no line breaks)
|
|
20
|
+
*/
|
|
21
|
+
export declare const bytesToBase64: (data: Uint8Array | ArrayBuffer) => string;
|
|
22
|
+
/**
|
|
23
|
+
* @description: Decode base64 into bytes. Accepts a bare payload or a full
|
|
24
|
+
* `data:` URL (the prefix is stripped), which is what `readFileAsDataURL` and
|
|
25
|
+
* canvas `toDataURL` hand you.
|
|
26
|
+
*
|
|
27
|
+
* @param {string} base64
|
|
28
|
+
* @return {Uint8Array}
|
|
29
|
+
*/
|
|
30
|
+
export declare const base64ToBytes: (base64: string) => Uint8Array<ArrayBuffer>;
|
|
31
|
+
/**
|
|
32
|
+
* @description: Encode bytes as base64url — the URL- and filename-safe alphabet from RFC 4648
|
|
33
|
+
* §5, with `+/` swapped for `-_` and the `=` padding dropped.
|
|
34
|
+
*
|
|
35
|
+
* This is the spelling JWTs, WebAuthn payloads, OAuth device codes and anything that rides in
|
|
36
|
+
* a query string or a path segment use. Plain base64 breaks in all of those: `+` becomes a
|
|
37
|
+
* space when a form-encoded value is parsed, and `/` splits a path.
|
|
38
|
+
*
|
|
39
|
+
* @param {Uint8Array | ArrayBuffer} data
|
|
40
|
+
* @return {string}
|
|
41
|
+
*/
|
|
42
|
+
export declare const bytesToBase64Url: (data: Uint8Array | ArrayBuffer) => string;
|
|
43
|
+
/**
|
|
44
|
+
* @description: Decode base64url back into bytes, restoring the padding the encoder dropped.
|
|
45
|
+
* Returns `null` on anything that is not valid base64url, because the usual caller is
|
|
46
|
+
* checking a token someone else supplied and a throw there is just a crash with extra steps.
|
|
47
|
+
*
|
|
48
|
+
* @param {string} value
|
|
49
|
+
* @return {Uint8Array | null}
|
|
50
|
+
*/
|
|
51
|
+
export declare const base64UrlToBytes: (value: string) => Uint8Array | null;
|
|
52
|
+
/**
|
|
53
|
+
* @description: Join byte chunks into one buffer, in order.
|
|
54
|
+
*
|
|
55
|
+
* The reason this exists as its own function: text that arrives in chunks must be joined
|
|
56
|
+
* *before* it is decoded, never after. A multi-byte UTF-8 character straddling a chunk
|
|
57
|
+
* boundary decodes to replacement characters when each chunk is decoded on its own, and the
|
|
58
|
+
* damage is invisible until someone reads a log with a Chinese name in it.
|
|
59
|
+
*
|
|
60
|
+
* @param {Uint8Array[]} chunks
|
|
61
|
+
* @return {Uint8Array}
|
|
62
|
+
*/
|
|
63
|
+
export declare const concatBytes: (chunks: readonly Uint8Array[]) => Uint8Array;
|
|
64
|
+
/** @description: Whether the bytes start with the gzip magic number (1f 8b). */
|
|
65
|
+
export declare const isGzip: (bytes: Uint8Array) => boolean;
|
|
66
|
+
/**
|
|
67
|
+
* @description: Whether the bytes are a ZIP container (PK\x03\x04) — which is
|
|
68
|
+
* also every OOXML file (docx / xlsx / pptx), ODF file, epub and jar.
|
|
69
|
+
*/
|
|
70
|
+
export declare const isZipContainer: (bytes: Uint8Array) => boolean;
|
|
71
|
+
/**
|
|
72
|
+
* @description: Whether the bytes are an HTML document rather than the binary
|
|
73
|
+
* format their extension claims.
|
|
74
|
+
*
|
|
75
|
+
* Web systems love exporting an HTML `<table>` under a `.xls` name; spreadsheet
|
|
76
|
+
* apps accept it, parsers that trust the extension do not. A leading BOM and
|
|
77
|
+
* whitespace are skipped, and a ZIP container short-circuits to `false` so a
|
|
78
|
+
* real .xlsx is never sniffed as HTML.
|
|
79
|
+
*/
|
|
80
|
+
export declare const isHtmlDocument: (bytes: Uint8Array) => boolean;
|
|
81
|
+
/**
|
|
82
|
+
* @description: Decompress bytes if — and only if — they are still gzipped.
|
|
83
|
+
*
|
|
84
|
+
* A server that sends `Content-Encoding: gzip` has the browser decode the body
|
|
85
|
+
* before you ever see it, while a `.gz` file served as `application/gzip`
|
|
86
|
+
* arrives compressed. The same fetch therefore yields either shape depending on
|
|
87
|
+
* the host, so the magic number decides instead of the URL.
|
|
88
|
+
*
|
|
89
|
+
* @param {Uint8Array} bytes
|
|
90
|
+
* @return {Promise<Uint8Array>} the original bytes when they are not gzipped
|
|
91
|
+
*/
|
|
92
|
+
export declare const gunzipMaybe: (bytes: Uint8Array) => Promise<Uint8Array>;
|
|
93
|
+
/**
|
|
94
|
+
* @description: Fetch a resource that may be delivered gzipped or already
|
|
95
|
+
* decoded (see `gunzipMaybe`), e.g. a large `.wasm.gz` asset on a static host.
|
|
96
|
+
*
|
|
97
|
+
* @param {RequestInfo | URL} input
|
|
98
|
+
* @param {RequestInit} init
|
|
99
|
+
* @return {Promise<Uint8Array>}
|
|
100
|
+
*/
|
|
101
|
+
export declare const fetchMaybeGzip: (input: RequestInfo | URL, init?: RequestInit) => Promise<Uint8Array>;
|
|
102
|
+
/**
|
|
103
|
+
* @description: Decode text bytes, trying encodings in order until one holds.
|
|
104
|
+
*
|
|
105
|
+
* A non-fatal `TextDecoder` never throws — invalid sequences silently become
|
|
106
|
+
* U+FFFD — so a legacy-encoded file decodes "successfully" into mojibake. Strict
|
|
107
|
+
* decoding is the only way to tell, so each candidate is tried with
|
|
108
|
+
* `fatal: true` and the last one is the fallback that cannot fail. The default
|
|
109
|
+
* chain covers a UTF-8 BOM, real UTF-8, Chinese "ANSI" exports (GB18030 is a
|
|
110
|
+
* superset of GBK) and finally latin1.
|
|
111
|
+
*
|
|
112
|
+
* Pair with `checkEncoding` when you would rather detect statistically than
|
|
113
|
+
* fall through a fixed list.
|
|
114
|
+
*
|
|
115
|
+
* @param {Uint8Array} bytes
|
|
116
|
+
* @param {string[]} encodings candidates, most specific first
|
|
117
|
+
* @return {string}
|
|
118
|
+
*/
|
|
119
|
+
export declare const decodeTextBytes: (bytes: Uint8Array, encodings?: string[]) => string;
|
|
120
|
+
interface SaveFileOptions {
|
|
121
|
+
/** MIME type for the picker's file-type entry and the Blob. */
|
|
122
|
+
mimeType?: string;
|
|
123
|
+
/** Human-readable type description shown by the save dialog. */
|
|
124
|
+
description?: string;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* @description: Save bytes to disk: a real "Save as" dialog through the File
|
|
128
|
+
* System Access API where it exists, an anchor download everywhere else.
|
|
129
|
+
*
|
|
130
|
+
* Resolves `true` when the file was written, `false` when the user dismissed
|
|
131
|
+
* the picker — a cancel is not an error, and callers that treat it as one end
|
|
132
|
+
* up showing a failure toast for a deliberate action. Anything else rejects.
|
|
133
|
+
*
|
|
134
|
+
* @param {Blob | Uint8Array} data
|
|
135
|
+
* @param {string} fileName
|
|
136
|
+
* @param {SaveFileOptions} options
|
|
137
|
+
* @return {Promise<boolean>} whether the file was written
|
|
138
|
+
*/
|
|
139
|
+
export declare const saveFileToDisk: (data: Blob | Uint8Array, fileName: string, options?: SaveFileOptions) => Promise<boolean>;
|
|
140
|
+
export {};
|
|
@@ -11,6 +11,14 @@ export declare enum DEVICE {
|
|
|
11
11
|
}
|
|
12
12
|
export type CurrentDevice = 'ipad' | 'android' | 'iphone' | 'pc';
|
|
13
13
|
export declare const currentDevice: () => CurrentDevice;
|
|
14
|
+
/**
|
|
15
|
+
* @description: Whether a `window` existed **when this module was first imported**.
|
|
16
|
+
*
|
|
17
|
+
* @deprecated Evaluated once at module load, so it is stuck at `false` for the life of the
|
|
18
|
+
* process in any SSR-then-hydrate flow, and cannot be stubbed in a test. New code checks
|
|
19
|
+
* `typeof window === 'undefined'` inside the function that needs it. Kept exported so
|
|
20
|
+
* existing callers keep compiling.
|
|
21
|
+
*/
|
|
14
22
|
export declare const isClient: boolean;
|
|
15
23
|
/** Viewport breakpoint, matching where the mobile layout takes over */
|
|
16
24
|
export declare const MOBILE_MEDIA_QUERY = "(max-width: 768px)";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as r,r as s,t as a}from"../../../i18n-
|
|
1
|
+
import{n as r,r as s,t as a}from"../../../i18n-BJIS1fR1.js";export{a as I18nCore,r as createI18n,s as useI18n};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { SyncHook } from './subscribe';
|
|
2
2
|
import { Mathjs, addNumSym, clamp, fit, inverseLerp, lerp, linearstep, mathjs, parseChineseNumber, parseEnglishNumber, parseRomanNumber, perToNum, range, remap, smoothstep, transformNumber } from './number';
|
|
3
|
-
import { MessageCodec, arrayBufferToString, checkEncoding, clearBr, clearStr, getMatchingSentences, getRandomString, isString, md5, randomString, strParse, toFullWidth, toHalfWidth, toString, transformText, truncate } from './str';
|
|
3
|
+
import { MessageCodec, arrayBufferToString, checkEncoding, clearBr, clearStr, getMatchingSentences, getRandomString, isString, md5, randomString, strParse, toFullWidth, toHalfWidth, toString, transformText, truncate, truncateWithMarker, fenceCode, slugify, csvEscape } from './str';
|
|
4
4
|
import type { TransformText, TruncateOptions, TruncatePosition } from './str';
|
|
5
5
|
import { createSpeechRecognizer, isSpeechRecognitionSupported } from './speech';
|
|
6
6
|
import type { SpeechError, SpeechErrorKind, SpeechRecognizer, SpeechRecognizerOptions } from './speech';
|
|
@@ -45,6 +45,8 @@ import { computePlacement } from './placement';
|
|
|
45
45
|
import type { ComputePlacementOptions, ComputedPlacement, Placement, PlacementRect } from './placement';
|
|
46
46
|
import type { ResolveLocaleOptions, TextLanguage } from './lang';
|
|
47
47
|
import { readFileAsArrayBuffer, readFileAsDataURL, readFileAsText, readFileAsUint8Array } from './file';
|
|
48
|
+
import { base64ToBytes, bytesToBase64, decodeTextBytes, fetchMaybeGzip, gunzipMaybe, isGzip, isHtmlDocument, isZipContainer, saveFileToDisk, bytesToBase64Url, base64UrlToBytes, concatBytes } from './binary';
|
|
49
|
+
import { UNAMBIGUOUS_ALPHABET, safeEqual, secureRandomString, secureToken } from './secure';
|
|
48
50
|
import { WorkerClient, serveWorker } from './worker';
|
|
49
51
|
import type { ServeWorkerOptions, WorkerClientOptions, WorkerHandlerContext, WorkerRequestBase, WorkerResponseBase } from './worker';
|
|
50
52
|
import { isUrlCached, networkAllowsDownload, prefetchUrl, prefetchUrls, prefetchWhenIdle, whenIdle } from './prefetch';
|
|
@@ -71,5 +73,5 @@ import type { CurrentDevice } from './device';
|
|
|
71
73
|
import { MOBILE_MEDIA_QUERY, currentDevice, isClient, isMobile, isWeiXin, matchMediaQuery, watchMediaQuery } from './device';
|
|
72
74
|
import { Color, ColorScheme, FMT, HEX_COLOR_REGEX, Hsl, Hsla, RGBA_REGEX, RGB_REGEX, Rgb, Rgba, blendMultiply, blendOverlay, blendScreen, brightnessContrast, componentToHex, cosinePalette, hexToAlpha, hexToHsb, hexToHsv, hexToRgb, hsbToHsl, hsbToRgb, hslToHsb, hslToHsv, hslToRgb, hsvToHsl, hsvToRgb, hue2rgb, linearToSrgb, luma, randomColor, rgbToHex, rgbToHsb, rgbToHsl, rgbToHsv, rgbaString, rgbaToHex, rgbaToRgb, saturation, srgbToLinear, vibrance } from '@/utils/color';
|
|
73
75
|
import type { RGB } from '@/utils/color';
|
|
74
|
-
export { performanceTime, timeFormat, timestampToTime, throttle, SyncHook, clearBr, clearStr, isString, randomString, strParse, scriptOnLoad, handleFetchHook, createData, report, QuestQueue, noop, getPerformance, querystring, formatJson, filterObj, merge, replaceOld, mergeExports, perToNum, range, clamp, lerp, inverseLerp, remap, fit, linearstep, smoothstep, Mathjs, mathjs, getStatus, status, Monitor, MimeType, getExtensions, setMime, getMime, memoize, once, isImageSize, convertImageToBase64, handleError, addClassToElement, removeClassToElement, createDocumentFragment, escapeHtml, isClient, isWeiXin, isMobile, debounce, currentDevice, handleConsole, compose, Color, FMT, Hsl, Hsla, Rgb, Rgba, randomColor, hexToRgb, componentToHex, rgbToHex, rgbToHsl, hue2rgb, hslToRgb, rgbToHsb, hsbToRgb, hsvToRgb, hsvToHsl, ColorScheme, AudioRecorder, getCookie, requestUrlToBuffer, getPixelRatio, createObjectURL, getFrame, getAllQueryString, queryFlag, isInIframe, appendUrl, getCookieByName, getWindow, connection, encodeUrl, imageRequest, durationHandler, networkSpeed, TOTP, localStorageGetItem, localStorageSetItem, localStorageRemoveItem, createStore, setFontSize2html, autosizeTextarea, createSpeechRecognizer, isSpeechRecognitionSupported, Chain, create, isEqual, cloneDeep, createSignal, subscribers, getMatchingSentences, transformNumber, toString, addNumSym, checkEncoding, transformText, isSafari, md5, getRandomString, bridgeManager, Client, BridgeManager, PostMessageBridge, MessageCodec, Platform, openPortBridge, acceptPortBridge, createPortBridge, BRIDGE_MARKER, DEFAULT_CHANNEL, singleFlight, WebDB, createHandoff, buildOffsets, paginateText, indexForOffset, segmentByRanges, detectLanguage, navigatorLanguage, resolveLocale, readFileAsArrayBuffer, readFileAsUint8Array, readFileAsText, readFileAsDataURL, WorkerClient, serveWorker, whenIdle, networkAllowsDownload, isUrlCached, prefetchUrl, prefetchUrls, prefetchWhenIdle, deferred, withTimeout, withTimeoutFallback, delay, TimeoutError, createRaceGuard, crc32, inflateRaw, readZipEntries, readZipEntry, zipHasEntry, rewriteZip, createZip, ZIP_STORED, ZIP_DEFLATE, arrayBufferToString, toHalfWidth, toFullWidth, truncate, parseChineseNumber, parseRomanNumber, parseEnglishNumber, MOBILE_MEDIA_QUERY, matchMediaQuery, watchMediaQuery, createLocalePath, setReportUrl, getReportUrl, formatDate, formatDuration, formatRelative, parseVttCueTiming, parseVttTimestamp, handleXhrHook, EventManager, createDoubleTapDetector, quad, cubic, quart, quint, sine, expo, circ, getImage, cutRound, opacity, getMatrix, getAngle, getArcPointerByDeg, getTangentByPointer, fanShapedByArc, roundRectByArc, getLinearGradient, adoptStyles, adoptSheetText, ADOPTED_STYLE_MARKER, ADOPTED_SHEET_MARKER, rgbToHsv, hexToHsb, hexToHsv, hsbToHsl, hslToHsb, hslToHsv, hexToAlpha, rgbaString, rgbaToRgb, rgbaToHex, srgbToLinear, linearToSrgb, luma, blendScreen, blendMultiply, blendOverlay, brightnessContrast, saturation, vibrance, cosinePalette, HEX_COLOR_REGEX, RGB_REGEX, RGBA_REGEX, loadScript, I18nCore, createI18n, useI18n, computePlacement, };
|
|
76
|
+
export { performanceTime, timeFormat, timestampToTime, throttle, SyncHook, clearBr, clearStr, isString, randomString, strParse, scriptOnLoad, handleFetchHook, createData, report, QuestQueue, noop, getPerformance, querystring, formatJson, filterObj, merge, replaceOld, mergeExports, perToNum, range, clamp, lerp, inverseLerp, remap, fit, linearstep, smoothstep, Mathjs, mathjs, getStatus, status, Monitor, MimeType, getExtensions, setMime, getMime, memoize, once, isImageSize, convertImageToBase64, handleError, addClassToElement, removeClassToElement, createDocumentFragment, escapeHtml, isClient, isWeiXin, isMobile, debounce, currentDevice, handleConsole, compose, Color, FMT, Hsl, Hsla, Rgb, Rgba, randomColor, hexToRgb, componentToHex, rgbToHex, rgbToHsl, hue2rgb, hslToRgb, rgbToHsb, hsbToRgb, hsvToRgb, hsvToHsl, ColorScheme, AudioRecorder, getCookie, requestUrlToBuffer, getPixelRatio, createObjectURL, getFrame, getAllQueryString, queryFlag, isInIframe, appendUrl, getCookieByName, getWindow, connection, encodeUrl, imageRequest, durationHandler, networkSpeed, TOTP, localStorageGetItem, localStorageSetItem, localStorageRemoveItem, createStore, setFontSize2html, autosizeTextarea, createSpeechRecognizer, isSpeechRecognitionSupported, Chain, create, isEqual, cloneDeep, createSignal, subscribers, getMatchingSentences, transformNumber, toString, addNumSym, checkEncoding, transformText, isSafari, md5, getRandomString, bridgeManager, Client, BridgeManager, PostMessageBridge, MessageCodec, Platform, openPortBridge, acceptPortBridge, createPortBridge, BRIDGE_MARKER, DEFAULT_CHANNEL, singleFlight, WebDB, createHandoff, buildOffsets, paginateText, indexForOffset, segmentByRanges, detectLanguage, navigatorLanguage, resolveLocale, readFileAsArrayBuffer, readFileAsUint8Array, base64ToBytes, bytesToBase64, decodeTextBytes, fetchMaybeGzip, gunzipMaybe, isGzip, isHtmlDocument, isZipContainer, saveFileToDisk, readFileAsText, readFileAsDataURL, WorkerClient, serveWorker, whenIdle, networkAllowsDownload, isUrlCached, prefetchUrl, prefetchUrls, prefetchWhenIdle, deferred, withTimeout, withTimeoutFallback, delay, TimeoutError, createRaceGuard, crc32, inflateRaw, readZipEntries, readZipEntry, zipHasEntry, rewriteZip, createZip, ZIP_STORED, ZIP_DEFLATE, arrayBufferToString, toHalfWidth, toFullWidth, truncate, parseChineseNumber, parseRomanNumber, parseEnglishNumber, MOBILE_MEDIA_QUERY, matchMediaQuery, watchMediaQuery, createLocalePath, setReportUrl, getReportUrl, formatDate, formatDuration, formatRelative, parseVttCueTiming, parseVttTimestamp, handleXhrHook, EventManager, createDoubleTapDetector, quad, cubic, quart, quint, sine, expo, circ, getImage, cutRound, opacity, getMatrix, getAngle, getArcPointerByDeg, getTangentByPointer, fanShapedByArc, roundRectByArc, getLinearGradient, adoptStyles, adoptSheetText, ADOPTED_STYLE_MARKER, ADOPTED_SHEET_MARKER, rgbToHsv, hexToHsb, hexToHsv, hsbToHsl, hslToHsb, hslToHsv, hexToAlpha, rgbaString, rgbaToRgb, rgbaToHex, srgbToLinear, linearToSrgb, luma, blendScreen, blendMultiply, blendOverlay, brightnessContrast, saturation, vibrance, cosinePalette, HEX_COLOR_REGEX, RGB_REGEX, RGBA_REGEX, loadScript, I18nCore, createI18n, useI18n, computePlacement, safeEqual, secureRandomString, secureToken, UNAMBIGUOUS_ALPHABET, bytesToBase64Url, base64UrlToBytes, concatBytes, truncateWithMarker, fenceCode, slugify, csvEscape, };
|
|
75
77
|
export type { RGB, DateInput, FormatRelativeOptions, RelativeStyle, TruncateOptions, TruncatePosition, SpeechError, SpeechErrorKind, SpeechRecognizer, SpeechRecognizerOptions, EasingFn, SpeedType, ImgSource, LoadScriptOptions, I18nConfig, MessageDict, StringValues, LocaleMessages, TranslateParams, LocaleChangeHandler, Debounced, Throttled, BeaconPayload, ReportConfig, LocalePath, LocalePathConfig, LocaleRoute, SingleFlight, IDBCollection, IDBResult, IDBStoreSchema, WebDBOptions, Handoff, HandoffOptions, JsonStore, Deferred, RaceGuard, DoubleTapDetector, DoubleTapDetectorOptions, ZipEntry, RewriteZipOptions, ResolveLocaleOptions, OffsetRange, PaginateOptions, PaginateResult, TextBox, TextGridMetrics, TextPage, Segment, TextLanguage, ServeWorkerOptions, WorkerClientOptions, WorkerHandlerContext, WorkerRequestBase, WorkerResponseBase, WhenIdleOptions, NetworkAllowanceOptions, PrefetchOptions, CurrentDevice, TransformText, MessageHandler, MessageData, PendingRequest, BridgeManagerOptions, BroadcastPayload, CallToPayload, PortBridge, OpenPortBridgeOptions, AcceptPortBridgeOptions, ComputePlacementOptions, ComputedPlacement, Placement, PlacementRect, };
|
package/dist/src/utils/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as s}from"../../enums-BAgbyGdH.js";import{$ as a,A as t,B as n,C as o,D as r,E as m,F as i,G as p,H as f,I as j,J as c,K as l,L as u,M as
|
|
1
|
+
import{i as s}from"../../enums-BAgbyGdH.js";import{$ as a,A as t,B as n,C as o,D as r,E as m,F as i,G as p,H as f,I as j,J as c,K as l,L as u,M as d,N as h,O as x,P as b,Q as e,R as g,S as k,T as v,U as w,V as y,W as A,X as C,Y as D,Z as E,_ as F,a as M,at as N,b as O,c as P,ct as S,d as T,dt as _,et as z,f as B,g as H,h as I,i as L,it as R,j as U,k as V,l as q,lt as G,m as J,n as K,nt as Q,o as W,ot as X,p as Y,q as Z,r as $,rt as ss,s as as,st as ts,t as ns,tt as os,u as rs,ut as ms,v as is,w as ps,x as fs,y as js,z as cs}from"../../color-B_KMM8UX.js";import{$ as ls,$t as us,A as ds,An as hs,At as xs,B as bs,Bn as es,Bt as gs,C as ks,Cn as vs,Ct as ws,D as ys,Dn as As,Dt as Cs,E as Ds,En as Es,Et as Fs,F as Ms,Fn as Ns,Ft as Os,G as Ps,Gt as Ss,H as Ts,Hn as _s,Ht as zs,I as Bs,In as Hs,It as Is,J as Ls,Jt as Rs,K as Us,Kt as Vs,L as qs,Ln as Gs,Lt as Js,M as Ks,Mn as Qs,Mt as Ws,N as Xs,Nn as Ys,Nt as Zs,O as $s,On as sa,Ot as aa,P as ta,Pn as na,Pt as oa,Q as ra,Qt as ma,R as ia,Rn as pa,Rt as fa,S as ja,Sn as ca,St as la,T as ua,Tn as da,Tt as ha,U as xa,Un as ba,Ut as ea,V as ga,Vn as ka,Vt as va,W as wa,Wt as ya,X as Aa,Xt as Ca,Y as Da,Yt as Ea,Z as Fa,Zt as Ma,_ as Na,_n as Oa,_t as Pa,a as Sa,an as Ta,at as _a,b as za,bn as Ba,bt as Ha,c as Ia,cn as La,ct as Ra,d as Ua,dn as Va,dt as qa,en as Ga,et as Ja,f as Ka,fn as Qa,ft as Wa,g as Xa,gn as Ya,gt as Za,h as $a,hn as st,ht as at,i as tt,in as nt,it as ot,j as rt,jn as mt,jt as it,k as pt,kn as ft,kt as jt,l as ct,ln as lt,lt as ut,m as dt,mn as ht,mt as xt,n as bt,nn as et,nt as gt,o as kt,on as vt,ot as wt,p as yt,pn as At,pt as Ct,q as Dt,qt as Et,r as Ft,rn as Mt,rt as Nt,s as Ot,sn as Pt,st as St,t as Tt,tn as _t,tt as zt,u as Bt,un as Ht,ut as It,v as Lt,vn as Rt,vt as Ut,w as Vt,wn as qt,wt as Gt,x as Jt,xn as Kt,xt as Qt,y as Wt,yn as Xt,yt as Yt,z as Zt,zn as $t,zt as sn}from"../../utils-BNwhohXq.js";import{A as an,C as tn,D as nn,E as on,F as rn,M as mn,N as pn,O as fn,P as jn,S as cn,T as ln,_ as un,a as dn,b as hn,c as xn,d as bn,f as en,g as gn,h as kn,i as vn,j as wn,k as yn,l as An,m as Cn,n as Dn,o as En,p as Fn,r as Mn,s as Nn,t as On,u as Pn,v as Sn,w as Tn,x as _n,y as zn}from"../../i18n-BJIS1fR1.js";import{n as Bn,t as Hn}from"../../chain-CTywmh_H.js";export{Wa as ADOPTED_SHEET_MARKER,Ct as ADOPTED_STYLE_MARKER,Mt as AudioRecorder,Ya as BRIDGE_MARKER,Oa as BridgeManager,Hn as Chain,Rt as Client,ns as Color,K as ColorScheme,Xt as DEFAULT_CHANNEL,Os as EventManager,$ as FMT,L as HEX_COLOR_REGEX,M as Hsl,W as Hsla,On as I18nCore,ya as MOBILE_MEDIA_QUERY,sa as Mathjs,l as MessageCodec,f as MimeType,kt as Monitor,Ba as Platform,Kt as PostMessageBridge,Ft as QuestQueue,as as RGBA_REGEX,P as RGB_REGEX,q as Rgb,rs as Rgba,s as SyncHook,Ga as TOTP,Vt as TimeoutError,ia as UNAMBIGUOUS_ALPHABET,It as WebDB,Bs as WorkerClient,$a as ZIP_DEFLATE,Xa as ZIP_STORED,ca as acceptPortBridge,fa as addClassToElement,ft as addNumSym,xt as adoptSheetText,at as adoptStyles,bn as appendUrl,Z as arrayBufferToString,sn as autosizeTextarea,Ts as base64ToBytes,xa as base64UrlToBytes,T as blendMultiply,B as blendOverlay,Y as blendScreen,vs as bridgeManager,J as brightnessContrast,St as buildOffsets,wa as bytesToBase64,Ps as bytesToBase64Url,c as checkEncoding,aa as circ,hs as clamp,D as clearBr,C as clearStr,nt as cloneDeep,I as componentToHex,us as compose,ot as computePlacement,Us as concatBytes,en as connection,Za as convertImageToBase64,H as cosinePalette,Na as crc32,Bn as create,Bt as createData,gs as createDocumentFragment,Is as createDoubleTapDetector,qa as createHandoff,Dn as createI18n,_a as createLocalePath,Fn as createObjectURL,qt as createPortBridge,ua as createRaceGuard,_t as createSignal,Es as createSpeechRecognizer,Nn as createStore,Lt as createZip,E as csvEscape,jt as cubic,Ss as currentDevice,Pa as cutRound,Ma as debounce,Dt as decodeTextBytes,Ds as deferred,ys as delay,vn as detectLanguage,Cn as durationHandler,kn as encodeUrl,va as escapeHtml,xs as expo,la as fanShapedByArc,e as fenceCode,Ls as fetchMaybeGzip,Ta as filterObj,mt as fit,fn as formatDate,yn as formatDuration,vt as formatJson,an as formatRelative,gn as getAllQueryString,ws as getAngle,Gt as getArcPointerByDeg,un as getCookie,Sn as getCookieByName,w as getExtensions,zn as getFrame,Ut as getImage,ha as getLinearGradient,a as getMatchingSentences,Yt as getMatrix,A as getMime,dt as getPerformance,hn as getPixelRatio,z as getRandomString,Ua as getReportUrl,tt as getStatus,Fs as getTangentByPointer,_n as getWindow,Da as gunzipMaybe,ma as handleConsole,Js as handleError,Ia as handleFetchHook,ct as handleXhrHook,F as hexToAlpha,is as hexToHsb,js as hexToHsv,O as hexToRgb,fs as hsbToHsl,k as hsbToRgb,o as hslToHsb,ps as hslToHsv,v as hslToRgb,m as hsvToHsl,r as hsvToRgb,x as hue2rgb,cn as imageRequest,Ra as indexForOffset,Wt as inflateRaw,Qs as inverseLerp,Vs as isClient,Pt as isEqual,Aa as isGzip,Fa as isHtmlDocument,Ha as isImageSize,tn as isInIframe,Et as isMobile,Tn as isSafari,As as isSpeechRecognitionSupported,os as isString,ds as isUrlCached,Rs as isWeiXin,ra as isZipContainer,Ys as lerp,V as linearToSrgb,na as linearstep,Tt as loadScript,xn as localStorageGetItem,An as localStorageRemoveItem,Pn as localStorageSetItem,t as luma,Ea as matchMediaQuery,Ns as mathjs,Q as md5,At as memoize,La as merge,lt as mergeExports,dn as navigatorLanguage,rt as networkAllowsDownload,ln as networkSpeed,Qa as noop,ht as once,Qt as opacity,da as openPortBridge,wt as paginateText,Hs as parseChineseNumber,Gs as parseEnglishNumber,pa as parseRomanNumber,wn as parseVttCueTiming,mn as parseVttTimestamp,$t as perToNum,pn as performanceTime,Ks as prefetchUrl,Xs as prefetchUrls,ta as prefetchWhenIdle,it as quad,Ws as quart,on as queryFlag,Ht as querystring,Zs as quint,U as randomColor,ss as randomString,es as range,Ja as readFileAsArrayBuffer,zt as readFileAsDataURL,gt as readFileAsText,Nt as readFileAsUint8Array,za as readZipEntries,Jt as readZipEntry,ka as remap,zs as removeClassToElement,Va as replaceOld,Ka as report,nn as requestUrlToBuffer,En as resolveLocale,ja as rewriteZip,d as rgbToHex,h as rgbToHsb,b as rgbToHsl,i as rgbToHsv,j as rgbaString,u as rgbaToHex,g as rgbaToRgb,Cs as roundRectByArc,Zt as safeEqual,cs as saturation,ls as saveFileToDisk,bt as scriptOnLoad,bs as secureRandomString,ga as secureToken,ut as segmentByRanges,qs as serveWorker,ea as setFontSize2html,p as setMime,yt as setReportUrl,oa as sine,st as singleFlight,R as slugify,_s as smoothstep,n as srgbToLinear,Sa as status,N as strParse,et as subscribers,Ot as throttle,jn as timeFormat,rn as timestampToTime,X as toFullWidth,ts as toHalfWidth,S as toString,ba as transformNumber,G as transformText,ms as truncate,_ as truncateWithMarker,Mn as useI18n,y as vibrance,Ca as watchMediaQuery,Ms as whenIdle,$s as withTimeout,pt as withTimeoutFallback,ks as zipHasEntry};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Primitives whose correctness depends on *how* they compute, not just what they return:
|
|
3
|
+
* comparisons that must not leak their answer through timing, and randomness that must not
|
|
4
|
+
* be predictable.
|
|
5
|
+
*
|
|
6
|
+
* Kept apart from `str.ts` deliberately. `randomString` and `getRandomString` there are
|
|
7
|
+
* `Math.random()` based — fine for a DOM id or a message correlation key, unsafe for anything
|
|
8
|
+
* an attacker would want to guess. Someone reaching for a token generator should land here.
|
|
9
|
+
*
|
|
10
|
+
* Uses the Web Crypto global, which exists in browsers, Node >= 19, Deno, Workers and
|
|
11
|
+
* service workers alike.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* @description: Compare two secrets in time that does not depend on where they first differ.
|
|
15
|
+
*
|
|
16
|
+
* A plain `a === b` returns as soon as it finds a mismatch, so the time it takes reveals how
|
|
17
|
+
* long a shared prefix was — enough to recover a token one character at a time across many
|
|
18
|
+
* requests. Use this whenever one side of the comparison is attacker-supplied: access keys,
|
|
19
|
+
* session tokens, HMAC digests, pairing codes.
|
|
20
|
+
*
|
|
21
|
+
* **It hides the contents, not the length.** Inputs of different lengths return `false`
|
|
22
|
+
* immediately, because comparing to a fixed length would either truncate or pad the very data
|
|
23
|
+
* under test. Length is rarely the secret; when it is, compare fixed-width digests instead.
|
|
24
|
+
*
|
|
25
|
+
* @param {string | Uint8Array} a
|
|
26
|
+
* @param {string | Uint8Array} b
|
|
27
|
+
* @return {boolean} whether the two are byte-for-byte equal
|
|
28
|
+
*/
|
|
29
|
+
export declare const safeEqual: (a: string | Uint8Array, b: string | Uint8Array) => boolean;
|
|
30
|
+
/** Unambiguous by design: no `0`/`O`, no `1`/`l`/`I`. For codes a human reads aloud or retypes. */
|
|
31
|
+
export declare const UNAMBIGUOUS_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
|
32
|
+
/**
|
|
33
|
+
* @description: A random string drawn from `alphabet` using the platform CSPRNG.
|
|
34
|
+
*
|
|
35
|
+
* Unlike `randomString` / `getRandomString` in `str.ts`, this is safe for values an attacker
|
|
36
|
+
* must not be able to predict: device-pairing codes, one-time tokens, invite links.
|
|
37
|
+
*
|
|
38
|
+
* The draw is rejection-sampled, so every character is uniform no matter what the alphabet
|
|
39
|
+
* length is. A plain `byte % alphabet.length` is biased toward the first
|
|
40
|
+
* `256 % alphabet.length` characters — small enough to ignore for a short-lived,
|
|
41
|
+
* rate-limited code, and not small enough to reason about again every time someone reuses
|
|
42
|
+
* this for something longer-lived.
|
|
43
|
+
*
|
|
44
|
+
* @param {number} length how many characters to draw
|
|
45
|
+
* @param {string} alphabet characters to draw from; defaults to an unambiguous set
|
|
46
|
+
* @return {string}
|
|
47
|
+
*/
|
|
48
|
+
export declare const secureRandomString: (length: number, alphabet?: string) => string;
|
|
49
|
+
/**
|
|
50
|
+
* @description: A random hex token of `bytes` bytes, from the platform CSPRNG.
|
|
51
|
+
*
|
|
52
|
+
* The default of 32 bytes is 256 bits — the usual floor for a bearer token that is not
|
|
53
|
+
* expected to expire soon.
|
|
54
|
+
*
|
|
55
|
+
* @param {number} bytes how many random bytes to draw
|
|
56
|
+
* @return {string} lowercase hex, twice as long as `bytes`
|
|
57
|
+
*/
|
|
58
|
+
export declare const secureToken: (bytes?: number) => string;
|
package/dist/src/utils/str.d.ts
CHANGED
|
@@ -13,6 +13,17 @@ export declare const strParse: (str?: string, sep?: string | RegExp, eq?: string
|
|
|
13
13
|
*/
|
|
14
14
|
export declare const clearBr: (str?: string) => string;
|
|
15
15
|
export declare const isString: (obj: unknown) => boolean;
|
|
16
|
+
/**
|
|
17
|
+
* @description: A short random-ish string prefixed with the current timestamp.
|
|
18
|
+
*
|
|
19
|
+
* **Not cryptographically secure** — it draws from `Math.random()`, whose output is
|
|
20
|
+
* predictable from previous values. Good for a DOM id, a message correlation key or a cache
|
|
21
|
+
* buster; never for a token, code or anything an attacker benefits from guessing. Use
|
|
22
|
+
* `secureRandomString` / `secureToken` for those.
|
|
23
|
+
*
|
|
24
|
+
* @param {number} len characters of randomness after the timestamp
|
|
25
|
+
* @return {string}
|
|
26
|
+
*/
|
|
16
27
|
export declare function randomString(len?: number): string;
|
|
17
28
|
interface ClearStrOption {
|
|
18
29
|
urlencoded?: boolean;
|
|
@@ -102,6 +113,15 @@ export declare const transformText: (content: string | ArrayBuffer) => Transform
|
|
|
102
113
|
* @returns The MD5 hash as a hexadecimal string
|
|
103
114
|
*/
|
|
104
115
|
export declare const md5: (str: string) => string;
|
|
116
|
+
/**
|
|
117
|
+
* @description: A short random-ish base-36 string.
|
|
118
|
+
*
|
|
119
|
+
* **Not cryptographically secure** — `Math.random()` based, like `randomString`. Use
|
|
120
|
+
* `secureRandomString` / `secureToken` when the value must be unguessable.
|
|
121
|
+
*
|
|
122
|
+
* @param {number} len
|
|
123
|
+
* @return {string}
|
|
124
|
+
*/
|
|
105
125
|
export declare const getRandomString: (len?: number) => string;
|
|
106
126
|
type FileChunk = {
|
|
107
127
|
name: string;
|
|
@@ -260,4 +280,59 @@ export declare const MessageCodec: {
|
|
|
260
280
|
*/
|
|
261
281
|
decodeFileChunked(chunks: FileChunk[]): Promise<File>;
|
|
262
282
|
};
|
|
283
|
+
/**
|
|
284
|
+
* @description: Cut text to `max` characters and mark that it was cut.
|
|
285
|
+
*
|
|
286
|
+
* Different from `truncate`, which is for display: that one keeps a head and a tail around an
|
|
287
|
+
* ellipsis so a path or a name stays recognisable. This one is for text about to cross a
|
|
288
|
+
* boundary — a log line into a database row, tool output into a message, a field into a
|
|
289
|
+
* fixed-size frame — where the job is to respect a hard ceiling and leave evidence that
|
|
290
|
+
* something was dropped. Silent truncation is the failure this prevents: a reader who cannot
|
|
291
|
+
* tell a short answer from a cut-off one will trust the cut-off one.
|
|
292
|
+
*
|
|
293
|
+
* @param {string} text
|
|
294
|
+
* @param {number} max maximum characters to keep, before the marker
|
|
295
|
+
* @param {string} marker appended when anything was dropped
|
|
296
|
+
* @return {string}
|
|
297
|
+
*/
|
|
298
|
+
export declare const truncateWithMarker: (text: string, max: number, marker?: string) => string;
|
|
299
|
+
/**
|
|
300
|
+
* @description: Wrap text in a Markdown code fence long enough to survive backticks inside it.
|
|
301
|
+
*
|
|
302
|
+
* A fixed ``` fence breaks the moment the body contains one — the block ends early and the
|
|
303
|
+
* rest of the document renders as prose, which is exactly what happens when you paste a
|
|
304
|
+
* Markdown snippet or a transcript into a report. CommonMark closes a fence only on a run at
|
|
305
|
+
* least as long as the opening one, so the fix is to measure the longest run in the body and
|
|
306
|
+
* open with one backtick more.
|
|
307
|
+
*
|
|
308
|
+
* @param {string} body
|
|
309
|
+
* @param {string} lang info string for the opening fence
|
|
310
|
+
* @return {string}
|
|
311
|
+
*/
|
|
312
|
+
export declare const fenceCode: (body: string, lang?: string) => string;
|
|
313
|
+
/**
|
|
314
|
+
* @description: Reduce text to a lowercase `a-z0-9-` slug, safe as a filename on every
|
|
315
|
+
* filesystem and as a URL segment.
|
|
316
|
+
*
|
|
317
|
+
* Non-ASCII is dropped rather than transliterated: a guess at romanisation is wrong often
|
|
318
|
+
* enough that an empty slug — which the caller can detect and replace — beats a confidently
|
|
319
|
+
* mangled one. Callers that need CJK titles preserved should keep the original alongside.
|
|
320
|
+
*
|
|
321
|
+
* @param {string} text
|
|
322
|
+
* @param {number} maxLength longest slug to return; trailing dashes are trimmed after cutting
|
|
323
|
+
* @return {string} the slug, or `''` when nothing survived
|
|
324
|
+
*/
|
|
325
|
+
export declare const slugify: (text: string, maxLength?: number) => string;
|
|
326
|
+
/**
|
|
327
|
+
* @description: Escape one CSV field: doubles any quote and wraps the value when it contains
|
|
328
|
+
* a comma, a quote or a newline (RFC 4180).
|
|
329
|
+
*
|
|
330
|
+
* A leading `=`, `+`, `-` or `@` is also prefixed with a quote, because spreadsheet software
|
|
331
|
+
* treats those as formulas — the "CSV injection" that turns an exported username into a
|
|
332
|
+
* command when someone opens the file.
|
|
333
|
+
*
|
|
334
|
+
* @param {string | number} value
|
|
335
|
+
* @return {string}
|
|
336
|
+
*/
|
|
337
|
+
export declare const csvEscape: (value: string | number) => string;
|
|
263
338
|
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|