ranuts API(自动生成)
由 bin/generate-api-docs.ts(npm run doc:api)自动生成:按入口点列出每一个导出 符号的签名与一行描述。描述直接提取自源码 JSDoc,因此保持英文。使用指引(该从哪个 入口导入、运行环境约束、约定)请先阅读 CLAUDE.md。
请从符号所属的子路径导入,例如 import { debounce } from 'ranuts/utils'。根入口 ranuts 重新导出 utils + visual 的全部符号。
413 个导出,共 6 个入口点。生成时间 2026-08-18T13:16:54.528Z。
入口点
ranuts/utils— 浏览器与通用工具函数 · 浏览器 + node · 327 个导出ranuts/sw— Service Worker 缓存策略与预缓存协议 · 仅 service worker · 9 个导出ranuts/node— Node 服务端工具(fs / http / ws / 中间件) · 仅 node · 26 个导出ranuts/visual— 2D 渲染引擎(Canvas / WebGL / WebGPU) · 仅浏览器 · 16 个导出ranuts/i18n— 框架无关的 i18n 引擎(也从 ranuts/utils 再导出) · 浏览器 + node · 9 个导出ranuts/vnode— Snabbdom 风格的虚拟 DOM · 浏览器 · 26 个导出
ranuts/utils
浏览器与通用工具函数 · 运行环境:浏览器 + node · 源码:src/utils/index.ts
ts
import { /* … */ } from 'ranuts/utils';函数
acceptPortBridge({ targetOrigin, name, }?: AcceptPortBridgeOptions) => Promise<PortBridge>— Acceptor: wait for the port the initiator hands over and return the bridge once theaddClassToElement(element: Element, addClass: string) => void— Add a class to an elementaddNumSym(value: string | number, flag?: string | number) => stringadoptSheetText(shadowRoot: ShadowRoot, cssText: string, marker?: string) => void— Inject dynamic styles supplied at runtime (a component'ssheetproperty, say).adoptStyles(shadowRoot: ShadowRoot, cssText: string, marker?: string) => void— Inject a component's static styles into a shadow root.appendUrl(url: string, params?: Record<string, string>) => string— Turn an object into a query string and append it to a URLarrayBufferToString(buffer: ArrayBuffer | Uint8Array) => string— Decode bytes into a string using the sniffed encoding. Required when readingautosizeTextarea(element: HTMLTextAreaElement) => (() => void)— Make a<textarea>grow and shrink with its content, so a long message isbase64ToBytes(base64: string) => Uint8Array<ArrayBuffer>— Decode base64 into bytes. Accepts a bare payload or a fullbase64UrlToBytes(value: string) => Uint8Array | null— Decode base64url back into bytes, restoring the padding the encoder dropped.blendMultiply(base: RGB, blend: RGB) => RGB— Multiply blend of two colours (channel-wisebase * blend). Channels in 0..1.blendOverlay(base: RGB, blend: RGB) => RGB— Overlay blend of two colours (multiply in shadows, screen in highlights). Channels in 0..1.blendScreen(base: RGB, blend: RGB) => RGB— Screen blend of two colours (channel-wise1 - (1 - base)(1 - blend)). Channels in 0..1.brightnessContrast(color: RGB, brightness: number, contrast: number) => RGB— Adjust brightness and contrast of a colour:(c - 0.5) * contrast + 0.5 + brightnessper channel. Channels in 0..1.buildOffsets(lengths: readonly number[]) => number[]— The global start offset of every chunk in the concatenated coordinatebytesToBase64(data: Uint8Array | ArrayBuffer) => string— Encode bytes as base64 without blowing the call stack.bytesToBase64Url(data: Uint8Array | ArrayBuffer) => string— Encode bytes as base64url — the URL- and filename-safe alphabet from RFC 4648checkEncoding(uint8Array: Uint8Array) => stringclamp(value: number, min: number, max: number) => number— Clampvalueinto the inclusive range[min, max].clearBr(str?: string) => string— Strip whitespace, line breaks and HTML tags out of a stringclearStr(str: string, options?: ClearStrOption) => string— Trim surrounding whitespace, percent-decode, and drop surrounding quotescloneDeep<T>(value: T, cloneMap?: WeakMap<object, any>) => T— Deep clone, covering the complex built-in types and circular references.componentToHex(c: string | number) => stringcompose<T>(middleware: Array<Middleware<T>>) => ComposedMiddleware<T>— Run a chain of async functions as if it were sequentialcomputePlacement(options: ComputePlacementOptions) => ComputedPlacement— Position a floating panel relative to an anchor rect: flips to the oppositeconcatBytes(chunks: readonly Uint8Array[]) => Uint8Array— Join byte chunks into one buffer, in order.connection() => number | undefined— Current network status: type, throughput, and whether the connection changedconvertImageToBase64(file: File) => Promise<convertImageToBase64Return>— Convert an image to base64cosinePalette(t: number, a: RGB, b: RGB, c: RGB, d: RGB) => RGB— Inigo Quilez cosine gradient palette:a + b * cos(2π(c·t + d)). Each ofa,b,c,dis an RGB triple;tis the position 0..1. Returns an RGB triple.crc32(data: Uint8Array) => number— CRC32 checksum (IEEE 802.3 polynomial), the one ZIP stores per entry.create(tagName: string, options?: ElementCreationOptions) => ChaincreateData(params?: Record<string, unknown>) => Record<string, unknown>— Build the standard envelope that accompanies a report — page URL, referrer,createDocumentFragment(list: Element[]) => DocumentFragment | undefined— Create a DocumentFragmentcreateDoubleTapDetector(options?: DoubleTapDetectorOptions) => DoubleTapDetector— Double-tap detection over raw(x, y, time)samples — pointer-type-agnostic,createHandoff<T>({ dbName, storeName, key }: HandoffOptions) => Handoff<T>— A one-shot value handoff between two pages of the same origin, backed bycreateI18n<TDict extends StringValues<TDict> = MessageDict>(config?: I18nConfig<TDict>) => I18nCore<TDict>— Create and register the global i18n singleton.createLocalePath(config: LocalePathConfig) => LocalePath— Create the set of locale path conversion functions.createObjectURL(src: Blob | ArrayBuffer | Response) => Promise<string>createPortBridge(port: MessagePort) => PortBridge— Build a bridge on any MessagePort (a Web Worker, a SharedWorker, or a port from a completed handshake).createRaceGuard() => RaceGuard— Bump-and-compare guard against a stale async response overwriting a newercreateSignal<T = unknown>(value: T, options?: SignalOptions<T>) => [() => T, (newValue: T) => void]— Create a minimal signal with optional event broadcasting, returned ascreateSpeechRecognizer(options?: SpeechRecognizerOptions) => SpeechRecognizer— Create a dictation session over the Web Speech API.createStore<T>(prefix?: string) => JsonStore<T>— A prefixed, JSON-serialising view over localStorage.createZip(files: ReadonlyArray<{ name: string; data: Uint8Array | string; }>) => Uint8Array— Build a ZIP from scratch, every entry STORED. No compression, so this iscsvEscape(value: string | number) => string— Escape one CSV field: doubles any quote and wraps the value when it containscurrentDevice() => CurrentDevicecutRound(img: ImgSource, radius: number) => ImgSource— Round an image's corners, returning an offscreen canvas.debounce<T extends (...args: any[]) => any>(fn: T, ms?: number) => Debounced<T>— Debounce — on a burst of calls, run only the last one, **msmillisecondsdecodeTextBytes(bytes: Uint8Array, encodings?: string[]) => string— Decode text bytes, trying encodings in order until one holds.deferred<T = void>() => Deferred<T>— A promise plus itsresolve/reject, for the case where the thing thatdelay(ms: number) => Promise<void>— Resolve aftermsmilliseconds. Uses the baresetTimeout, so it works indetectLanguage(text: string, sampleSize?: number) => TextLanguage— Decide a text's primary language from the ratio of CJK to Latin characters.durationHandler<T, U>(handler: (...args: T[]) => U, ...params: T[]) => ((a: number) => Promise<U>)— Run a function repeatedly at a fixed intervalencodeUrl(url: string) => string— Encode a URL to a percent-encoded form, excluding already-encoded sequences.escapeHtml(string?: string | number | null) => stringfanShapedByArc(ctx: CanvasRenderingContext2D, maxRadius: number, start: number, end: number, gutter: number) => void— Trace a pie slice with arc(), including the gutter between slices.fenceCode(body: string, lang?: string) => string— Wrap text in a Markdown code fence long enough to survive backticks inside it.fetchMaybeGzip(input: RequestInfo | URL, init?: RequestInit) => Promise<Uint8Array>— Fetch a resource that may be delivered gzipped or alreadyfilterObj(obj: Record<string, unknown>, list: Array<string>) => Record<string, unknown>— Return a new object without the properties whose values appear inlist— typically used to drop empty strings and nullsfit(value: number, a1: number, a2: number, b1: number, b2: number) => number— Remapvaluefrom[a1, a2]onto[b1, b2]and clamp to the output range — the shaderfit.formatDate(value?: DateInput, pattern?: string) => string— Format a date with a token pattern. Accepts a timestamp, a date string, aformatDuration(seconds: number) => string— Format an elapsed number of seconds as a colon-separated clock duration,formatJson(value: string | object, onError?: (error: Error) => void, indent?: number) => string— Pretty-print JSON. Accepts an object or a JSON string (single quotes areformatRelative(value: DateInput, options?: FormatRelativeOptions) => string— Format a point in time relative to another — "3 days ago", "in 2 hours".getAllQueryString(url?: string) => Record<string, string>— Parse a URL's query string into an object. Defaults to the currentgetAngle(deg: number) => number— Degrees to radiansgetArcPointerByDeg(deg: number, r: number) => [number, number]— The point on a circle at a given anglegetCookie(objName: string) => string— Read a named cookiegetCookieByName(name: string) => stringgetExtensions(mimeType: string) => string[]— Get file extensions from MIME typegetFrame(n?: number) => Promise<number>— Frames per millisecond; multiply by 1000 for frames per secondgetImage(src: string) => Promise<ImgSource>— Load an image by path, resolving once it has decoded.getLinearGradient(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, background: string) => CanvasGradient— Translate a CSSlinear-gradient(...)string into a Canvas CanvasGradient.getMatchingSentences(text: string, searchValue: string) => string[]— Collect the complete sentences of a text that contain the search term, keeping only thegetMatrix(radius: number, sigma?: number) => number[]— Build a 2D Gaussian weight matrix, normalised so the weights sum to 1.getMime(ext: string) => string | undefinedgetPerformance() => BasicType | undefinedgetPixelRatio(context: CanvasRenderingContext2D & Partial<Context>) => number— Get the device pixel ratiogetRandomString(len?: number) => string— A short random-ish base-36 string.getReportUrl() => string— The currently configured reporting endpoint, or''when none was setgetStatus(code?: number | string) => number | string | undefined— Get the status code.getTangentByPointer(x: number, y: number) => Array<number>— The tangent line at a point on a circlegetWindow() => ClientRatio— Get the viewport size across browsersgunzipMaybe(bytes: Uint8Array) => Promise<Uint8Array>— Decompress bytes if — and only if — they are still gzipped.handleConsole(hooks?: (...args: unknown[]) => void) => (() => void)— Tap intoconsoleso every call also reaches your hook, while still printinghandleError(hooks?: (error: ErrorPayload) => void) => (() => void)— Listen for uncaught errors and unhandled promise rejections, in the capturehandleFetchHook(options?: Partial<Options>) => (() => void)— Instrumentwindow.fetchso every request, response and failure reaches yourhandleXhrHook(options?: Partial<Options>) => (() => void)— InstrumentXMLHttpRequest(open/send) so requests, responses andhexToAlpha(aa: string) => number— A two-digit hex alpha channel (ff/80/00) to a 0–100 percentage.hexToHsb(hex: string) => number[] | null—#rrggbb/#rgbto[h, s, b]; null when the hex is invalid.hexToHsv(hex: string) => number[] | nullhexToRgb(hex: string) => Array<number> | null—#rrggbb/#rgb(with or without the#) to[r, g, b]; null when it cannot be parsed.hsbToHsl(h: number, s: number, b: number) => number[]hsbToRgb(h: number, s: number, v: number) => number[]hslToHsb(h: number, s: number, l: number) => number[]—[h, s, l]to[h, s, b]hslToHsv(h: number, s: number, l: number) => number[]hslToRgb(h: number | string | number[], s: number | string, l: number | string) => Array<number>hsvToHsl(h: number, s: number, b: number) => number[]hsvToRgb(h: number, s: number, v: number) => number[]hue2rgb(p: number, q: number, t: number) => numberimageRequest(url?: string) => Promise<number>— Request an image (used to time the network)indexForOffset(offsets: readonly number[], offset: number) => number— Binary-search which chunk a global offset falls into — the last indexinflateRaw(data: Uint8Array) => Promise<Uint8Array>— Decompress raw DEFLATE bytes (no zlib or gzip wrapper) — the form ZIPinverseLerp(a: number, b: number, value: number) => number— Inverse oflerp— wherevaluesits betweenaandb, as 0..1. Returns 0 whena === b. Not clamped.isEqual(value: any, other: any, seen?: Map<any, any>) => boolean— Deep-compare two values.isGzip(bytes: Uint8Array) => boolean— Whether the bytes start with the gzip magic number (1f 8b).isHtmlDocument(bytes: Uint8Array) => boolean— Whether the bytes are an HTML document rather than the binaryisImageSize(file: File, width?: number, height?: number) => Promise<boolean>— Check an image's dimensions against a given width / height. When both areisInIframe() => boolean— Whether this page is running inside an iframe. Returns false under SSR.isMobile() => boolean— Whether this is a mobile deviceisSafari() => boolean | undefined | stringisSpeechRecognitionSupported() => boolean— Whether this runtime can recognize speech. Checked at call time, so it is safeisString(obj: unknown) => booleanisUrlCached(url: string) => Promise<boolean>— Whether a URL is already in CacheStorage. When probing a group of files,isWeiXin() => boolean— Whether this is the WeChat in-app browserisZipContainer(bytes: Uint8Array) => boolean— Whether the bytes are a ZIP container (PK\x03\x04) — which islerp(a: number, b: number, t: number) => number— Linear interpolation fromatobbyt(t=0 → a, t=1 → b). Not clamped.linearstep(edge0: number, edge1: number, x: number) => number— Linear ramp — 0 belowedge0, 1 aboveedge1, a straight line between (the shaderlinearstep, no smoothing).linearToSrgb(c: number) => number— Convert one linear-light channel (0..1) to sRGB.loadScript({ type, content }: LoadScriptOptions) => Promise<{ success: boolean; }>— Inject one script dynamically, de-duplicated by content.localStorageGetItem(name: string) => string— Read a string from localStorage, or''when missing or unavailable.localStorageRemoveItem(name: string) => void— Remove a key from localStorage. Silently does nothing when storage is unavailable.localStorageSetItem(name: string, value: string) => void— Write a string to localStorage. Silently does nothing when storage isluma(r: number, g: number, b: number) => number— Perceived brightness (luma) of an RGB colour using Rec. 601 weights. Channels may be 0..1 or 0..255 — the result keeps that scale.matchMediaQuery(query: string) => boolean— Read whether a media query currently matches, synchronously. Returns false under SSR.mathjs(a: number, type: string, b: number) => ComputeNumberResultmd5(str: string) => string— MD5 hash function implementationmemoize<T extends Func>(fn: T | unknown) => ((...args: Parameters<T>) => ReturnType<T>)— Former name ofonce. The name is misleading — it does not cache permerge(a: Obj, b?: Obj) => Obj— Merge objectsmergeExports(obj: Record<string, string>, exports: Record<string, string>) => Record<string, string>— Copy an exports object ontoobj, then freeze itnavigatorLanguage() => TextLanguage— Map the browser UI language into the same buckets (the default when there isnetworkAllowsDownload(options?: NetworkAllowanceOptions) => boolean— Whether the current network and user settings allow proactively downloadingnetworkSpeed(options: Options) => Promise<ReturnType>— Measure the network's ping by timing requestsnoop() => voidonce<T extends Func>(fn: T | unknown) => ((...args: Parameters<T>) => ReturnType<T>)— Run once — evaluate on the first call, cache the result, and return thatopacity(img: ImgSource, opacity: number) => ImgSource— Apply an overall opacity to an image, returning an offscreen canvas.openPortBridge({ targetWindow, targetOrigin, name, }: OpenPortBridgeOptions) => PortBridge— Initiator: create a MessageChannel, hand one port to the target window and keep the other.paginateText(text: string, box: TextBox, metrics: TextGridMetrics, options?: PaginateOptions) => PaginateResult— Cut text into pages that fitbox, given the type metrics.parseChineseNumber(value: string) => number | null— Chinese numerals to Arabic, covering 「十五」「二十三」「一百零三」「一千零一」「三万」.parseEnglishNumber(value: string) => number | null— English ordinals to numbers, tried in order: Arabic digits, number wordsparseRomanNumber(value: string) => number | null— Roman numerals to Arabic (either case, handling subtractive forms such as IV / IX). Returns null for invalid input.parseVttCueTiming(line: string) => { start: number; end: number; } | undefined— Parse a WebVTT cue timing line —<start> --> <end>, optionally followed byparseVttTimestamp(raw: string) => number | undefined— Parse a WebVTT/SRT-style timestamp —HH:MM:SS.mmmorMM:SS.mmm(the hourperformanceTime() => number— Current timestampperToNum(str?: string) => number— Convert a percentage string into a numberprefetchUrl(url: string) => Promise<void>— Pull a single URL into the cache; skipped when already cached. Failures areprefetchUrls(urls: string[], options?: PrefetchOptions) => Promise<void>— Prefetch a group of URLs, serially — prefetching is background work, andprefetchWhenIdle(urls: string[], options?: WhenIdleOptions & NetworkAllowanceOptions & PrefetchOptions) => (() => void)— Prefetch a group of URLs while idle, subject tonetworkAllowsDownload.queryFlag(key: string, url?: string) => boolean— Read a query parameter as a boolean flag. True for?k,?k=,?k=1andquerystring(data?: {}) => string— Serialise an object into a URL query stringrandomColor() => ColorrandomString(len?: number) => string— A short random-ish string prefixed with the current timestamp.range(num: number, min?: number, max?: number) => number— Clamp a value between a minimum and a maximumreadFileAsArrayBuffer(blob: Blob) => Promise<ArrayBuffer>— Read a File / Blob as an ArrayBufferreadFileAsDataURL(blob: Blob) => Promise<string>— Read a File / Blob as a data: URL (image previews and the like)readFileAsText(blob: Blob, encoding?: string) => Promise<string>— Read a File / Blob as textreadFileAsUint8Array(blob: Blob) => Promise<Uint8Array<ArrayBuffer>>— Read a File / Blob as a Uint8Array (pair with checkEncoding / arrayBufferToString for encoding sniffing)readZipEntries(bytes: Uint8Array) => ZipEntry[]— Read an archive's central directory. Returns[]for anything that is notreadZipEntry(bytes: Uint8Array, entry: string | ZipEntry) => Promise<Uint8Array | null>— Extract one entry's decompressed bytes. Resolvesnullwhen the entry isremap(value: number, a1: number, a2: number, b1: number, b2: number) => number— Linearly remapvaluefrom range[a1, a2]onto[b1, b2]. Not clamped (GLSL-style map).removeClassToElement(element: Element, removeClass: string) => void— Remove a class from an elementreplaceOld(source: any, name: string, replacement: (...args: unknown[]) => unknown, isForced?: boolean) => () => void— Replace a property on an object, wrapping whatever was there before.report({ url, type, payload }: BeaconPayload) => boolean— Send a telemetry beacon. Prefersnavigator.sendBeacon(does not blockrequestUrlToBuffer(src: string, options: Partial<RequestUrlToArraybufferOption>) => Promise<requestUrlToArraybufferReturn>— Fetch a URL as an ArrayBufferresolveLocale(options: ResolveLocaleOptions) => string— Resolve which of your supported locales to use, from the usual chain:rewriteZip(bytes: Uint8Array, options?: RewriteZipOptions) => Promise<Uint8Array>— Rebuild an archive with some entries replaced and/or new entries appended.rgbaString(r: number, g: number, b: number, a: number) => string— Build a CSSrgba()string. Alpha is 0–100 rather than 0–1, matching thergbaToHex(r: number, g: number, b: number, a: number) => string— Composite a translucent colour over white and return it as a 6-digit hex.rgbaToRgb(r: number, g: number, b: number, a: number) => number[]— Composite a translucent colour over white, giving the equivalent opaque rgb.rgbToHex(r: string | number | Array<string | number>, g?: string | number, b?: string | number) => stringrgbToHsb(r: number, g: number, b: number) => number[]rgbToHsl(r: number | number[], g?: number, b?: number) => Array<number>rgbToHsv(r: number, g: number, b: number) => number[]— Alias ofrgbToHsb— HSV and HSB are two names for the same colour space.roundRectByArc(ctx: CanvasRenderingContext2D, ...[x, y, w, h, r]: number[]) => void— Trace a rounded rectangle with arc(). A corner radius larger than half thesafeEqual(a: string | Uint8Array, b: string | Uint8Array) => boolean— Compare two secrets in time that does not depend on where they first differ.saturation(color: RGB, amount: number) => RGB— Adjust saturation by mixing toward the colour's luminance.amount0 = greyscale, 1 = unchanged, >1 = more saturated. Channels in 0..1.saveFileToDisk(data: Blob | Uint8Array, fileName: string, options?: SaveFileOptions) => Promise<boolean>— Save bytes to disk: a real "Save as" dialog through the FilescriptOnLoad(urls: string[], append?: HTMLElement, callback?: () => void) => Promise<void>— Insert script/link tags dynamicallysecureRandomString(length: number, alphabet?: string) => string— A random string drawn fromalphabetusing the platform CSPRNG.secureToken(bytes?: number) => string— A random hex token ofbytesbytes, from the platform CSPRNG.segmentByRanges<T>(text: string, chunkStart: number, ranges: readonly OffsetRange<T>[]) => Segment<T>[]— Split one chunk of text into a sequence of plain / matched spans accordingserveWorker<Req extends WorkerRequestBase, Res extends object = object, Progress = unknown>(handler: (request: Req, context: WorkerHandlerContext<Progress>) =>…— Serve requests inside a Web Worker, mirroring {@link WorkerClient} on thesetFontSize2html(designWidth?: number) => void— Set the root font size from the design mock's widthsetMime(ext: string, mimeType: string) => Map<string, string>setReportUrl(next: ReportConfig | string) => void— Configure the default reporting endpoint (and optionally the cookie holdingsingleFlight<T>(fn: () => Promise<T>) => SingleFlight<T>— The async flavour of "run once": concurrent callers share one in-flightslugify(text: string, maxLength?: number) => string— Reduce text to a lowercasea-z0-9-slug, safe as a filename on everysmoothstep(edge0: number, edge1: number, x: number) => number— Smooth Hermite interpolation between 0 and 1 foredge0 < x < edge1(GLSLsmoothstep).srgbToLinear(c: number) => number— Convert one sRGB channel (0..1) to linear-light (IEC 61966-2-1 transfer function).strParse(str?: string, sep?: string | RegExp, eq?: string | RegExp) => Record<string, string>— Parse a delimited string into an object, e.g.throttle<T extends (...args: any[]) => any>(fn: T, delay?: number) => Throttled<T>— Throttle — under a burst of calls, run at a fixed interval: the first calltimeFormat(time: number) => string— Format a number of seconds as a colon-separated durationtimestampToTime(timestamp?: number | string) => Date & { format?: Function; }— Turn a timestamp into aDatecarrying aformatmethod.toFullWidth(value: string) => string— Convert half-width characters to full-width (the inverse oftoHalfWidth)toHalfWidth(value: string) => string— Convert full-width characters to half-width (digits, letters, punctuation andtoString(value: string | number) => stringtransformNumber(value: string, locale?: string, precision?: number, fixed?: number) => stringtransformText(content: string | ArrayBuffer) => TransformText | undefinedtruncate(value: string, options: TruncateOptions | number) => string— Shorten a string to a maximum length, marking the cut with an ellipsis.truncateWithMarker(text: string, max: number, marker?: string) => string— Cut text tomaxcharacters and mark that it was cut.useI18n<TDict extends StringValues<TDict> = MessageDict>() => I18nCore<TDict> | null— The active global instance, or null when none was created. Pass the samevibrance(color: RGB, amount: number) => RGB— Vibrance — saturates muted colours more than already-saturated ones.amount> 0 boosts, < 0 mutes. Channels in 0..1.watchMediaQuery(query: string, callback: (matches: boolean) => void) => (() => void)— Watch a media query. The callback **fires once synchronously with thewhenIdle(callback: () => void, options?: WhenIdleOptions) => (() => void)— Run a callback while the browser is idle, falling back to setTimeout wherewithTimeout<T>(promise: Promise<T>, ms: number, options?: { message?: string; onTimeout?: () => void; }) => Promise<T>— Reject if a promise has not settled withinms. The returned promisewithTimeoutFallback<T>(promise: Promise<T>, ms: number, fallback: T, onTimeout?: () => void) => Promise<T>— Resolve to a fallback value instead of rejecting whenmselapses. ForzipHasEntry(bytes: Uint8Array, name: string) => boolean— Whether the archive contains an entry with exactly this name. Cheaper than
类
class AudioRecorder— Record audioclass BridgeManagerclass Chain— Chainable DOM operationsclass Colorclass ColorSchemeclass EventManager— EventManager — a scoped listener registry built on AbortController.class Hslclass Hslaclass I18nCore— The engine. Optionally parameterised by your dictionary shape.class Mathjs— Arithmetic that works around floating-point precision.class Monitor— Front-end telemetry: page-load performance, clicks, errors, fetch/XHR trafficclass PostMessageBridge— Bridge registration event, consumed by the clientclass QuestQueue— An async task queue with limited concurrency. At mostsimultaneoustasksclass Rgbclass Rgbaclass SyncHookclass TimeoutErrorclass TOTPclass WebDB— A Promise wrapper over IndexedDB. The native API is event-callback andclass WorkerClient— A worker client with request ids. The request typeReqis defined by the
接口
interface AcceptPortBridgeOptionsinterface BeaconPayloadinterface BridgeManagerOptionsinterface BroadcastPayloadinterface CallToPayloadinterface ComputedPlacementinterface ComputePlacementOptionsinterface Debouncedinterface Deferred— Promise primitives that JavaScript does not ship: an externally settled promise and ainterface DoubleTapDetectorinterface DoubleTapDetectorOptionsinterface FormatRelativeOptionsinterface Handoffinterface HandoffOptionsinterface I18nConfiginterface IDBCollection— A store name bound once, values unwrapped, failures folded into the empty caseinterface IDBResult— The uniform result shape of every IndexedDB operation. Every methodinterface IDBStoreSchema— Declarative schema for object stores.openDataBasecreates the missinginterface JsonStoreinterface LoadScriptOptionsinterface LocalePathinterface LocalePathConfiginterface LocaleRoute— URL maths for a multi-language site (pure functions, no global state, no DOM).interface MessageDatainterface MessageHandlerinterface NetworkAllowanceOptionsinterface OffsetRange— An annotation in global coordinates: the half-open interval[start, end)plus any payloadinterface OpenPortBridgeOptionsinterface PaginateOptionsinterface PaginateResultinterface PendingRequestinterface PlacementRectinterface PortBridge— A point-to-point bridge over MessagePort.interface PrefetchOptionsinterface RaceGuardinterface ReportConfiginterface ResolveLocaleOptionsinterface RewriteZipOptionsinterface Segment— One piece of the split result:value === nullmarks a plain span covered by no rangeinterface ServeWorkerOptionsinterface SingleFlightinterface SpeechErrorinterface SpeechRecognizerinterface SpeechRecognizerOptionsinterface SpeedType— The ease-in / ease-out pair of one easing familyinterface TextBox— The box each page must fit into, in px.interface TextGridMetricsinterface TextPageinterface Throttledinterface TransformTextinterface TruncateOptionsinterface WebDBOptionsinterface WhenIdleOptionsinterface WorkerClientOptionsinterface WorkerHandlerContext— Handed to the handler so it can stream progress for the request it is currently servinginterface WorkerRequestBase— A request always carries the id the client stamped on itinterface WorkerResponseBase— A response must at least echo the request id so the two can be pairedinterface ZipEntry— One entry as described by the archive's central directory.
类型
type CurrentDevicetype DateInput— Accepted everywhere a moment in time is taken;undefinedmeans "now".type EasingFn— One easing function: (elapsed, from, delta, duration) => current valuetype ImgSource— A bitmap container usable both as a drawImage source and as a render targettype LocaleChangeHandlertype LocaleMessages— Locale → dictionary. Parameterised by the dictionary shape so an app can hand in its owntype MessageDicttype Placementtype RelativeStyle—'compact'is ours; the other three areIntl.RelativeTimeFormatstyles.type RGB— An RGB triple with each channel in 0..1 (linear or sRGB depending on the operation).type SpeechErrorKind—deniedmeans the user or the browser refused the microphone — worth surfacing.type StringValues— "An object whose values are all strings" — the constraint the dictionary type parametertype TextLanguage— Coarse language bucket: Chinese / English / other onlytype TranslateParamstype TruncatePosition— Which end of the string gets dropped when it is too long.
常量
const ADOPTED_SHEET_MARKER: "data-adopted-sheet"const ADOPTED_STYLE_MARKER: "data-adopted-style"— Default marker attribute on the<style>fallback, identifying styles this module injectedconst BRIDGE_MARKER: "__ranuts_bridge__"const bridgeManager: BridgeManagerconst circ: SpeedTypeconst Client: { connect: ({ id, targetWindow, targetOrigin, channel, }: BridgeManagerOptions) => { bridge: PostMessageBridge; id: string; }; remove: (id: strin…const cubic: SpeedTypeconst DEFAULT_CHANNEL: "default"const expo: SpeedTypeconst FMT: Record<string, string[]>const HEX_COLOR_REGEX: RegExp—#rgb/#rrggbb(the#is required)const isClient: boolean— Whether awindowexisted when this module was first imported.const MessageCodec: { encode(data: any): string; decode<T = any>(encodedStr: string): T | null; encodeFile(file: File): Promise<string>; decodeFile(encoded: st…— Message codec.const MimeType: Map<string, string>const MOBILE_MEDIA_QUERY: "(max-width: 768px)"— Viewport breakpoint, matching where the mobile layout takes overconst Platform: { init: <T = unknown, R = unknown>(events: Record<string, MessageHandler<T, R>>) => { destroy: () => void; }; }const quad: SpeedTypeconst quart: SpeedTypeconst quint: SpeedTypeconst RGB_REGEX: RegExp—rgb(r,g,b), no spaces — strip whitespace before matchingconst RGBA_REGEX: RegExp—rgba(r,g,b,a), no spaces — strip whitespace before matchingconst sine: SpeedTypeconst status: { message: Map<number, string>; code: Map<string, number>; codes: number[]; redirect: { 300: boolean; 301: boolean; 302: boolean; 303: boolean; 3…const subscribers: SyncHook— Global event bus: a signal carrying asubscriberbroadcasts through it on changeconst UNAMBIGUOUS_ALPHABET: "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"— Unambiguous by design: no0/O, no1/l/I. For codes a human reads aloud or retypes.const ZIP_DEFLATE: 8const ZIP_STORED: 0— Compression methods this module understands.
ranuts/sw
Service Worker 缓存策略与预缓存协议 · 运行环境:仅 service worker · 源码:src/sw/index.ts
ts
import { /* … */ } from 'ranuts/sw';函数
cacheFirst(request: Request, options: CacheStrategyOptions) => Promise<Response>— Cache-first: serve the stored copy when there is one, otherwise fetch anddropCachesExcept(keep: readonly string[], options?: { scope?: SWScope; }) => Promise<string[]>— Delete every cache except the ones named. Call it onactivateso a newnetworkFirst(request: Request, options: CacheStrategyOptions) => Promise<Response>— Network-first: go to the network, store what comes back, and fall back to theprecache(cacheName: string, urls: readonly string[], options?: { scope?: SWScope; }) => Promise<void>— Fill a cache with a list of URLs, skipping what is already there. Failures areservePrecache(options: ServePrecacheOptions) => (() => void)— Answer the precache messages thatprefetchUrls({ serviceWorkerMessage })
接口
interface CacheStrategyOptionsinterface PrecacheMessageEvent— The bit ofExtendableMessageEventused here, declared locally rather than pulled frominterface ServePrecacheOptionsinterface SWScope— Minimal view of the SW global the helpers touch, so they can be unit-tested with a stub.
ranuts/node
Node 服务端工具(fs / http / ws / 中间件) · 运行环境:仅 node · 源码:src/node/index.ts
ts
import { /* … */ } from 'ranuts/node';函数
appendFile(path: string, content: string) => Promise<Ranuts.Identification>— Append content to an existing filebodyMiddleware(options?: Partial<ServerBody>) => MiddlewareFunctionconnect(connectMiddleware: ConnectMiddleware) => MiddlewareFunctionget({ url }: Request) => Promise<Response>getIPAdress() => string | undefineddefault(req: Req) => ParseUrl | undefined— Parse an IncomingMessage's request URL; the return type is always ParseUrlprompt({ message, stream, defaultResponse }: PromptOption) => Promise<boolean>queryFileInfo(path: string) => Promise<Ranuts.Identification>— Stat a file — typically to tell a file from a directory via data.isDirectory()readDir(options: Options) => Array<string>readFile(path: string, format?: BufferEncoding) => FilePromiseResult— Read a file, returning a status code and the content on successreadStream(option: ReadOption) => ReadStreamrunCommand(command: string, args: string[]) => Promise<void>startTask() => symbolstaticMiddleware(option?: Partial<Option>) => MiddlewareFunctiontaskEnd(symbol: symbol) => number | biginttraverse(dir: string, callback: Caller, pre?: string) => Promise<any>— Walk every directory recursively, running a function for each file foundtraverseSync(dir: string, callback: Caller, pre?: string) => void— Synchronous: walk every directory recursively, running a function for each file foundwatchFile(path: string, interval?: number) => Promise<Ranuts.Identification>— Watch a file for changes and report its statuswriteFile(path: string, content: string) => Promise<Ranuts.Identification>— Write a file at the given path, truncating it if it exists and creating it if it does notwriteStream(option: WriteOption) => WriteStreamWSS(this: any, server: http.Server) => void— Create a WebSocket Server
类
class Routerclass Server
接口
interface Context
常量
const isColorSupported: boolean
其他
default
ranuts/visual
2D 渲染引擎(Canvas / WebGL / WebGPU) · 运行环境:仅浏览器 · 源码:src/utils/visual/index.ts
ts
import { /* … */ } from 'ranuts/visual';类
class Applicationclass ColorAdjustFilter— A ready-made colour-grade filter: brightness, contrast and saturation. Mirrors theclass Containerclass Filter— A full-screen post-processing pass. Sample the previous pass throughu_texture(andclass Graphicsclass WebGLRenderTarget
接口
interface ColorAdjustOptionsinterface IApplicationOptionsinterface IFillStyleOptionsinterface ILineStyleOptions
枚举
enum LINE_CAPenum LINE_JOINenum RENDERER_TYPEenum SHAPE_TYPE
常量
const BYTES_PER_VERTEX: 12const MAX_VERTEX_COUNT: 65536
ranuts/i18n
框架无关的 i18n 引擎(也从 ranuts/utils 再导出) · 运行环境:浏览器 + node · 源码:src/utils/i18n.ts
ts
import { /* … */ } from 'ranuts/i18n';函数
createI18n<TDict extends StringValues<TDict> = MessageDict>(config?: I18nConfig<TDict>) => I18nCore<TDict>— Create and register the global i18n singleton.useI18n<TDict extends StringValues<TDict> = MessageDict>() => I18nCore<TDict> | null— The active global instance, or null when none was created. Pass the same
类
class I18nCore— The engine. Optionally parameterised by your dictionary shape.
接口
interface I18nConfig
类型
type LocaleChangeHandlertype LocaleMessages— Locale → dictionary. Parameterised by the dictionary shape so an app can hand in its owntype MessageDicttype StringValues— "An object whose values are all strings" — the constraint the dictionary type parametertype TranslateParams
ranuts/vnode
Snabbdom 风格的虚拟 DOM · 运行环境:浏览器 · 源码:src/vnode/index.ts
ts
import { /* … */ } from 'ranuts/vnode';函数
addNS(data: VNodeData, children: Array<VNode | string | number> | undefined, sel: string | undefined) => voidcreate(tagName: string, options?: ElementCreationOptions) => Chainh{ (sel: string): VNode; (sel: string, data: VNodeData | null): VNode; (sel: string, children: VNodeChildren): VNode; (sel: string, data: VNodeData | null, chi… (+3 overloads)init() => (oldVnode: VNode | Element, vnode: VNode) => VNodevnode(sel: string | undefined, data: any | undefined, children: Array<VNode | string | number> | undefined, text: string | number | undefined, elm: Element | T…
类
class Chain— Chainable DOM operations
接口
interface DOMAPIinterface Fragmentinterface Hooksinterface VNodeinterface VNodeData
类型
type ArrayOrElementtype Keytype ModuleHooktype Modulestype VNodeChildElementtype VNodeChildrentype VNodes
常量
const attributesModule: { create: (oldVnode: VNode, vnode: VNode) => void; update: (oldVnode: VNode, vnode: VNode) => void; }const classModule: { create: (oldVnode: VNode, vnode: VNode) => void; update: (oldVnode: VNode, vnode: VNode) => void; }const eventListenersModule: { create: (oldVnode: VNode, vnode?: VNode) => void; update: (oldVnode: VNode, vnode?: VNode) => void; destroy: (oldVnode: VNode, vn…const htmlDomApi: DOMAPIconst modules: Modulesconst propsModule: { create: (oldVnode: VNode, vnode: VNode) => void; update: (oldVnode: VNode, vnode: VNode) => void; }const styleModule: { pre: () => void; create: (oldVnode: VNode, vnode: VNode) => void; update: (oldVnode: VNode, vnode: VNode) => void; destroy: (vnode: VNode)…
命名空间
namespace is— Type guards — array / string / primitive / VNode