ranuts 0.2.0-alpha.1 → 0.4.0-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 +126 -24
- package/README.md +7 -5
- package/README.zh-CN.md +7 -5
- package/dist/chain-CTywmh_H.js +1 -0
- package/dist/{color-CRdlaDqQ.js → color-Dohr9BXX.js} +1 -1
- package/dist/enums-BAgbyGdH.js +1 -0
- package/dist/i18n-Cf5TtRb4.js +1 -0
- package/dist/index.d.ts +1 -5
- package/dist/index.js +1 -1
- package/dist/src/node/appendFile.d.ts +3 -3
- package/dist/src/node/fileInfo.d.ts +2 -2
- package/dist/src/node/index.js +1 -1
- package/dist/src/node/paresUrl.d.ts +1 -1
- package/dist/src/node/readFile.d.ts +3 -3
- package/dist/src/node/traverse.d.ts +2 -2
- package/dist/src/node/watchFile.d.ts +3 -3
- package/dist/src/node/writeFile.d.ts +3 -3
- package/dist/src/sw/index.d.ts +109 -0
- package/dist/src/sw/index.js +1 -0
- package/dist/src/utils/async.d.ts +81 -0
- package/dist/src/utils/audioRecorder.d.ts +1 -1
- package/dist/src/utils/behavior.d.ts +12 -3
- package/dist/src/utils/bom.d.ts +68 -178
- package/dist/src/utils/bridge.d.ts +153 -0
- package/dist/src/utils/canvas.d.ts +54 -0
- package/dist/src/utils/chain.d.ts +80 -0
- package/dist/src/utils/color.d.ts +76 -4
- package/dist/src/utils/compose.d.ts +1 -1
- package/dist/src/utils/console.d.ts +19 -1
- package/dist/src/utils/debounce.d.ts +27 -5
- package/dist/src/utils/device.d.ts +31 -3
- package/dist/src/utils/dom.d.ts +5 -84
- package/dist/src/utils/error.d.ts +18 -1
- package/dist/src/utils/event.d.ts +61 -0
- package/dist/src/utils/file.d.ts +35 -0
- package/dist/src/utils/i18n/index.js +1 -0
- package/dist/src/utils/i18n.d.ts +69 -0
- package/dist/src/utils/idb.d.ts +218 -0
- package/dist/src/utils/img.d.ts +60 -4
- package/dist/src/utils/index.d.ts +50 -16
- package/dist/src/utils/index.js +1 -1
- package/dist/src/utils/lang.d.ts +69 -0
- package/dist/src/utils/localePath.d.ts +62 -0
- package/dist/src/utils/memoize.d.ts +53 -5
- package/dist/src/utils/monitor.d.ts +55 -26
- package/dist/src/utils/number.d.ts +46 -9
- package/dist/src/utils/obj.d.ts +56 -31
- package/dist/src/utils/paginate.d.ts +73 -0
- package/dist/src/utils/prefetch.d.ts +81 -0
- package/dist/src/utils/queue.d.ts +53 -23
- package/dist/src/utils/report.d.ts +51 -3
- package/dist/src/utils/request.d.ts +26 -7
- package/dist/src/utils/script.d.ts +26 -4
- package/dist/src/utils/segment.d.ts +62 -0
- package/dist/src/utils/signal.d.ts +35 -3
- package/dist/src/utils/storage.d.ts +57 -0
- package/dist/src/utils/str.d.ts +112 -88
- package/dist/src/utils/style.d.ts +31 -0
- package/dist/src/utils/subscribe.d.ts +5 -5
- package/dist/src/utils/throttle.d.ts +26 -13
- package/dist/src/utils/time.d.ts +38 -6
- package/dist/src/utils/tween.d.ts +40 -0
- package/dist/src/utils/visual/application.d.ts +4 -4
- package/dist/src/utils/visual/enums.d.ts +4 -4
- package/dist/src/utils/visual/graphics/graphics.d.ts +25 -25
- package/dist/src/utils/visual/graphics/graphicsData.d.ts +1 -1
- package/dist/src/utils/visual/graphics/graphicsGeometry.d.ts +6 -6
- package/dist/src/utils/visual/index.js +1 -1
- package/dist/src/utils/visual/math/matrix.d.ts +8 -8
- package/dist/src/utils/visual/math/transform.d.ts +1 -1
- package/dist/src/utils/visual/render/batchRenderer.d.ts +20 -18
- package/dist/src/utils/visual/render/utils/batch/index.d.ts +13 -13
- package/dist/src/utils/visual/render/utils/float.d.ts +13 -13
- package/dist/src/utils/visual/render/utils/verticy.d.ts +3 -3
- package/dist/src/utils/visual/render/utils/webgl/initShader.d.ts +3 -2
- package/dist/src/utils/visual/render/utils/webgpu/shaders.d.ts +2 -2
- package/dist/src/utils/visual/render/webGPURenderer.d.ts +8 -8
- package/dist/src/utils/visual/vertex/container.d.ts +17 -16
- package/dist/src/utils/worker.d.ts +125 -0
- package/dist/src/utils/zip.d.ts +162 -0
- package/dist/src/vnode/index.d.ts +1 -1
- package/dist/src/vnode/index.js +1 -1
- package/dist/src/vnode/is.d.ts +4 -0
- package/dist/test/canvas.test.d.ts +1 -0
- package/dist/test/color.test.d.ts +1 -0
- package/dist/test/sw.test.d.ts +1 -0
- package/dist/test/tween.test.d.ts +1 -0
- package/dist/test/utils/async.test.d.ts +1 -0
- package/dist/test/utils/file-read.test.d.ts +1 -0
- package/dist/test/utils/format.test.d.ts +1 -0
- package/dist/test/utils/idb-collection.test.d.ts +1 -0
- package/dist/test/utils/idb.test.d.ts +1 -0
- package/dist/test/utils/instrumentation.test.d.ts +1 -0
- package/dist/test/utils/lang.test.d.ts +1 -0
- package/dist/test/utils/locale-path.test.d.ts +1 -0
- package/dist/test/utils/media-query.test.d.ts +1 -0
- package/dist/test/utils/number-parse.test.d.ts +1 -0
- package/dist/test/utils/paginate.test.d.ts +1 -0
- package/dist/test/utils/prefetch.test.d.ts +1 -0
- package/dist/test/utils/query-storage.test.d.ts +1 -0
- package/dist/test/utils/queue.test.d.ts +1 -0
- package/dist/test/utils/report-config.test.d.ts +1 -0
- package/dist/test/utils/report-image.test.d.ts +1 -0
- package/dist/test/utils/segment.test.d.ts +1 -0
- package/dist/test/utils/signal-once.test.d.ts +1 -0
- package/dist/test/utils/single-flight.test.d.ts +1 -0
- package/dist/test/utils/timing.test.d.ts +1 -0
- package/dist/test/utils/worker-client.test.d.ts +1 -0
- package/dist/test/utils/worker-serve.test.d.ts +1 -0
- package/dist/test/utils/zip.test.d.ts +1 -0
- package/dist/umd/index.umd.cjs +1 -1
- package/dist/umd/node/node.umd.cjs +1 -1
- package/dist/umd/utils/utils.umd.cjs +1 -1
- package/dist/utils-8TVtLBjA.js +1 -0
- package/docs/API.md +341 -147
- package/package.json +13 -6
- package/dist/src/vnode/chainDom.d.ts +0 -47
- package/dist/subscribe-CINWsor3.js +0 -1
- package/dist/utils-_OxsVZmz.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var t=class{_events=/* @__PURE__ */new Map;tap=(t,a)=>{this._events.get(t)&&t!==Symbol.for("NEW_LISTENER")&&this.call(Symbol.for("NEW_LISTENER"),t);const e=this._events.get(t)||/* @__PURE__ */new Set;return"function"==typeof a?e.add({name:t,callback:a}):e.add(a),this._events.set(t,e),this};call=(t,...a)=>((this._events.get(t)||/* @__PURE__ */new Set).forEach(t=>{const{callback:e}=t;e(...a)}),this);callSync=async(t,...a)=>{const e=this._events.get(t)||/* @__PURE__ */new Set;for(const n of e){const{callback:t}=n;await t(...a)}return this};once=(t,a)=>{let e;if("function"==typeof a)e={name:t,callback:(...n)=>{a(...n),this.off(t,e)},initialCallback:a};else{const{callback:n}=a;e={name:t,callback:(...a)=>{n(...a),this.off(t,e)},initialCallback:n}}return this.tap(t,e),this};off=(t,a)=>{const e=[...this._events.get(t)||/* @__PURE__ */new Set].filter(t=>{if("function"==typeof a)return t.callback!==a&&t.initialCallback!==a;{const{callback:e}=a;return t.callback!==e&&t.initialCallback!==e}});return this._events.set(t,new Set(e)),this}},a=Math.PI/180,e=180/Math.PI,n=2*Math.PI;export{t as i,n,e as r,a as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=()=>{};function t(e){return e<10?`0${e}`:e}var n=(e,t=2)=>String(e).padStart(t,"0"),r=/YYYY|YY|MM|M|DD|D|HH|H|hh|h|mm|m|ss|s|SSS|A|a|\[([^\]]*)]/g,s=(e,t="YYYY-MM-DD HH:mm:ss")=>{const s=null==e?/* @__PURE__ */new Date:new Date(e);if(Number.isNaN(s.getTime()))return"Invalid Date";const i=s.getHours(),a=i%12||12,o={YYYY:String(s.getFullYear()),YY:n(s.getFullYear()%100),MM:n(s.getMonth()+1),M:String(s.getMonth()+1),DD:n(s.getDate()),D:String(s.getDate()),HH:n(i),H:String(i),hh:n(a),h:String(a),mm:n(s.getMinutes()),m:String(s.getMinutes()),ss:n(s.getSeconds()),s:String(s.getSeconds()),SSS:n(s.getMilliseconds(),3),A:i<12?"AM":"PM",a:i<12?"am":"pm"};return t.replace(r,(e,t)=>void 0!==t?t:o[e])};function i(e){const t=e?new Date(e):/* @__PURE__ */new Date;return t.format=(e="YYYY-MM-DD HH:mm:ss")=>s(t,e),t}var a=e=>{if(0===e)return"00:00";if(!e)return"";const n=Math.trunc(e/3600),r=Math.trunc(e%3600/60),s=t(Math.trunc(e-3600*n-60*r));return 0===n?`${t(r)}:${s}`:`${t(n)}:${t(r)}:${s}`},o=()=>{if("undefined"!=typeof document)return performance.now();if("undefined"!=typeof process){const[e,t]=process.hrtime();return 1e3*e+t/1e6}return Date.now()},c=/* @__PURE__ */function(e){return e.IPAD="ipad",e.ANDROID="android",e.IPhONE="iphone",e.PC="pc",e}({}),u=()=>{if("undefined"!=typeof window){const e=navigator.userAgent.toLowerCase();return/ipad|ipod/.test(e)?"ipad":/android/.test(e)?"android":/iphone/.test(e)?"iphone":"pc"}return"pc"},d="undefined"!=typeof window,l="(max-width: 768px)",h=e=>"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia(e).matches,f=(e,t)=>{if("undefined"==typeof window||"function"!=typeof window.matchMedia)return t(!1),()=>{};const n=window.matchMedia(e),r=()=>t(n.matches);if(r(),"function"==typeof n.addEventListener)return n.addEventListener("change",r),()=>n.removeEventListener("change",r);const s=n;return s.addListener(r),()=>s.removeListener(r)},g=()=>!!d&&window.navigator.userAgent.toLowerCase().includes("micromessenger"),w=()=>{if(!d)return!1;const e=window.navigator.userAgent;return!!/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(e)},p=()=>{if(!d)return!1;const e=/iphone/i.test(window.navigator.userAgent),t=window.devicePixelRatio&&2===window.devicePixelRatio,n=window.devicePixelRatio&&3===window.devicePixelRatio,r=360===window.screen.width&&780===window.screen.height,s=375===window.screen.width&&812===window.screen.height,i=390===window.screen.width&&844===window.screen.height,a=414===window.screen.width&&896===window.screen.height,o=428===window.screen.width&&926===window.screen.height;switch(!0){case e&&n&&r:case e&&n&&s:case e&&n&&i:case e&&t&&a:case e&&n&&a:case e&&n&&o:return!0;default:return!1}},m=(t=e)=>{const n=()=>{t(),d&&window.removeEventListener("popstate",n)};d&&window.history.pushState(null,"",window.location.href),setTimeout(()=>{d&&window.addEventListener("popstate",n)},500)},y=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""},v=(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)}),A=e=>{const t=e.backingStorePixelRatio||e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||1;return(d&&window.devicePixelRatio||1)/t},_=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},D=(e=10)=>{const t=[];let n,r=0;return new Promise(s=>{const i=()=>{const a=o(),c=a-r;0!==r&&t.push(c),r=a,t.length>e&&(s(1/(t.reduce((e,t)=>e+t)/e)),cancelAnimationFrame(n)),n=requestAnimationFrame(i)};t.length<=e&&(n=requestAnimationFrame(i))})},x=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},S=e=>x(e),M=(e,t)=>{const n=x(t)[e];if(void 0===n)return!1;const r=n.toLowerCase();return""===r||"1"===r||"true"===r},b=()=>{if("undefined"==typeof window)return!1;try{return window.parent!==window}catch{return!0}};function L(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}var R=e=>{const t=document.createElement("img");t.src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",t.width=0,t.height=0,t.style.opacity="0",e.dataTransfer&&e.dataTransfer.setDragImage(t,0,0)};function P(e){if("undefined"!=typeof window){const t=new RegExp(`(^| )${e}(?:=([^;]*))?(;|$)`).exec(document.cookie);if(t&&t[2])return t[2]}return""}var O=()=>"undefined"!=typeof window?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},k=()=>{if("undefined"!=typeof window)return window.navigator.connection},Y=/(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x7E]|%(?:[^\da-f]|[\da-f][^\da-f]|$))+/gi,F=/(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g;function I(e){return String(e).replace(F,"$1�$2").replace(Y,encodeURI)}var B=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)}}),C=(e,...t)=>n=>new Promise((r,s)=>{setTimeout(async()=>{try{r(await e(...t))}catch(n){s(n)}},n)}),H=async e=>{const{url:t,duration:n=3e3,count:r=5}=e;let s=0,i=0;const a=[];for(let o=0;o<r;o++){const e=await C(B,t)(n);a.push(e)}return s=Math.max(...a)-Math.min(...a),i=a.reduce((e,t)=>e+t)/a.length,{ping:i,jitter:s}},$=()=>{if("undefined"!=typeof navigator)return navigator.vendor&&navigator.vendor.indexOf("Apple")>-1&&navigator.userAgent&&!navigator.userAgent.includes("CriOS")&&!navigator.userAgent.includes("FxiOS")},E=()=>{try{return"undefined"==typeof localStorage?null:localStorage}catch{return null}},T=(e,t)=>{try{E()?.setItem(e,t)}catch{}},U=e=>{try{return E()?.getItem(e)??""}catch{return""}},N=e=>{try{E()?.removeItem(e)}catch{}},j=(e="")=>{const t=t=>`${e}${t}`;return{keyOf:t,get:(e,n)=>{const r=U(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 T(t(e),r),U(t(e))===r},remove:e=>N(t(e))}},z=(e,t=2e4)=>{const n=e.slice(0,t);let r=0,s=0;for(const i of n){const e=i.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"},q=()=>{if("undefined"==typeof navigator)return"other";const e=(navigator.language||"").toLowerCase();return e.startsWith("zh")?"zh":e.startsWith("en")?"en":"other"},K=e=>{const{supported:t,query:n,cookie:r,storageKey:s,useNavigator:i=!0,url:a}=e,o=e.fallback??t[0]??"en";if(0===t.length)return o;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],i=c.findIndex(e=>e===s||e.split("-")[0]===s);return-1===i?void 0:t[i]},d=[];if(n&&d.push(x(a)[n]),r&&d.push(P(r)),s&&d.push(U(s)),i&&"undefined"!=typeof navigator){const{languages:e,language:t}=navigator;d.push(...e??[],t)}for(const l of d){const e=u(l);if(e)return e}return o},W=Object.freeze({}),G=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&&U(this._storageKey)||null;if(n&&(this._messages[n]||0===t.length))return n;if(e.locale)return e.locale;if(e.detectNavigator){const e=K({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&&T(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??W;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()}},J=null;function Q(e={}){return J=new G(e)}function V(){return J}export{m as A,s as B,B as C,M as D,H as E,d as F,a as H,w as I,g as L,l as M,u as N,R as O,p as P,h as R,O as S,$ as T,i as U,o as V,e as W,y as _,q as a,A as b,U as c,L as d,k as f,x as g,I as h,z as i,c as j,v as k,N as l,C as m,Q as n,K as o,_ as p,V as r,j as s,G as t,T as u,P as v,b as w,S as x,D as y,f as z};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import type { BridgeManagerOptions, BroadcastPayload, CallToPayload, MessageData, MessageHandler, PendingRequest } from './src/utils';
|
|
3
|
-
import type { CurrentDevice, TransformText } from '@/utils';
|
|
4
|
-
export { AudioRecorder, Color, ColorScheme, FMT, Hsl, Hsla, Mathjs, MimeType, Monitor, QuestQueue, Rgb, Rgba, SyncHook, addClassToElement, appendUrl, audioVendor, canvasVendor, changeHumpToLowerCase, clearBr, clearStr, componentToHex, compose, connection, convertImageToBase64, createData, createDocumentFragment, createObjectURL, currentDevice, debounce, durationHandler, encodeUrl, escapeHtml, filterObj, formatJson, generateThrottle, getAllQueryString, getCookie, getCookieByName, getFrame, getHost, getMime, getPerformance, getPixelRatio, getStatus, getWindow, handleConsole, handleError, handleFetchHook, hexToRgb, hsbToRgb, hslToRgb, hsvToHsl, hsvToRgb, hue2rgb, imageRequest, isClient, isImageSize, isMobile, isString, isWeiXin, mathjs, memoize, merge, mergeExports, networkSpeed, noop, perToNum, performanceTime, querystring, randomColor, randomString, range, removeClassToElement, removeGhosting, replaceOld, report, requestUrlToBuffer, retain, rgbToHex, rgbToHsb, rgbToHsl, scriptOnLoad, setMime, status, str2Xml, strParse, throttle, timeFormat, timestampToTime, webglVendor, TOTP, isBangDevice, localStorageGetItem, localStorageSetItem, setAttributeByGlobal, setFontSize2html, Chain, create, isEqual, cloneDeep, createSignal, subscribers, getMatchingSentences, transformNumber, toString, addNumSym, getQuery, checkEncoding, transformText, isSafari, md5, getRandomString, bridgeManager, Client, BridgeManager, PostMessageBridge, MessageCodec, Platform, getExtensions, };
|
|
5
|
-
export type { CurrentDevice, TransformText, MessageHandler, MessageData, PendingRequest, BridgeManagerOptions, BroadcastPayload, CallToPayload, };
|
|
1
|
+
export * from './src/utils';
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{i as s}from"./enums-BAgbyGdH.js";import{A as a,B as t,C as n,D as o,E as r,F as m,G as i,H as p,I as f,J as j,K as c,L as l,M as u,N as h,O as x,P as b,Q as d,R as e,S as g,T as k,U as v,V as w,W as y,X as z,Y as A,Z as B,_ as C,a as D,b as E,c as F,d as H,f as I,g as L,h as M,i as N,j as O,k as P,l as R,m as S,n as T,o as U,p as V,q as W,r as _,s as q,t as G,u as J,v as K,w as Q,x as X,y as Y,z as Z}from"./color-Dohr9BXX.js";import{$,$t as ss,A as as,At as ts,B as ns,Bt as os,C as rs,Ct as ms,D as is,Dt as ps,E as fs,Et as js,F as cs,Ft as ls,G as us,Gt as hs,H as xs,Ht as bs,I as ds,It as es,J as gs,Jt as ks,K as vs,Kt as ws,L as ys,Lt as zs,M as As,Mt as Bs,N as Cs,Nt as Ds,O as Es,Ot as Fs,P as Hs,Pt as Is,Q as Ls,Qt as Ms,R as Ns,Rt as Os,S as Ps,St as Rs,T as Ss,Tt as Ts,U as Us,Ut as Vs,V as Ws,Vt as _s,W as qs,Wt as Gs,X as Js,Xt as Ks,Y as Qs,Yt as Xs,Z as Ys,Zt as Zs,_ as $s,_t as sa,a as aa,an as ta,at as na,b as oa,bt as ra,c as ma,cn as ia,ct as pa,d as fa,dt as ja,en as ca,et as la,f as ua,ft as ha,g as xa,gt as ba,h as da,ht as ea,i as ga,in as ka,it as va,j as wa,jt as ya,k as za,kt as Aa,l as Ba,ln as Ca,lt as Da,m as Ea,mt as Fa,n as Ha,nn as Ia,nt as La,o as Ma,on as Na,ot as Oa,p as Pa,pt as Ra,q as Sa,qt as Ta,r as Ua,rn as Va,rt as Wa,s as _a,sn as qa,st as Ga,t as Ja,tn as Ka,tt as Qa,u as Xa,un as Ya,ut as Za,v as $a,vt as st,w as at,wt as tt,x as nt,xt as ot,y as rt,yt as mt,z as it,zt as pt}from"./utils-8TVtLBjA.js";import{A as ft,B as jt,C as ct,D as lt,E as ut,F as ht,H as xt,I as bt,L as dt,M as et,N as gt,O as kt,P as vt,R as wt,S as yt,T as zt,U as At,V as Bt,W as Ct,_ as Dt,a as Et,b as Ft,c as Ht,d as It,f as Lt,g as Mt,h as Nt,i as Ot,k as Pt,l as Rt,m as St,n as Tt,o as Ut,p as Vt,r as Wt,s as _t,t as qt,u as Gt,v as Jt,w as Kt,x as Qt,y as Xt,z as Yt}from"./i18n-Cf5TtRb4.js";import{n as Zt,t as $t}from"./chain-CTywmh_H.js";export{gs as ADOPTED_SHEET_MARKER,Qs as ADOPTED_STYLE_MARKER,Ds as AudioRecorder,ws as BRIDGE_MARKER,Ta as BridgeManager,$t as Chain,ks as Client,G as Color,T as ColorScheme,Xs as DEFAULT_CHANNEL,sa as EventManager,_ as FMT,N as HEX_COLOR_REGEX,D as Hsl,U as Hsla,qt as I18nCore,et as MOBILE_MEDIA_QUERY,Ia as Mathjs,f as MessageCodec,u as MimeType,Ma as Monitor,Ks as Platform,Zs as PostMessageBridge,Ua as QuestQueue,q as RGBA_REGEX,F as RGB_REGEX,R as Rgb,J as Rgba,s as SyncHook,ps as TOTP,at as TimeoutError,vs as WebDB,cs as WorkerClient,da as ZIP_DEFLATE,xa as ZIP_STORED,Ms as acceptPortBridge,mt as addClassToElement,Va as addNumSym,Js as adoptSheetText,Ys as adoptStyles,It as appendUrl,l as arrayBufferToString,Fs as audioVendor,ss as bridgeManager,Us as buildOffsets,Aa as canvasVendor,e as changeHumpToLowerCase,Z as checkEncoding,Za as circ,t as clearBr,w as clearStr,Is as cloneDeep,H as componentToHex,js as compose,Lt as connection,Ls as convertImageToBase64,$s as crc32,Zt as create,Xa as createData,ra as createDocumentFragment,Sa as createHandoff,Tt as createI18n,Ws as createLocalePath,Vt as createObjectURL,ca as createPortBridge,ya as createSignal,_t as createStore,$a as createZip,ja as cubic,gt as currentDevice,$ as cutRound,tt as debounce,Ss as deferred,fs as delay,Ot as detectLanguage,St as durationHandler,Nt as encodeUrl,ot as escapeHtml,ha as expo,va as fanShapedByArc,ls as filterObj,jt as formatDate,es as formatJson,Mt as getAllQueryString,na as getAngle,Oa as getArcPointerByDeg,Dt as getCookie,Jt as getCookieByName,h as getExtensions,Xt as getFrame,la as getImage,Ga as getLinearGradient,p as getMatchingSentences,Qa as getMatrix,b as getMime,Ea as getPerformance,Ft as getPixelRatio,Qt as getQuery,v as getRandomString,fa as getReportUrl,ga as getStatus,pa as getTangentByPointer,yt as getWindow,Ts as handleConsole,st as handleError,ma as handleFetchHook,Ba as handleXhrHook,I as hexToAlpha,V as hexToHsb,S as hexToHsv,M as hexToRgb,L as hsbToHsl,C as hsbToRgb,K as hslToHsb,Y as hslToHsv,E as hslToRgb,X as hsvToHsl,g as hsvToRgb,n as hue2rgb,ct as imageRequest,qs as indexForOffset,rt as inflateRaw,vt as isBangDevice,ht as isClient,zs as isEqual,La as isImageSize,Kt as isInIframe,bt as isMobile,zt as isSafari,y as isString,za as isUrlCached,dt as isWeiXin,Ja as loadScript,Ht as localStorageGetItem,Rt as localStorageRemoveItem,Gt as localStorageSetItem,wt as matchMediaQuery,ka as mathjs,i as md5,Vs as memoize,Os as merge,pt as mergeExports,Et as navigatorLanguage,as as networkAllowsDownload,ut as networkSpeed,Ct as noop,Gs as once,Wa as opacity,Ka as openPortBridge,xs as paginateText,ta as parseChineseNumber,Na as parseEnglishNumber,qa as parseRomanNumber,ia as perToNum,Bt as performanceTime,wa as prefetchUrl,As as prefetchUrls,Cs as prefetchWhenIdle,Ra as quad,Fa as quart,lt as queryFlag,os as querystring,ea as quint,Q as randomColor,c as randomString,Ca as range,ys as readFileAsArrayBuffer,Ns as readFileAsDataURL,it as readFileAsText,ns as readFileAsUint8Array,oa as readZipEntries,nt as readZipEntry,Rs as removeClassToElement,kt as removeGhosting,_s as replaceOld,ua as report,Pt as requestUrlToBuffer,Ut as resolveLocale,ft as retain,Ps as rewriteZip,k as rgbToHex,r as rgbToHsb,o as rgbToHsl,x as rgbToHsv,P as rgbaString,a as rgbaToHex,O as rgbaToRgb,Da as roundRectByArc,Ha as scriptOnLoad,us as segmentByRanges,ds as serveWorker,bs as setAttributeByGlobal,ms as setFontSize2html,m as setMime,Pa as setReportUrl,ba as sine,hs as singleFlight,aa as status,W as str2Xml,j as strParse,Bs as subscribers,_a as throttle,xt as timeFormat,At as timestampToTime,A as toFullWidth,z as toHalfWidth,B as toString,Ya as transformNumber,d as transformText,Wt as useI18n,Yt as watchMediaQuery,ts as webglVendor,Hs as whenIdle,is as withTimeout,Es as withTimeoutFallback,rs as zipHasEntry};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @description:
|
|
3
|
-
* @param {string} path
|
|
4
|
-
* @param {string} content
|
|
2
|
+
* @description: Append content to an existing file
|
|
3
|
+
* @param {string} path file path
|
|
4
|
+
* @param {string} content content to append
|
|
5
5
|
* @return {Promise}
|
|
6
6
|
*/
|
|
7
7
|
export declare const appendFile: (path: string, content: string) => Promise<Ranuts.Identification>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @description:
|
|
3
|
-
* @param {string} path
|
|
2
|
+
* @description: Stat a file — typically to tell a file from a directory via data.isDirectory()
|
|
3
|
+
* @param {string} path file path
|
|
4
4
|
* @return {Promise}
|
|
5
5
|
*/
|
|
6
6
|
declare const queryFileInfo: (path: string) => Promise<Ranuts.Identification>;
|
package/dist/src/node/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{P as e,S as t,r as n,x as r}from"../../color-CRdlaDqQ.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 S}from"node:util";import{Buffer as T}from"node:buffer";import P from"node:crypto";function O(){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:O,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(n).forEach(r=>t[r]=e?U(n[r][0],n[r][1]):String),t})(),((e=F)=>({isColorSupported:e,reset:e?e=>`${n.reset[0]}${e}${n.reset[1]}`:String,bold:e?U(n.bold[0],n.bold[1],`${n.bold[1]}${n.bold[0]}`):String,dim:e?U(n.dim[0],n.dim[1],`${n.dim[1]}${n.dim[0]}`):String}))()),$=(t={})=>{const{uploadDir:n=".",encoding:r="",json:o=!0}=t;return(t,s)=>{const{req:i,res:c}=t,{url:d,method:l}=i,[u="",f=""]=d?.split("?")||[],h=f?new URLSearchParams(f):{};t.request||(t.request={}),t.request.method=l,t.request.path=u,t.request.url=d,t.request.query=h;const p=i.headers["content-type"];if("application/json"===p){r?i.setEncoding(r):i.setEncoding("utf-8");let e="";i.on("data",t=>{e+=t}),i.on("end",()=>{c.setHeader("content-type","application/json;charset=UTF-8");try{t.request.body=o?JSON.parse(e):e}catch{t.request.body=e}s()})}if(p?.includes("multipart/form-data;")){const[t,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 t={};u.split("\r\n").slice(0,4).forEach(n=>{Object.assign(t,e(n,";",/=|:/))});const r=t["Content-Type"],o=Buffer.from(t.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(`${n}/${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})})}),z=()=>{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 J(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 W=e=>{const{dirPath:t}=e;try{return H.readdirSync(t)}catch(n){throw n}},G=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=(e={})=>{const{pathname:n,fileTypes:o={}}=e;return async(e,s)=>{try{const{req:i,res:c}=e;if(i.url){const e="text/html",s=n||process.cwd(),d=E.normalize(E.resolve(s)),l=E.extname(i.url).slice(1);Object.keys(o).forEach(e=>t(e,o[e]));const u=l?r(l):e;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=S(f),te=S(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=T.byteLength(e);let r=null;if(n>65535?(r=T.alloc(10+n),r[1]=127,r.writeUInt32BE(n,6),r.write(e,10)):n>125?(r=T.alloc(4+n),r[1]=126,r.writeUInt16BE(n,2),r.write(e,4)):(r=T.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=T.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: "+P.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=T.allocUnsafe(0),s=T.allocUnsafe(0);const i=[];let a=!0;function c(){const e=function(e){const t=T.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=T.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=T.allocUnsafe(0)}}})}})}n.on("data",e=>{for(o=T.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{G as Router,q as Server,ce as WSS,_ as appendFile,$ as body,k as colors,R as connect,K as get,z as getIPAdress,F as isColorSupported,J as paresUrl,A as prompt,N as queryFileInfo,W 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{F as e,J as t,P as n,r}from"../../color-Dohr9BXX.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 P from"node:crypto";function O(){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:O,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,F=(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},M=(e,t)=>new Promise((n,r)=>{H.appendFile(e,t,t=>{t?r({success:!1,_identification:!1,data:t}):F(e).then(e=>{n(e)})})}),_=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=_)=>{const t={};return Object.keys(r).forEach(n=>t[n]=e?U(r[n][0],r[n][1]):String),t})(),((e=_)=>({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:n=".",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(n=>{Object.assign(e,t(n,";",/=|:/))});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(`${n}/${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})})}),J=({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})})}),K=()=>{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 W=e=>{const{dirPath:t}=e;try{return H.readdirSync(t)}catch(n){throw n}},G=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=(t={})=>{const{pathname:r,fileTypes:o={}}=t;return async(t,s)=>{try{const{req:i,res:c}=t;if(i.url){const t="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?n(l):t;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: "+P.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{G as Router,q as Server,ce as WSS,M as appendFile,$ as body,k as colors,R as connect,J as get,K as getIPAdress,_ as isColorSupported,z as paresUrl,A as prompt,N as queryFileInfo,W as readDir,F 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};
|
|
@@ -11,7 +11,7 @@ interface Req extends IncomingMessage {
|
|
|
11
11
|
_parsedUrl?: ParseUrl;
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
14
|
-
* @description:
|
|
14
|
+
* @description: Parse an IncomingMessage's request URL; the return type is always ParseUrl
|
|
15
15
|
* @param {Req} req
|
|
16
16
|
* @return {ParseUrl}
|
|
17
17
|
*/
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { FilePromiseResult } from '@/node/fs';
|
|
2
2
|
/**
|
|
3
|
-
* @description:
|
|
4
|
-
* @param {string} path
|
|
5
|
-
* @param {string} format
|
|
3
|
+
* @description: Read a file, returning a status code and the content on success
|
|
4
|
+
* @param {string} path file path
|
|
5
|
+
* @param {string} format encoding, defaults to utf-8
|
|
6
6
|
* @return {Promise}
|
|
7
7
|
*/
|
|
8
8
|
declare const readFile: (path: string, format?: BufferEncoding) => FilePromiseResult;
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import type { Stats } from 'node:fs';
|
|
2
2
|
type Caller = (relPath: string, absPath: string, stats: Stats) => any;
|
|
3
3
|
/**
|
|
4
|
-
* @description:
|
|
4
|
+
* @description: Walk every directory recursively, running a function for each file found
|
|
5
5
|
* @param {string} dir
|
|
6
6
|
* @param {Caller} callback
|
|
7
7
|
* @param {*} pre
|
|
8
8
|
*/
|
|
9
9
|
export declare function traverse(dir: string, callback: Caller, pre?: string): Promise<any>;
|
|
10
10
|
/**
|
|
11
|
-
* @description:
|
|
11
|
+
* @description: Synchronous: walk every directory recursively, running a function for each file found
|
|
12
12
|
* @param {string} dir
|
|
13
13
|
* @param {Caller} callback
|
|
14
14
|
* @param {*} pre
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @description:
|
|
3
|
-
* @param {string} path
|
|
4
|
-
* @param {number} interval
|
|
2
|
+
* @description: Watch a file for changes and report its status
|
|
3
|
+
* @param {string} path file to watch
|
|
4
|
+
* @param {number} interval poll interval in milliseconds, defaults to 20
|
|
5
5
|
* @return {Promise}
|
|
6
6
|
*/
|
|
7
7
|
declare const watchFile: (path: string, interval?: number) => Promise<Ranuts.Identification>;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @description:
|
|
3
|
-
* @param {string} path
|
|
4
|
-
* @param {string} content
|
|
2
|
+
* @description: Write a file at the given path, truncating it if it exists and creating it if it does not
|
|
3
|
+
* @param {string} path file path
|
|
4
|
+
* @param {string} content file content
|
|
5
5
|
* @return {Promise}
|
|
6
6
|
*/
|
|
7
7
|
declare const writeFile: (path: string, content: string) => Promise<Ranuts.Identification>;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Service Worker building blocks.
|
|
3
|
+
*
|
|
4
|
+
* A companion to `prefetchUrls` / `prefetchWhenIdle` in `ranuts/utils`: those ship the page
|
|
5
|
+
* side of the "warm the cache in the background" protocol, and {@link servePrecache} is the
|
|
6
|
+
* worker side that answers them. The two caching strategies below are the standard pair every
|
|
7
|
+
* SW ends up writing.
|
|
8
|
+
*
|
|
9
|
+
* Its own entry point (`ranuts/sw`) rather than part of `ranuts/utils`, because this code runs
|
|
10
|
+
* in a `ServiceWorkerGlobalScope` where `window` and `document` do not exist — pulling in the
|
|
11
|
+
* general utils barrel would drag DOM-facing modules into a worker bundle.
|
|
12
|
+
*
|
|
13
|
+
* All of it assumes a bundled service worker. A hand-written `sw.js` served as a static file
|
|
14
|
+
* cannot import from node_modules; either bundle it, or copy the pieces you need.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* The bit of `ExtendableMessageEvent` used here, declared locally rather than pulled from
|
|
18
|
+
* `lib.webworker` — that lib conflicts with `lib.dom` in a project that compiles both, and
|
|
19
|
+
* this package must stay importable from either.
|
|
20
|
+
*/
|
|
21
|
+
export interface PrecacheMessageEvent {
|
|
22
|
+
data: unknown;
|
|
23
|
+
waitUntil: (promise: Promise<unknown>) => void;
|
|
24
|
+
}
|
|
25
|
+
/** Minimal view of the SW global the helpers touch, so they can be unit-tested with a stub. */
|
|
26
|
+
export interface SWScope {
|
|
27
|
+
caches: CacheStorage;
|
|
28
|
+
fetch: typeof fetch;
|
|
29
|
+
addEventListener: (type: string, listener: (event: never) => void) => void;
|
|
30
|
+
removeEventListener: (type: string, listener: (event: never) => void) => void;
|
|
31
|
+
}
|
|
32
|
+
export interface CacheStrategyOptions {
|
|
33
|
+
/** Cache to read and write. */
|
|
34
|
+
cacheName: string;
|
|
35
|
+
/** Whether a response may be stored. Default: any GET answered with 200. */
|
|
36
|
+
shouldCache?: (request: Request, response: Response) => boolean;
|
|
37
|
+
/** Scope override, for tests or a non-global worker. */
|
|
38
|
+
scope?: SWScope;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* @description: Cache-first: serve the stored copy when there is one, otherwise fetch and
|
|
42
|
+
* store. For immutable, content-hashed assets — scripts, styles, fonts, model weights.
|
|
43
|
+
*
|
|
44
|
+
* @param {Request} request
|
|
45
|
+
* @param {CacheStrategyOptions} options
|
|
46
|
+
* @return {Promise<Response>} never rejects; a network failure resolves to a 408
|
|
47
|
+
*/
|
|
48
|
+
export declare const cacheFirst: (request: Request, options: CacheStrategyOptions) => Promise<Response>;
|
|
49
|
+
/**
|
|
50
|
+
* @description: Network-first: go to the network, store what comes back, and fall back to the
|
|
51
|
+
* cache when offline. For anything that must reflect a deploy immediately — HTML navigations,
|
|
52
|
+
* a manifest, an API response you also want available offline.
|
|
53
|
+
*
|
|
54
|
+
* @param {Request} request
|
|
55
|
+
* @param {CacheStrategyOptions} options
|
|
56
|
+
* @return {Promise<Response>} never rejects; offline with nothing cached resolves to a 408
|
|
57
|
+
*/
|
|
58
|
+
export declare const networkFirst: (request: Request, options: CacheStrategyOptions) => Promise<Response>;
|
|
59
|
+
/**
|
|
60
|
+
* @description: Fill a cache with a list of URLs, skipping what is already there. Failures are
|
|
61
|
+
* per-URL and silent — one 404 in a precache list must not abort the install.
|
|
62
|
+
*
|
|
63
|
+
* @param {string} cacheName
|
|
64
|
+
* @param {string[]} urls
|
|
65
|
+
* @param {object} options
|
|
66
|
+
* @return {Promise<void>}
|
|
67
|
+
*/
|
|
68
|
+
export declare const precache: (cacheName: string, urls: readonly string[], options?: {
|
|
69
|
+
scope?: SWScope;
|
|
70
|
+
}) => Promise<void>;
|
|
71
|
+
/**
|
|
72
|
+
* @description: Delete every cache except the ones named. Call it on `activate` so a new
|
|
73
|
+
* build's caches replace the previous build's instead of accumulating.
|
|
74
|
+
*
|
|
75
|
+
* @param {string[]} keep cache names to preserve
|
|
76
|
+
* @param {object} options
|
|
77
|
+
* @return {Promise<string[]>} the names that were deleted
|
|
78
|
+
*/
|
|
79
|
+
export declare const dropCachesExcept: (keep: readonly string[], options?: {
|
|
80
|
+
scope?: SWScope;
|
|
81
|
+
}) => Promise<string[]>;
|
|
82
|
+
export interface ServePrecacheOptions {
|
|
83
|
+
/** Cache the URLs land in. */
|
|
84
|
+
cacheName: string;
|
|
85
|
+
/** Message `type` to answer. Must match `prefetchUrls({ serviceWorkerMessage })`. */
|
|
86
|
+
type: string;
|
|
87
|
+
scope?: SWScope;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* @description: Answer the precache messages that `prefetchUrls({ serviceWorkerMessage })`
|
|
91
|
+
* posts from the page — the worker half of that protocol.
|
|
92
|
+
*
|
|
93
|
+
* Downloading here rather than on the page is the whole point: the work is wrapped in
|
|
94
|
+
* `event.waitUntil`, so the service worker stays alive through navigations. A page-side fetch
|
|
95
|
+
* is aborted the moment the user clicks away, and a large asset then restarts from zero on the
|
|
96
|
+
* next visit.
|
|
97
|
+
*
|
|
98
|
+
* @param {ServePrecacheOptions} options
|
|
99
|
+
* @return {Function} stop — removes the listener
|
|
100
|
+
* @example
|
|
101
|
+
* ```ts
|
|
102
|
+
* // sw.ts
|
|
103
|
+
* servePrecache({ type: 'precache-models', cacheName: 'models' });
|
|
104
|
+
*
|
|
105
|
+
* // page
|
|
106
|
+
* prefetchUrls(modelFiles, { serviceWorkerMessage: 'precache-models' });
|
|
107
|
+
* ```
|
|
108
|
+
*/
|
|
109
|
+
export declare const servePrecache: (options: ServePrecacheOptions) => (() => void);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=()=>globalThis,t=()=>new Response("Network error happened",{status:408,headers:{"Content-Type":"text/plain"}}),c=(e,t)=>"GET"===e.method&&200===t.status,a=(e,t,c,a)=>{const s=a.clone();return e.caches.open(t).then(e=>e.put(c.url,s)).catch(()=>{})},s=async(s,n)=>{const r=n.scope??e(),o=n.shouldCache??c;try{const e=await r.caches.match(s.url);if(e)return e;const t=await r.fetch(s);return o(s,t)&&a(r,n.cacheName,s,t),t}catch{return t()}},n=async(s,n)=>{const r=n.scope??e(),o=n.shouldCache??c;try{const e=await r.fetch(s);return o(s,e)&&a(r,n.cacheName,s,e),e}catch{return await r.caches.match(s.url).catch(()=>{})??t()}},r=async(t,c,a={})=>{const s=a.scope??e(),n=await s.caches.open(t);for(const e of c)try{if(await n.match(e))continue;const t=await s.fetch(e,{cache:"force-cache"});t.ok&&await n.put(e,t.clone())}catch{}},o=async(t,c={})=>{const a=c.scope??e(),s=(await a.caches.keys()).filter(e=>!t.includes(e));return await Promise.all(s.map(e=>a.caches.delete(e))),s},h=t=>{const c=t.scope??e(),a=e=>{const a=e.data;a&&a.type===t.type&&Array.isArray(a.urls)&&e.waitUntil(r(t.cacheName,a.urls,{scope:c}))};return c.addEventListener("message",a),()=>c.removeEventListener("message",a)};export{s as cacheFirst,o as dropCachesExcept,n as networkFirst,r as precache,h as servePrecache};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Promise primitives that JavaScript does not ship: an externally settled promise and a
|
|
3
|
+
* bounded wait. Both are things hand-rolled at nearly every call site that needs them, and
|
|
4
|
+
* both are usually hand-rolled with the same leak.
|
|
5
|
+
*/
|
|
6
|
+
export interface Deferred<T> {
|
|
7
|
+
promise: Promise<T>;
|
|
8
|
+
resolve: (value: T | PromiseLike<T>) => void;
|
|
9
|
+
reject: (reason?: unknown) => void;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* @description: A promise plus its `resolve` / `reject`, for the case where the thing that
|
|
13
|
+
* settles the promise is not the thing that creates it — a response arriving on a message
|
|
14
|
+
* listener, a callback fired by a third-party SDK, a queue slot freeing up.
|
|
15
|
+
*
|
|
16
|
+
* The alternative is assigning the executor's arguments to outer `let`s, which TypeScript
|
|
17
|
+
* cannot prove are assigned and which is easy to get subtly wrong.
|
|
18
|
+
*
|
|
19
|
+
* @return {Deferred<T>}
|
|
20
|
+
* @example
|
|
21
|
+
* ```ts
|
|
22
|
+
* const ready = deferred<Editor>();
|
|
23
|
+
* sdk.onReady((editor) => ready.resolve(editor));
|
|
24
|
+
* const editor = await ready.promise;
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare const deferred: <T = void>() => Deferred<T>;
|
|
28
|
+
export declare class TimeoutError extends Error {
|
|
29
|
+
constructor(message: string);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* @description: Reject if a promise has not settled within `ms`. The returned promise
|
|
33
|
+
* settles with whatever the input does, or rejects with a [`TimeoutError`](#timeouterror).
|
|
34
|
+
*
|
|
35
|
+
* **The timer is always cleared**, including on the fast path. The usual hand-rolled
|
|
36
|
+
* version — `Promise.race([task, new Promise((_, r) => setTimeout(r, ms))])` — leaks the
|
|
37
|
+
* timer whenever the task wins, which in Node keeps the event loop alive for the full
|
|
38
|
+
* duration and in tests leaves a stray timer firing into the next test.
|
|
39
|
+
*
|
|
40
|
+
* This does **not** cancel the underlying work; a promise cannot be cancelled. Pass
|
|
41
|
+
* `onTimeout` to tear the operation down (abort a fetch, terminate a worker) when the
|
|
42
|
+
* deadline passes.
|
|
43
|
+
*
|
|
44
|
+
* @param {Promise<T>} promise the operation to bound
|
|
45
|
+
* @param {number} ms deadline in milliseconds
|
|
46
|
+
* @param {object} options `message` for the error text, `onTimeout` for cleanup
|
|
47
|
+
* @return {Promise<T>}
|
|
48
|
+
* @example
|
|
49
|
+
* ```ts
|
|
50
|
+
* const controller = new AbortController();
|
|
51
|
+
* const res = await withTimeout(fetch(url, { signal: controller.signal }), 5000, {
|
|
52
|
+
* message: 'fetch timed out',
|
|
53
|
+
* onTimeout: () => controller.abort(),
|
|
54
|
+
* });
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
export declare const withTimeout: <T>(promise: Promise<T>, ms: number, options?: {
|
|
58
|
+
message?: string;
|
|
59
|
+
onTimeout?: () => void;
|
|
60
|
+
}) => Promise<T>;
|
|
61
|
+
/**
|
|
62
|
+
* @description: Resolve to a fallback value instead of rejecting when `ms` elapses. For
|
|
63
|
+
* work that has a usable degraded answer — a cached copy, the original file, an empty list
|
|
64
|
+
* — where failing the whole flow on a slow dependency is worse than being approximate.
|
|
65
|
+
*
|
|
66
|
+
* A rejection from `promise` itself still propagates; only the deadline is absorbed.
|
|
67
|
+
*
|
|
68
|
+
* @param {Promise<T>} promise the operation to bound
|
|
69
|
+
* @param {number} ms deadline in milliseconds
|
|
70
|
+
* @param {T} fallback value to resolve with when the deadline passes
|
|
71
|
+
* @param {Function} onTimeout optional cleanup, called when the deadline passes
|
|
72
|
+
* @return {Promise<T>}
|
|
73
|
+
*/
|
|
74
|
+
export declare const withTimeoutFallback: <T>(promise: Promise<T>, ms: number, fallback: T, onTimeout?: () => void) => Promise<T>;
|
|
75
|
+
/**
|
|
76
|
+
* @description: Resolve after `ms` milliseconds. Uses the bare `setTimeout`, so it works in
|
|
77
|
+
* Node, Web Workers and the browser alike.
|
|
78
|
+
* @param {number} ms
|
|
79
|
+
* @return {Promise<void>}
|
|
80
|
+
*/
|
|
81
|
+
export declare const delay: (ms: number) => Promise<void>;
|
|
@@ -1,6 +1,15 @@
|
|
|
1
|
-
export declare const handleClick: (hooks?: (event: MouseEvent) => void) => void;
|
|
2
1
|
/**
|
|
3
|
-
* @description:
|
|
2
|
+
* @description: Listen for every click on the document, in the capture phase so a handler
|
|
3
|
+
* calling `stopPropagation` cannot hide it.
|
|
4
|
+
*
|
|
5
|
+
* Returns an **unsubscribe function**; without one the listener outlives whatever installed it.
|
|
6
|
+
*
|
|
7
|
+
* @param {Function} hooks receives the click event
|
|
8
|
+
* @return {Function} unsubscribe
|
|
9
|
+
*/
|
|
10
|
+
export declare const handleClick: (hooks?: (event: MouseEvent) => void) => (() => void);
|
|
11
|
+
/**
|
|
12
|
+
* @description: Read the device's latitude and longitude (prompts the user for permission)
|
|
4
13
|
* @return {*}
|
|
5
14
|
*/
|
|
6
15
|
export declare const getRegionalLatitudeAndLongitude: () => Promise<GeolocationPosition>;
|
|
@@ -10,6 +19,6 @@ export declare const webglVendor: () => {
|
|
|
10
19
|
} | null;
|
|
11
20
|
export declare const canvasVendor: () => string | null;
|
|
12
21
|
/**
|
|
13
|
-
* @description:
|
|
22
|
+
* @description: Audio fingerprint. 1. Generate an audio stream (triangle wave), run an FFT over it and hash the result with SHA. 2. Generate an audio stream (sine wave), run it through dynamic compression and hash with MD5.
|
|
14
23
|
*/
|
|
15
24
|
export declare const audioVendor: () => Promise<string>;
|