import { AsyncVoidIOResult, AsyncIOResult, VoidIOResult, IOResult, AsyncResult } from 'happy-rusty'; import { FetchInit, FetchTask } from '@happy-ts/fetch-t'; export { ABORT_ERROR, FetchError, FetchTask, TIMEOUT_ERROR } from '@happy-ts/fetch-t'; import * as happyOpfs from 'happy-opfs'; import { FsRequestInit, UploadRequestInit, ZipFromUrlRequestInit, AppendOptions, DownloadFileTempResponse, ExistsOptions, WriteOptions, ZipOptions } from 'happy-opfs'; export { DecodeBase64Options, EncodeBase64Options, decodeBase64, decodeByteString, decodeHex, encodeBase64, encodeByteString, encodeHex } from 'happy-codec'; /** * 播放音频的选项。 * @since 1.5.0 * @example * ```ts * import { audio } from 'minigame-std'; * * // 循环播放 * const source = audio.playWebAudioFromAudioBuffer(buffer, { loop: true }); * * // 禁用自动断开连接 * const source2 = audio.playWebAudioFromAudioBuffer(buffer, { autoDisconnect: false }); * ``` */ interface PlayOptions { /** * 是否循环播放。 * @defaultValue `false` */ loop?: boolean; /** * 播放完后是否自动调用 `source.disconnect`。 * @defaultValue `true` */ autoDisconnect?: boolean; } /** * Web/小游戏 平台的音频播放实现。 */ /** * 获取缓存的 AudioContext。 * @returns 返回缓存的 AudioContext。 * @since 1.5.0 * @example * ```ts * const context = audio.getGlobalAudioContext(); * ``` */ declare function getGlobalAudioContext(): AudioContext; /** * 关闭缓存的 AudioContext。 * @returns 返回一个 AsyncVoidIOResult。 * @since 1.5.0 * @example * ```ts * await audio.closeGlobalAudioContext(); * ``` */ declare function closeGlobalAudioContext(): AsyncVoidIOResult; /** * 创建一个 AudioContext。 * 如果要获取缓存的实例,请使用 `getGlobalAudioContext`。 * @returns 返回一个 AudioContext实例。 * @since 1.5.0 * @example * ```ts * const context = audio.createWebAudioContext(); * ``` */ declare function createWebAudioContext(): AudioContext; /** * 播放一个 AudioBuffer。 * @param buffer - 解码后的 AudioBuffer。 * @param options - 播放选项。 * @returns 正在播放的 AudioBufferSourceNode。 * @since 1.5.0 * @example * ```ts * const source = audio.playWebAudioFromAudioBuffer(audioBuffer, { loop: true }); * ``` */ declare function playWebAudioFromAudioBuffer(buffer: AudioBuffer, options?: PlayOptions): AudioBufferSourceNode; /** * 使用 Buffer 进行解码播放。 * @param buffer - 需要解码的 Buffer。 * @param options - 播放选项。 * @returns 正在播放的 AudioBufferSourceNode。 * @since 1.5.0 * @example * ```ts * const result = await audio.playWebAudioFromBufferSource(buffer); * if (result.isOk()) { * const source = result.unwrap(); * } * ``` */ declare function playWebAudioFromBufferSource(buffer: BufferSource, options?: PlayOptions): AsyncIOResult; /** * 读取文件并播放。 * @param filePath - 文件路径。 * @param options - 播放选项。 * @returns 正在播放的 AudioBufferSourceNode。 * @since 1.5.0 * @example * ```ts * const result = await audio.playWebAudioFromFile('/path/to/audio.mp3'); * if (result.isOk()) { * const source = result.unwrap(); * } * ``` */ declare function playWebAudioFromFile(filePath: string, options?: PlayOptions): AsyncIOResult; /** * 音频相关功能模块,提供 Web Audio API 封装。 * @module audio */ type mod$9_PlayOptions = PlayOptions; declare const mod$9_closeGlobalAudioContext: typeof closeGlobalAudioContext; declare const mod$9_createWebAudioContext: typeof createWebAudioContext; declare const mod$9_getGlobalAudioContext: typeof getGlobalAudioContext; declare const mod$9_playWebAudioFromAudioBuffer: typeof playWebAudioFromAudioBuffer; declare const mod$9_playWebAudioFromBufferSource: typeof playWebAudioFromBufferSource; declare const mod$9_playWebAudioFromFile: typeof playWebAudioFromFile; declare namespace mod$9 { export { mod$9_closeGlobalAudioContext as closeGlobalAudioContext, mod$9_createWebAudioContext as createWebAudioContext, mod$9_getGlobalAudioContext as getGlobalAudioContext, mod$9_playWebAudioFromAudioBuffer as playWebAudioFromAudioBuffer, mod$9_playWebAudioFromBufferSource as playWebAudioFromBufferSource, mod$9_playWebAudioFromFile as playWebAudioFromFile }; export type { mod$9_PlayOptions as PlayOptions }; } /** * 剪贴板操作模块,提供读取和写入剪贴板文本的功能。 * @module clipboard */ /** * 异步写入文本数据到剪贴板。 * @param data - 需要写入的文本数据。 * @returns 写入操作的结果。 * @since 1.0.0 * @example * ```ts * const result = await writeText('Hello, World!'); * if (result.isOk()) { * console.log('文本已复制到剪贴板'); * } else { * console.error('复制失败:', result.unwrapErr()); * } * ``` */ declare function writeText(data: string): AsyncVoidIOResult; /** * 异步读取剪贴板文本数据。 * @returns 读取操作的结果。 * @since 1.0.0 * @example * ```ts * const result = await readText(); * if (result.isOk()) { * console.log('剪贴板内容:', result.unwrap()); * } else { * console.error('读取失败:', result.unwrapErr()); * } * ``` */ declare function readText(): AsyncIOResult; declare const mod$8_readText: typeof readText; declare const mod$8_writeText: typeof writeText; declare namespace mod$8 { export { mod$8_readText as readText, mod$8_writeText as writeText, }; } /** * Codec 模块:提供各种编码/解码功能。 * 除了 UTF-8 编码/解码功能外,其余编码/解码功能直接从 `happy-codec` 包中导出。 * * @module codec */ /** * 将字符串数据编码为 `Uint8Array`(UTF-8 编码)。 * @param data - 需要编码的字符串数据。 * @returns 编码后的 `Uint8Array`。 * @since 1.0.0 * @example * ```ts * const encoded = encodeUtf8('你好'); * console.log(encoded); // Uint8Array [228, 189, 160, 229, 165, 189] * ``` */ declare function encodeUtf8(data: string): Uint8Array; /** * 将二进制数据解码为字符串(UTF-8 解码)。 * @param data - 需要解码的二进制数据。 * @param options - 解码选项(可选)。 * @param options.fatal - 如果为 `true`,遇到无效的 UTF-8 序列会抛出异常;如果为 `false`(默认),使用替换字符 U+FFFD 代替。 * @param options.ignoreBOM - 如果为 `true`,保留字节顺序标记(BOM);如果为 `false`(默认),自动删除 BOM。 * @returns 解码后的字符串。 * @throws {TypeError} 当 `options.fatal` 为 `true` 且输入包含无效的 UTF-8 序列时。 * @since 1.0.0 * @example * ```ts * // 基本用法 * const decoded = decodeUtf8(new Uint8Array([228, 189, 160, 229, 165, 189])); * console.log(decoded); // '你好' * * // 使用 fatal 选项处理无效字节 * const withReplacement = decodeUtf8(new Uint8Array([0xff, 0xfe])); * console.log(withReplacement); // '��'(使用替换字符) * * // 使用 ignoreBOM 选项保留 BOM * const withBOM = new Uint8Array([0xef, 0xbb, 0xbf, 0x48, 0x69]); // BOM + 'Hi' * decodeUtf8(withBOM); // 'Hi'(删除 BOM) * decodeUtf8(withBOM, { ignoreBOM: true }); // '\uFEFFHi'(保留 BOM) * ``` */ declare function decodeUtf8(data: BufferSource, options?: TextDecoderOptions): string; /** * 公共类型定义模块。 * * @module defines */ /** * 数据源类型,可以是 string 或者 BufferSource。 * @since 1.8.0 * @example * ```ts * // 字符串类型 * const strData: DataSource = 'Hello, World!'; * * // ArrayBuffer 类型 * const bufferData: DataSource = new ArrayBuffer(8); * * // Uint8Array 类型 * const u8aData: DataSource = new Uint8Array([1, 2, 3]); * ``` */ type DataSource = string | BufferSource; /** * RSA 公钥接口,用于加密数据。 * @since 1.6.0 * @example * ```ts * import { cryptos } from 'minigame-std'; * * const publicKey = (await cryptos.rsa.importPublicKey(pemString, 'SHA-256')).unwrap(); * * // 加密并返回 ArrayBuffer * const encrypted = (await publicKey.encrypt('Hello, World!')).unwrap(); * * // 加密并返回 Base64 字符串 * const encryptedStr = (await publicKey.encryptToString('Hello, World!')).unwrap(); * ``` */ interface RSAPublicKey { /** * 使用 RSA-OAEP 算法加密数据。 * @param data - 要加密的数据。 * @returns 加密后的 ArrayBuffer。 */ encrypt(data: DataSource): AsyncIOResult; /** * 加密后转换为 Base64 字符串。 * @param data - 要加密的数据。 * @returns 加密后的 Base64 字符串。 */ encryptToString(data: DataSource): AsyncIOResult; } /** * RSA-OAEP 加密支持的 SHA 哈希算法。 * * @since 1.6.0 * @example * ```ts * import { importPublicKey, type SHA } from 'minigame-std'; * * const hash: SHA = 'SHA-256'; * const publicKey = (await importPublicKey(pemString, hash)).unwrap(); * ``` */ type SHA = 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512'; /** * 使用 SHA-1 算法计算 HMAC。 * @param key - 密钥,可以是字符串或 BufferSource。 * @param data - 需要计算 HMAC 的数据,可以是字符串或 BufferSource。 * @returns 返回十六进制格式的 HMAC 字符串。 * @since 1.8.0 * @example * ```ts * const hmac = (await sha1HMAC('secret-key', 'Hello, World!')).unwrap(); * console.log(hmac); // 十六进制 HMAC 字符串 * ``` */ declare function sha1HMAC(key: DataSource, data: DataSource): AsyncIOResult; /** * 使用 SHA-256 算法计算 HMAC。 * @param key - 密钥,可以是字符串或 BufferSource。 * @param data - 需要计算 HMAC 的数据,可以是字符串或 BufferSource。 * @returns 返回十六进制格式的 HMAC 字符串。 * @since 1.8.0 * @example * ```ts * const hmac = (await sha256HMAC('secret-key', 'Hello, World!')).unwrap(); * console.log(hmac); // 十六进制 HMAC 字符串 * ``` */ declare function sha256HMAC(key: DataSource, data: DataSource): AsyncIOResult; /** * 使用 SHA-384 算法计算 HMAC。 * @param key - 密钥,可以是字符串或 BufferSource。 * @param data - 需要计算 HMAC 的数据,可以是字符串或 BufferSource。 * @returns 返回十六进制格式的 HMAC 字符串。 * @since 1.8.0 * @example * ```ts * const hmac = (await sha384HMAC('secret-key', 'Hello, World!')).unwrap(); * console.log(hmac); // 十六进制 HMAC 字符串 * ``` */ declare function sha384HMAC(key: DataSource, data: DataSource): AsyncIOResult; /** * 使用 SHA-512 算法计算 HMAC。 * @param key - 密钥,可以是字符串或 BufferSource。 * @param data - 需要计算 HMAC 的数据,可以是字符串或 BufferSource。 * @returns 返回十六进制格式的 HMAC 字符串。 * @since 1.8.0 * @example * ```ts * const hmac = (await sha512HMAC('secret-key', 'Hello, World!')).unwrap(); * console.log(hmac); // 十六进制 HMAC 字符串 * ``` */ declare function sha512HMAC(key: DataSource, data: DataSource): AsyncIOResult; /** * MD5 哈希计算类,支持流式更新。 * @since 1.0.0 * @example * ```ts * // 基本用法 * const hash = new Md5().update('Hello, World!').toString(); * console.log(hash); // '65a8e27d8879283831b664bd8b7f0ad4' * * // 流式更新 * const md5 = new Md5(); * md5.update('Hello, '); * md5.update('World!'); * console.log(md5.toString()); // '65a8e27d8879283831b664bd8b7f0ad4' * * // 获取 ArrayBuffer * const buffer = new Md5().update('test').digest(); * ``` */ declare class Md5 { private a; private b; private c; private d; private block; private pos; private n0; private n1; /** * 累加已处理的消息长度。 * * n0 和 n1 共同组成一个 64 位计数器,用于记录消息的总字节数。 * - n0: 低 32 位 * - n1: 高 32 位 * * 当 n0 溢出(超过 0xffffffff,即 2^32 - 1)时,需要向 n1 进位。 * * @param len - 本次处理的字节数 */ private addLength; private hash; /** * 更新内部状态。 * @param data - 要更新的数据,数据大小不能超过 2^32 字节。 */ update(data: DataSource): this; /** * 返回最终的哈希值。 */ digest(): ArrayBuffer; /** * 以十六进制字符串形式返回哈希值。 */ toString(): string; } /** * 计算字符串或 Buffer 的 MD5 值。 * @param data - 需要计算 MD5 值的数据,可以是字符串或 BufferSource。 * @returns 计算得到的 MD5 十六进制字符串(32 位)。 * @since 1.0.0 * @example * ```ts * const hash = md5('Hello, World!'); * console.log(hash); // '65a8e27d8879283831b664bd8b7f0ad4' * ``` */ declare function md5(data: DataSource): string; /** * UUID 类型。 * @since 1.7.0 * @example * ```ts * import { cryptos, type UUID } from 'minigame-std'; * * const result = await cryptos.randomUUID(); * if (result.isOk()) { * const uuid: UUID = result.unwrap(); * console.log(uuid); // 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' * } * ``` */ type UUID = `${string}-${string}-${string}-${string}-${string}`; /** * 获取密码学安全的随机数。 * @param length - 要生成的随机字节数。 * @returns 包含随机数据的 Uint8Array,封装在 IOResult 中。 * @since 1.7.0 * @example * ```ts * const result = await getRandomValues(16); * if (result.isOk()) { * console.log(result.unwrap()); // Uint8Array(16) [...] * } * ``` */ declare function getRandomValues(length: number): AsyncIOResult>; /** * 生成符合 RFC 4122 标准的 UUID v4。 * @returns UUID 字符串,封装在 IOResult 中。 * @since 1.7.0 * @example * ```ts * const result = await randomUUID(); * if (result.isOk()) { * console.log(result.unwrap()); // 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' * } * ``` */ declare function randomUUID(): AsyncIOResult; /** * 从 PEM 格式的字符串导入 RSA 公钥,用于加密操作。 * @param pem - PEM 格式的公钥字符串。 * @param hash - 用于 OAEP 填充的哈希算法(SHA-1、SHA-256、SHA-384 或 SHA-512)。 * @returns RSA 公钥对象,包含 encrypt 方法用于加密数据。 * @since 1.6.0 * @example * ```ts * const publicKey = (await importPublicKey(pemString, 'SHA-256')).unwrap(); * * // 加密并返回 ArrayBuffer * const encrypted = (await publicKey.encrypt('Hello, World!')).unwrap(); * * // 加密并返回 Base64 字符串 * const encryptedStr = (await publicKey.encryptToString('Hello, World!')).unwrap(); * ``` */ declare function importPublicKey(pem: string, hash: SHA): AsyncIOResult; declare const mod$7_importPublicKey: typeof importPublicKey; declare namespace mod$7 { export { mod$7_importPublicKey as importPublicKey, }; } /** * 计算数据的 SHA-1 哈希值。 * @param data - 需要计算哈希的数据,可以是字符串或 BufferSource。 * @returns 返回十六进制格式的哈希字符串。 * @since 1.6.0 * @example * ```ts * const hash = await sha1('Hello, World!'); * if (hash.isOk()) { * console.log(hash.unwrap()); // 十六进制哈希字符串 * } * ``` */ declare function sha1(data: DataSource): AsyncIOResult; /** * 计算数据的 SHA-256 哈希值。 * @param data - 需要计算哈希的数据,可以是字符串或 BufferSource。 * @returns 返回十六进制格式的哈希字符串。 * @since 1.0.0 * @example * ```ts * const hash = await sha256('Hello, World!'); * if (hash.isOk()) { * console.log(hash.unwrap()); // 十六进制哈希字符串 * } * ``` */ declare function sha256(data: DataSource): AsyncIOResult; /** * 计算数据的 SHA-384 哈希值。 * @param data - 需要计算哈希的数据,可以是字符串或 BufferSource。 * @returns 返回十六进制格式的哈希字符串。 * @since 1.6.0 * @example * ```ts * const hash = await sha384('Hello, World!'); * if (hash.isOk()) { * console.log(hash.unwrap()); // 十六进制哈希字符串 * } * ``` */ declare function sha384(data: DataSource): AsyncIOResult; /** * 计算数据的 SHA-512 哈希值。 * @param data - 需要计算哈希的数据,可以是字符串或 BufferSource。 * @returns 返回十六进制格式的哈希字符串。 * @since 1.6.0 * @example * ```ts * const hash = await sha512('Hello, World!'); * if (hash.isOk()) { * console.log(hash.unwrap()); // 十六进制哈希字符串 * } * ``` */ declare function sha512(data: DataSource): AsyncIOResult; /** * 加密相关功能模块,提供 HMAC、MD5、SHA、RSA 等加密算法和随机数生成。 * @module cryptos */ type mod$6_Md5 = Md5; declare const mod$6_Md5: typeof Md5; type mod$6_RSAPublicKey = RSAPublicKey; type mod$6_SHA = SHA; type mod$6_UUID = UUID; declare const mod$6_getRandomValues: typeof getRandomValues; declare const mod$6_md5: typeof md5; declare const mod$6_randomUUID: typeof randomUUID; declare const mod$6_sha1: typeof sha1; declare const mod$6_sha1HMAC: typeof sha1HMAC; declare const mod$6_sha256: typeof sha256; declare const mod$6_sha256HMAC: typeof sha256HMAC; declare const mod$6_sha384: typeof sha384; declare const mod$6_sha384HMAC: typeof sha384HMAC; declare const mod$6_sha512: typeof sha512; declare const mod$6_sha512HMAC: typeof sha512HMAC; declare namespace mod$6 { export { mod$6_Md5 as Md5, mod$6_getRandomValues as getRandomValues, mod$6_md5 as md5, mod$6_randomUUID as randomUUID, mod$7 as rsa, mod$6_sha1 as sha1, mod$6_sha1HMAC as sha1HMAC, mod$6_sha256 as sha256, mod$6_sha256HMAC as sha256HMAC, mod$6_sha384 as sha384, mod$6_sha384HMAC as sha384HMAC, mod$6_sha512 as sha512, mod$6_sha512HMAC as sha512HMAC }; export type { mod$6_RSAPublicKey as RSAPublicKey, mod$6_SHA as SHA, mod$6_UUID as UUID }; } /** * 添加错误监听器,用于监听标准的错误事件。 * @param listener - 错误事件的回调函数。 * @returns 返回一个函数,调用该函数可以移除监听器。 * @since 1.0.0 * @example * ```ts * const removeListener = addErrorListener((ev) => { * console.error('捕获到错误:', ev.message); * }); * * // 移除监听器 * removeListener(); * ``` */ declare function addErrorListener(listener: (ev: WechatMinigame.ListenerError) => void): () => void; /** * 添加未处理的 Promise 拒绝事件监听器。 * @param listener - 未处理的 Promise 拒绝事件的回调函数。 * @returns 返回一个函数,调用该函数可以移除监听器。 * @since 1.0.0 * @example * ```ts * const removeListener = addUnhandledrejectionListener((ev) => { * console.error('未处理的 Promise 拒绝:', ev.reason); * }); * * // 移除监听器 * removeListener(); * ``` */ declare function addUnhandledrejectionListener(listener: (ev: Pick) => void): () => void; /** * 添加窗口大小变化监听器。 * @param listener - 窗口大小变化的回调函数。 * @returns 返回一个函数,调用该函数可以移除监听器。 * @since 1.7.0 * @example * ```ts * const removeListener = addResizeListener((size) => { * console.log('窗口大小变化:', size.windowWidth, 'x', size.windowHeight); * }); * * // 移除监听器 * removeListener(); * ``` */ declare function addResizeListener(listener: WechatMinigame.OnWindowResizeCallback): () => void; /** * 微信小游戏网络请求初始化配置接口,继承自微信小游戏请求选项,除去'url'和'responseType'。 * @since 1.0.0 * @example * ```ts * import { fetchT, type MinaFetchInit } from 'minigame-std'; * * const init: MinaFetchInit = { * method: 'POST', * header: { 'Content-Type': 'application/json' }, * responseType: 'json', * }; * const task = fetchT('https://api.example.com/data', init); * ``` */ interface MinaFetchInit extends Omit { responseType?: 'arraybuffer' | 'text' | 'json'; onChunk?: FetchInit['onChunk']; } /** * 联合网络请求初始化配置类型,结合了 FetchInit 和 MinaFetchInit。 * @since 1.0.0 * @example * ```ts * import { fetchT, type UnionFetchInit } from 'minigame-std'; * * const init: UnionFetchInit = { * method: 'GET', * responseType: 'json', * timeout: 30000, * }; * const task = fetchT('https://api.example.com/data', init); * ``` */ type UnionFetchInit = FetchInit & MinaFetchInit; /** * 网络请求模块,提供可中断的 fetch 请求功能,支持 text、JSON、ArrayBuffer 等响应类型。 * @module fetch */ /** * 发起一个可中断的文本类型响应的网络请求。 * @param url - 请求的 URL 地址。 * @param init - 请求的初始化配置,指定响应类型为文本且请求可中断。 * @returns 返回一个文本类型的 FetchTask。 * @since 1.0.0 * @example * ```ts * const task = fetchT('https://api.example.com/data', { responseType: 'text' }); * const result = await task.result; * if (result.isOk()) { * console.log(result.unwrap()); // 文本内容 * } * // 如需中断请求 * task.abort(); * ``` */ declare function fetchT(url: string, init: UnionFetchInit & { responseType: 'text'; }): FetchTask; /** * 发起一个可中断的 ArrayBuffer 类型响应的网络请求。 * @param url - 请求的 URL 地址。 * @param init - 请求的初始化配置,指定响应类型为 ArrayBuffer 且请求可中断。 * @returns 返回一个 ArrayBuffer 类型的 FetchTask。 * @since 1.0.0 * @example * ```ts * const task = fetchT('https://api.example.com/file', { responseType: 'arraybuffer' }); * const result = await task.result; * if (result.isOk()) { * const buffer = result.unwrap(); * console.log('文件大小:', buffer.byteLength); * } * ``` */ declare function fetchT(url: string, init: UnionFetchInit & { responseType: 'arraybuffer'; }): FetchTask; /** * 发起一个可中断的 JSON 类型响应的网络请求。 * @typeParam T - 预期的 JSON 响应数据类型。 * @param url - 请求的 URL 地址。 * @param init - 请求的初始化配置,指定响应类型为 JSON 且请求可中断。 * @returns 返回一个 JSON 类型的 FetchTask。 * @since 1.0.0 * @example * ```ts * interface User { * id: number; * name: string; * } * const task = fetchT('https://api.example.com/user/1', { responseType: 'json' }); * const result = await task.result; * if (result.isOk()) { * const user = result.unwrap(); * console.log(user.name); * } * ``` */ declare function fetchT(url: string, init: UnionFetchInit & { responseType: 'json'; }): FetchTask; /** * 发起一个可中断的网络请求,默认返回文本类型响应。 * @typeParam T - 预期的响应数据类型。 * @param url - 请求的 URL 地址。 * @param init - 请求的初始化配置,指定请求可中断。 * @returns FetchTask。 * @since 1.0.0 * @example * ```ts * const task = fetchT('https://api.example.com/data'); * const result = await task.result; * if (result.isOk()) { * console.log(result.unwrap()); * } * ``` */ declare function fetchT(url: string, init?: UnionFetchInit): FetchTask; /** * 异步写入文件的内容类型,支持 `ArrayBuffer` `TypedArray` `string`。 * 小游戏不支持 `Blob` 和 `ReadableStream`,因此直接使用 `DataSource`。 * @since 1.0.0 * @example * ```ts * import { fs, type WriteFileContent } from 'minigame-std'; * * const content: WriteFileContent = '文本内容'; * await fs.writeFile('/path/to/file.txt', content); * ``` */ type WriteFileContent = DataSource; /** * 读取文件的内容类型,支持 `Uint8Array` `string`。 * 小游戏不支持 `Blob`、`File` 和 `ReadableStream`。 * @since 1.0.0 * @example * ```ts * import type { ReadFileContent } from 'minigame-std'; * * // ReadFileContent 可以是 Uint8Array 或 string * const content: ReadFileContent = new Uint8Array(8); * ``` */ type ReadFileContent = Uint8Array | string; /** * 指定编码读取文件的选项。 * @since 1.0.0 * @example * ```ts * import type { ReadOptions } from 'minigame-std'; * * const options: ReadOptions = { encoding: 'utf8' }; * ``` */ interface ReadOptions { /** * 读取文件的编码类型,支持 `bytes(Uint8Array)` `utf8(string)`。 * * @defaultValue `'bytes'` */ encoding?: FileEncoding; } /** * 支持的文件编码格式。 * @since 1.0.0 * @example * ```ts * import type { FileEncoding } from 'minigame-std'; * * const encoding: FileEncoding = 'utf8'; * ``` */ type FileEncoding = 'bytes' | 'utf8'; /** * 下载文件的选项。 * @since 1.0.0 * @example * ```ts * import { fs, type DownloadFileOptions } from 'minigame-std'; * * const options: DownloadFileOptions = { * onProgress: (progress) => console.log(`下载进度: ${progress.progress}%`), * }; * const task = fs.downloadFile('https://example.com/file.zip', '/path/to/save.zip', options); * ``` */ interface DownloadFileOptions extends Omit { onProgress?: FetchInit['onProgress']; } /** * 上传文件的选项。 * @since 1.0.0 * @example * ```ts * import { fs, type UploadFileOptions } from 'minigame-std'; * * const options: UploadFileOptions = { * name: 'file', * formData: { key: 'value' }, * }; * const task = fs.uploadFile('/path/to/file.txt', 'https://example.com/upload', options); * ``` */ interface UploadFileOptions extends Omit { /** * 可选的文件名称。 */ name?: string; } /** * 统一下载请求的选项。 * @since 1.0.0 * @example * ```ts * import type { UnionDownloadFileOptions } from 'minigame-std'; * * const options: UnionDownloadFileOptions = { * timeout: 30000, * onProgress: (p) => console.log(p.progress), * }; * ``` */ type UnionDownloadFileOptions = FsRequestInit & DownloadFileOptions; /** * 统一上传请求的选项。 * @since 1.0.0 * @example * ```ts * import type { UnionUploadFileOptions } from 'minigame-std'; * * const options: UnionUploadFileOptions = { * name: 'file', * formData: { key: 'value' }, * }; * ``` */ type UnionUploadFileOptions = UploadRequestInit & UploadFileOptions; /** * stat 操作的选项。 * @since 1.0.0 * @example * ```ts * import { fs, type StatOptions } from 'minigame-std'; * * const options: StatOptions = { recursive: true }; * const result = await fs.stat('/path/to/dir', options); * ``` */ interface StatOptions { /** * 是否递归读取目录内容。 */ recursive: boolean; } /** * `unzipFromUrl` 的统一选项。 * @since 1.4.0 * @example * ```ts * import { fs, type ZipFromUrlOptions } from 'minigame-std'; * * const options: ZipFromUrlOptions = { * onProgress: (p) => console.log(p.progress), * }; * await fs.unzipFromUrl('https://example.com/archive.zip', '/path/to/output', options); * ``` */ type ZipFromUrlOptions = DownloadFileOptions & ZipFromUrlRequestInit; /** * 递归创建文件夹,相当于 `mkdir -p`。 * @param dirPath - 将要创建的目录的路径。 * @returns 创建成功返回的异步操作结果。 * @since 1.0.0 * @example * ```ts * const result = await mkdir('/path/to/dir'); * if (result.isOk()) { * console.log('目录创建成功'); * } * ``` */ declare function mkdir(dirPath: string): AsyncVoidIOResult; /** * 移动或重命名文件或目录。 * @param srcPath - 原始路径。 * @param destPath - 新路径。 * @returns 操作成功返回的异步操作结果。 * @since 1.0.0 * @example * ```ts * const result = await move('/old/path', '/new/path'); * if (result.isOk()) { * console.log('移动成功'); * } * ``` */ declare function move(srcPath: string, destPath: string): AsyncVoidIOResult; /** * 异步读取指定目录下的所有文件和子目录。 * @param dirPath - 需要读取的目录路径。 * @returns 包含目录内容的字符串数组的异步操作结果。 * @since 1.0.0 * @example * ```ts * const result = await readDir('/path/to/dir'); * if (result.isOk()) { * console.log(result.unwrap()); // ['file1.txt', 'file2.txt', 'subdir'] * } * ``` */ declare function readDir(dirPath: string): AsyncIOResult; /** * 以 UTF-8 格式读取文件。 * @param filePath - 文件路径。 * @param options - 读取选项,指定编码为 'utf8'。 * @returns 包含文件内容的字符串的异步操作结果。 * @since 1.0.0 * @example * ```ts * const result = await readFile('/path/to/file.txt', { encoding: 'utf8' }); * if (result.isOk()) { * console.log(result.unwrap()); * } * ``` */ declare function readFile(filePath: string, options: ReadOptions & { encoding: 'utf8'; }): AsyncIOResult; /** * 以二进制格式读取文件。 * @param filePath - 文件路径。 * @param options - 读取选项,指定编码为 'bytes'。 * @returns 包含文件内容的 Uint8Array 的异步操作结果。 * @since 1.0.0 * @example * ```ts * const result = await readFile('/path/to/file.txt', { encoding: 'bytes' }); * if (result.isOk()) { * const bytes = result.unwrap(); * console.log(decodeUtf8(bytes)); * } * ``` */ declare function readFile(filePath: string, options?: ReadOptions & { encoding: 'bytes'; }): AsyncIOResult>; /** * 读取文件内容。 * @param filePath - 文件的路径。 * @param options - 可选的读取选项。 * @returns 包含文件内容的异步操作结果。 * @since 1.0.0 * @example * ```ts * const result = await readFile('/path/to/file.txt'); * if (result.isOk()) { * const bytes = result.unwrap(); * console.log(decodeUtf8(bytes)); * } * ``` */ declare function readFile(filePath: string, options?: ReadOptions): AsyncIOResult; /** * 删除文件或目录。 * @param path - 要删除的文件或目录的路径。 * @returns 删除成功返回的异步操作结果。 * @since 1.0.0 * @example * ```ts * const result = await remove('/path/to/file.txt'); * if (result.isOk()) { * console.log('删除成功'); * } * ``` */ declare function remove(path: string): AsyncVoidIOResult; /** * 获取单个文件或目录的状态信息。 * @param path - 文件或目录的路径。 * @param options - 可选选项,recursive 设置为 false(默认)获取单个文件状态。 * @returns 包含状态信息的异步操作结果。 * @since 1.0.0 * @example * ```ts * const result = await stat('/path/to/file.txt'); * if (result.isOk()) { * const stats = result.unwrap(); * console.log(stats.isFile()); // true * } * ``` */ declare function stat(path: string, options?: StatOptions & { recursive: false; }): AsyncIOResult; /** * 递归获取目录下所有文件和子目录的状态信息。 * @param path - 目录的路径。 * @param options - 选项,recursive 设置为 true 以递归获取。 * @returns 包含所有文件状态信息数组的异步操作结果。 * @since 1.0.0 * @example * ```ts * const result = await stat('/path/to/dir', { recursive: true }); * if (result.isOk()) { * const fileStats = result.unwrap(); * fileStats.forEach(file => console.log(file.path)); * } * ``` */ declare function stat(path: string, options: StatOptions & { recursive: true; }): AsyncIOResult; declare function stat(path: string, options?: StatOptions): AsyncIOResult; /** * 写入文件,文件不存在则创建,同时创建对应目录。 * @param filePath - 文件路径。 * @param contents - 要写入的内容,支持 ArrayBuffer 和 string(需确保是 UTF-8 编码)。 * @param options - 可选写入选项。 * @returns 写入成功返回的异步操作结果。 * @since 1.0.0 * @example * ```ts * const result = await writeFile('/path/to/file.txt', 'Hello, World!'); * if (result.isOk()) { * console.log('写入成功'); * } * ``` */ declare function writeFile(filePath: string, contents: WriteFileContent, options?: WriteOptions): AsyncVoidIOResult; /** * 向文件追加内容。 * @param filePath - 文件路径。 * @param contents - 要追加的内容。 * @param options - 可选的追加选项。 * @returns 追加成功返回的异步操作结果。 * @since 1.0.0 * @example * ```ts * const result = await appendFile('/path/to/file.txt', '\nNew content'); * if (result.isOk()) { * console.log('追加成功'); * } * ``` */ declare function appendFile(filePath: string, contents: WriteFileContent, options?: AppendOptions): AsyncVoidIOResult; /** * 复制文件或文件夹。 * @param srcPath - 源文件或文件夹路径。 * @param destPath - 目标文件或文件夹路径。 * @returns 操作的异步结果。 * @since 1.0.0 * @example * ```ts * const result = await copy('/src/file.txt', '/dest/file.txt'); * if (result.isOk()) { * console.log('复制成功'); * } * ``` */ declare function copy(srcPath: string, destPath: string): AsyncVoidIOResult; /** * 检查指定路径的文件或目录是否存在。 * @param path - 文件或目录的路径。 * @param options - 可选的检查选项。 * @returns 存在返回 true 的异步操作结果。 * @since 1.0.0 * @example * ```ts * const result = await exists('/path/to/file.txt'); * if (result.isOk() && result.unwrap()) { * console.log('文件存在'); * } * ``` */ declare function exists(path: string, options?: ExistsOptions): AsyncIOResult; /** * 清空指定目录下的所有文件和子目录。 * @param dirPath - 目录路径。 * @returns 清空成功返回的异步操作结果。 * @since 1.0.1 * @example * ```ts * const result = await emptyDir('/path/to/dir'); * if (result.isOk()) { * console.log('目录已清空'); * } * ``` */ declare function emptyDir(dirPath: string): AsyncVoidIOResult; /** * 读取 JSON 文件并解析为对象。 * @typeParam T - JSON 解析后的类型。 * @param filePath - 文件路径。 * @returns 解析后的对象。 * @since 1.6.0 * @example * ```ts * const result = await readJsonFile<{ name: string }>('/path/to/config.json'); * if (result.isOk()) { * console.log(result.unwrap().name); * } * ``` */ declare function readJsonFile(filePath: string): AsyncIOResult; /** * 读取文本文件的内容。 * @param filePath - 文件路径。 * @returns 包含文件文本内容的异步操作结果。 * @since 1.0.0 * @example * ```ts * const result = await readTextFile('/path/to/file.txt'); * if (result.isOk()) { * console.log(result.unwrap()); * } * ``` */ declare function readTextFile(filePath: string): AsyncIOResult; /** * 将数据序列化为 JSON 并写入文件。 * @typeParam T - 要写入数据的类型。 * @param filePath - 文件路径。 * @param data - 要写入的数据。 * @returns 写入操作的异步结果。 * @since 2.0.0 * @example * ```ts * const result = await writeJsonFile('/path/to/config.json', { name: 'test' }); * if (result.isOk()) { * console.log('写入成功'); * } * ``` */ declare function writeJsonFile(filePath: string, data: T): AsyncVoidIOResult; /** * 下载文件并保存到临时文件。 * @param fileUrl - 文件的网络 URL。 * @param options - 可选的下载参数。 * @returns 下载操作的 FetchTask,可用于取消或监听进度。 * @since 1.0.0 * @example * ```ts * const task = downloadFile('https://example.com/file.zip'); * const result = await task.result; * if (result.isOk()) { * console.log('下载完成:', result.unwrap().tempFilePath); * } * ``` */ declare function downloadFile(fileUrl: string, options?: UnionDownloadFileOptions): FetchTask; /** * 下载文件并保存到指定路径。 * @param fileUrl - 文件的网络 URL。 * @param filePath - 下载后文件存储的路径。 * @param options - 可选的请求初始化参数。 * @returns 下载操作的 FetchTask。 * @since 1.0.0 * @example * ```ts * const task = downloadFile('https://example.com/file.zip', '/path/to/save.zip'); * const result = await task.result; * if (result.isOk()) { * console.log('下载完成'); * } * ``` */ declare function downloadFile(fileUrl: string, filePath: string, options?: UnionDownloadFileOptions): FetchTask; /** * 上传本地文件到服务器。 * @param filePath - 需要上传的文件路径。 * @param fileUrl - 目标服务器的 URL。 * @param options - 可选的请求初始化参数。 * @returns 上传操作的 FetchTask。 * @since 1.0.0 * @example * ```ts * const task = uploadFile('/path/to/file.txt', 'https://example.com/upload'); * const result = await task.result; * if (result.isOk()) { * console.log('上传成功'); * } * ``` */ declare function uploadFile(filePath: string, fileUrl: string, options?: UnionUploadFileOptions): FetchTask; /** * 解压 zip 文件。 * @param zipFilePath - 要解压的 zip 文件路径。 * @param targetPath - 要解压到的目标文件夹路径。 * @returns 解压操作的异步结果。 * @since 1.3.0 * @example * ```ts * const result = await unzip('/path/to/archive.zip', '/path/to/output'); * if (result.isOk()) { * console.log('解压成功'); * } * ``` */ declare function unzip(zipFilePath: string, targetPath: string): AsyncVoidIOResult; /** * 从网络下载 zip 文件并解压。 * @param zipFileUrl - Zip 文件的网络地址。 * @param targetPath - 要解压到的目标文件夹路径。 * @param options - 可选的下载参数。 * @returns 下载并解压操作的异步结果。 * @since 1.4.0 * @example * ```ts * const result = await unzipFromUrl('https://example.com/archive.zip', '/path/to/output'); * if (result.isOk()) { * console.log('下载并解压成功'); * } * ``` */ declare function unzipFromUrl(zipFileUrl: string, targetPath: string, options?: UnionDownloadFileOptions): AsyncVoidIOResult; /** * 压缩文件或文件夹到内存。 * @param sourcePath - 需要压缩的文件(夹)路径。 * @param options - 可选的压缩参数。 * @returns 压缩后的 Uint8Array。 * @since 1.3.0 * @example * ```ts * const result = await zip('/path/to/source'); * if (result.isOk()) { * console.log('压缩成功:', result.unwrap().length, 'bytes'); * } * ``` */ declare function zip(sourcePath: string, options?: ZipOptions): AsyncIOResult>; /** * 压缩文件或文件夹并保存到指定路径。 * @param sourcePath - 需要压缩的文件(夹)路径。 * @param zipFilePath - 压缩后的 zip 文件路径。 * @param options - 可选的压缩参数。 * @returns 压缩操作的异步结果。 * @since 1.3.0 * @example * ```ts * const result = await zip('/path/to/source', '/path/to/archive.zip'); * if (result.isOk()) { * console.log('压缩成功'); * } * ``` */ declare function zip(sourcePath: string, zipFilePath: string, options?: ZipOptions): AsyncVoidIOResult; /** * 下载文件并压缩到内存。 * @param sourceUrl - 要下载的文件 URL。 * @param options - 合并的下载和压缩选项。 * @returns 压缩后的 Uint8Array。 * @since 1.4.0 * @example * ```ts * const result = await zipFromUrl('https://example.com/file.txt'); * if (result.isOk()) { * console.log('下载并压缩成功'); * } * ``` */ declare function zipFromUrl(sourceUrl: string, options?: ZipFromUrlOptions): AsyncIOResult>; /** * 下载文件并压缩为 zip 文件。 * @param sourceUrl - 要下载的文件 URL。 * @param zipFilePath - 要输出的 zip 文件路径。 * @param options - 合并的下载和压缩选项。 * @returns 操作的异步结果。 * @since 1.4.0 * @example * ```ts * const result = await zipFromUrl('https://example.com/file.txt', '/path/to/archive.zip'); * if (result.isOk()) { * console.log('下载并压缩成功'); * } * ``` */ declare function zipFromUrl(sourceUrl: string, zipFilePath: string, options?: ZipFromUrlOptions): AsyncVoidIOResult; /** * `mkdir` 的同步版本,递归创建文件夹。 * @param dirPath - 将要创建的目录的路径。 * @returns 创建成功返回的操作结果。 * @since 1.1.0 * @example * ```ts * const result = mkdirSync('/path/to/dir'); * if (result.isOk()) { * console.log('目录创建成功'); * } * ``` */ declare function mkdirSync(dirPath: string): VoidIOResult; /** * `move` 的同步版本,移动或重命名文件或目录。 * @param srcPath - 原始路径。 * @param destPath - 新路径。 * @returns 操作成功返回的操作结果。 * @since 1.1.0 * @example * ```ts * const result = moveSync('/old/path', '/new/path'); * if (result.isOk()) { * console.log('移动成功'); * } * ``` */ declare function moveSync(srcPath: string, destPath: string): VoidIOResult; /** * `readDir` 的同步版本,读取指定目录下的所有文件和子目录。 * @param dirPath - 需要读取的目录路径。 * @returns 包含目录内容的字符串数组的操作结果。 * @since 1.1.0 * @example * ```ts * const result = readDirSync('/path/to/dir'); * if (result.isOk()) { * console.log(result.unwrap()); // ['file1.txt', 'file2.txt'] * } * ``` */ declare function readDirSync(dirPath: string): IOResult; /** * 以 UTF-8 格式读取文件。 * @param filePath - 文件路径。 * @param options - 读取选项,指定编码为 'utf8'。 * @returns 包含文件内容的字符串的操作结果。 * @since 1.1.0 * @example * ```ts * const result = readFileSync('/path/to/file.txt', { encoding: 'utf8' }); * if (result.isOk()) { * console.log(result.unwrap()); * } * ``` */ declare function readFileSync(filePath: string, options: ReadOptions & { encoding: 'utf8'; }): IOResult; /** * 以二进制格式读取文件。 * @param filePath - 文件路径。 * @param options - 读取选项,指定编码为 'bytes'。 * @returns 包含文件内容的 Uint8Array 的操作结果。 * @since 1.1.0 * @example * ```ts * const result = readFileSync('/path/to/file.txt', { encoding: 'bytes' }); * if (result.isOk()) { * const bytes = result.unwrap(); * console.log(decodeUtf8(bytes)); * } * ``` */ declare function readFileSync(filePath: string, options?: ReadOptions & { encoding: 'bytes'; }): IOResult>; /** * `readFile` 的同步版本,读取文件内容。 * @param filePath - 文件的路径。 * @param options - 可选的读取选项。 * @returns 包含文件内容的操作结果。 * @since 1.1.0 * @example * ```ts * const result = readFileSync('/path/to/file.txt'); * if (result.isOk()) { * const bytes = result.unwrap(); * console.log(decodeUtf8(bytes)); * } * ``` */ declare function readFileSync(filePath: string, options?: ReadOptions): IOResult; /** * `remove` 的同步版本,删除文件或目录。 * @param path - 要删除的文件或目录的路径。 * @returns 删除成功返回的操作结果。 * @since 1.1.0 * @example * ```ts * const result = removeSync('/path/to/file.txt'); * if (result.isOk()) { * console.log('删除成功'); * } * ``` */ declare function removeSync(path: string): VoidIOResult; /** * `stat` 的同步版本,获取文件或目录的状态信息。 * @param path - 文件或目录的路径。 * @returns 包含状态信息的操作结果。 * @since 1.1.0 * @example * ```ts * const result = statSync('/path/to/file.txt'); * if (result.isOk()) { * console.log(result.unwrap().isFile()); // true * } * ``` */ declare function statSync(path: string, options?: StatOptions & { recursive: false; }): IOResult; /** * `stat` 的同步版本,递归获取目录下所有文件和子目录的状态信息。 * @param path - 目录的路径。 * @param options - 选项,recursive 设置为 true 时递归获取。 * @returns 包含目录下所有文件状态信息数组的操作结果。 * @since 1.1.0 * @example * ```ts * const result = statSync('/path/to/dir', { recursive: true }); * if (result.isOk()) { * result.unwrap().forEach(item => { * console.log(item.path, item.stats.isDirectory()); * }); * } * ``` */ declare function statSync(path: string, options: StatOptions & { recursive: true; }): IOResult; /** * `stat` 的同步版本,获取文件或目录的状态信息。 * @param path - 文件或目录的路径。 * @param options - 可选选项,包含 recursive 可递归获取目录下所有文件状态。 * @returns 包含状态信息的操作结果,根据 options.recursive 返回单个 Stats 或 FileStats 数组。 * @since 1.1.0 */ declare function statSync(path: string, options?: StatOptions): IOResult; /** * `writeFile` 的同步版本,写入文件。 * @param filePath - 文件路径。 * @param contents - 要写入的内容。 * @returns 写入成功返回的操作结果。 * @since 1.1.0 * @example * ```ts * const result = writeFileSync('/path/to/file.txt', 'Hello, World!'); * if (result.isOk()) { * console.log('写入成功'); * } * ``` */ declare function writeFileSync(filePath: string, contents: WriteFileContent): VoidIOResult; /** * `appendFile` 的同步版本,向文件追加内容。 * @param filePath - 文件路径。 * @param contents - 要追加的内容。 * @param options - 可选的追加选项。 * @returns 追加成功返回的操作结果。 * @since 1.1.0 * @example * ```ts * const result = appendFileSync('/path/to/file.txt', '\nNew content'); * if (result.isOk()) { * console.log('追加成功'); * } * ``` */ declare function appendFileSync(filePath: string, contents: WriteFileContent, options?: AppendOptions): VoidIOResult; /** * `copy` 的同步版本,复制文件或文件夹。 * @param srcPath - 源文件或文件夹路径。 * @param destPath - 目标文件或文件夹路径。 * @returns 操作的结果。 * @since 1.1.0 * @example * ```ts * const result = copySync('/src/file.txt', '/dest/file.txt'); * if (result.isOk()) { * console.log('复制成功'); * } * ``` */ declare function copySync(srcPath: string, destPath: string): VoidIOResult; /** * `exists` 的同步版本,检查指定路径的文件或目录是否存在。 * @param path - 文件或目录的路径。 * @param options - 可选的检查选项。 * @returns 存在返回 true 的操作结果。 * @since 1.1.0 * @example * ```ts * const result = existsSync('/path/to/file.txt'); * if (result.isOk() && result.unwrap()) { * console.log('文件存在'); * } * ``` */ declare function existsSync(path: string, options?: ExistsOptions): IOResult; /** * `emptyDir` 的同步版本,清空指定目录下的所有文件和子目录。 * @param dirPath - 目录路径。 * @returns 清空成功返回的操作结果。 * @since 1.1.0 * @example * ```ts * const result = emptyDirSync('/path/to/dir'); * if (result.isOk()) { * console.log('目录已清空'); * } * ``` */ declare function emptyDirSync(dirPath: string): VoidIOResult; /** * `readJsonFile` 的同步版本,读取 JSON 文件并解析为对象。 * @typeParam T - JSON 解析后的类型。 * @param filePath - 文件路径。 * @returns 解析后的对象。 * @since 1.6.0 * @example * ```ts * const result = readJsonFileSync<{ name: string }>('/path/to/config.json'); * if (result.isOk()) { * console.log(result.unwrap().name); * } * ``` */ declare function readJsonFileSync(filePath: string): IOResult; /** * `readTextFile` 的同步版本,读取文本文件的内容。 * @param filePath - 文件路径。 * @returns 包含文件文本内容的操作结果。 * @since 1.1.0 * @example * ```ts * const result = readTextFileSync('/path/to/file.txt'); * if (result.isOk()) { * console.log(result.unwrap()); * } * ``` */ declare function readTextFileSync(filePath: string): IOResult; /** * `writeJsonFile` 的同步版本,将数据序列化为 JSON 并写入文件。 * @typeParam T - 要写入数据的类型。 * @param filePath - 文件路径。 * @param data - 要写入的数据。 * @returns 写入操作的结果。 * @since 2.0.0 * @example * ```ts * const result = writeJsonFileSync('/path/to/config.json', { name: 'test' }); * if (result.isOk()) { * console.log('写入成功'); * } * ``` */ declare function writeJsonFileSync(filePath: string, data: T): VoidIOResult; /** * `unzip` 的同步版本,解压 zip 文件。 * @param zipFilePath - 要解压的 zip 文件路径。 * @param targetPath - 要解压到的目标文件夹路径。 * @returns 解压操作的结果。 * @since 1.3.0 * @example * ```ts * const result = unzipSync('/path/to/archive.zip', '/path/to/output'); * if (result.isOk()) { * console.log('解压成功'); * } * ``` */ declare function unzipSync(zipFilePath: string, targetPath: string): VoidIOResult; /** * 压缩文件或文件夹到内存。 * @param sourcePath - 需要压缩的文件(夹)路径。 * @param options - 可选的压缩参数。 * @returns 压缩后的 Uint8Array。 * @since 1.3.0 * @example * ```ts * const result = zipSync('/path/to/source'); * if (result.isOk()) { * console.log('压缩成功:', result.unwrap().length, 'bytes'); * } * ``` */ declare function zipSync(sourcePath: string, options?: ZipOptions): IOResult>; /** * `zip` 的同步版本,压缩文件或文件夹。 * @param sourcePath - 需要压缩的文件(夹)路径。 * @param zipFilePath - 压缩后的 zip 文件路径。 * @param options - 可选的压缩参数。 * @returns 压缩操作的结果。 * @since 1.3.0 * @example * ```ts * const result = zipSync('/path/to/source', '/path/to/archive.zip'); * if (result.isOk()) { * console.log('压缩成功'); * } * ``` */ declare function zipSync(sourcePath: string, zipFilePath: string, options?: ZipOptions): VoidIOResult; /** * 文件系统操作模块,提供同步和异步的文件读写、目录操作等功能。 * @module fs */ type mod$5_DownloadFileOptions = DownloadFileOptions; type mod$5_FileEncoding = FileEncoding; type mod$5_ReadFileContent = ReadFileContent; type mod$5_ReadOptions = ReadOptions; type mod$5_StatOptions = StatOptions; type mod$5_UnionDownloadFileOptions = UnionDownloadFileOptions; type mod$5_UnionUploadFileOptions = UnionUploadFileOptions; type mod$5_UploadFileOptions = UploadFileOptions; type mod$5_WriteFileContent = WriteFileContent; type mod$5_ZipFromUrlOptions = ZipFromUrlOptions; declare const mod$5_appendFile: typeof appendFile; declare const mod$5_appendFileSync: typeof appendFileSync; declare const mod$5_copy: typeof copy; declare const mod$5_copySync: typeof copySync; declare const mod$5_downloadFile: typeof downloadFile; declare const mod$5_emptyDir: typeof emptyDir; declare const mod$5_emptyDirSync: typeof emptyDirSync; declare const mod$5_exists: typeof exists; declare const mod$5_existsSync: typeof existsSync; declare const mod$5_mkdir: typeof mkdir; declare const mod$5_mkdirSync: typeof mkdirSync; declare const mod$5_move: typeof move; declare const mod$5_moveSync: typeof moveSync; declare const mod$5_readDir: typeof readDir; declare const mod$5_readDirSync: typeof readDirSync; declare const mod$5_readFile: typeof readFile; declare const mod$5_readFileSync: typeof readFileSync; declare const mod$5_readJsonFile: typeof readJsonFile; declare const mod$5_readJsonFileSync: typeof readJsonFileSync; declare const mod$5_readTextFile: typeof readTextFile; declare const mod$5_readTextFileSync: typeof readTextFileSync; declare const mod$5_remove: typeof remove; declare const mod$5_removeSync: typeof removeSync; declare const mod$5_stat: typeof stat; declare const mod$5_statSync: typeof statSync; declare const mod$5_unzip: typeof unzip; declare const mod$5_unzipFromUrl: typeof unzipFromUrl; declare const mod$5_unzipSync: typeof unzipSync; declare const mod$5_uploadFile: typeof uploadFile; declare const mod$5_writeFile: typeof writeFile; declare const mod$5_writeFileSync: typeof writeFileSync; declare const mod$5_writeJsonFile: typeof writeJsonFile; declare const mod$5_writeJsonFileSync: typeof writeJsonFileSync; declare const mod$5_zip: typeof zip; declare const mod$5_zipFromUrl: typeof zipFromUrl; declare const mod$5_zipSync: typeof zipSync; declare namespace mod$5 { export { mod$5_appendFile as appendFile, mod$5_appendFileSync as appendFileSync, mod$5_copy as copy, mod$5_copySync as copySync, mod$5_downloadFile as downloadFile, mod$5_emptyDir as emptyDir, mod$5_emptyDirSync as emptyDirSync, mod$5_exists as exists, mod$5_existsSync as existsSync, mod$5_mkdir as mkdir, mod$5_mkdirSync as mkdirSync, mod$5_move as move, mod$5_moveSync as moveSync, happyOpfs as opfs, mod$5_readDir as readDir, mod$5_readDirSync as readDirSync, mod$5_readFile as readFile, mod$5_readFileSync as readFileSync, mod$5_readJsonFile as readJsonFile, mod$5_readJsonFileSync as readJsonFileSync, mod$5_readTextFile as readTextFile, mod$5_readTextFileSync as readTextFileSync, mod$5_remove as remove, mod$5_removeSync as removeSync, mod$5_stat as stat, mod$5_statSync as statSync, mod$5_unzip as unzip, mod$5_unzipFromUrl as unzipFromUrl, mod$5_unzipSync as unzipSync, mod$5_uploadFile as uploadFile, mod$5_writeFile as writeFile, mod$5_writeFileSync as writeFileSync, mod$5_writeJsonFile as writeJsonFile, mod$5_writeJsonFileSync as writeJsonFileSync, mod$5_zip as zip, mod$5_zipFromUrl as zipFromUrl, mod$5_zipSync as zipSync }; export type { mod$5_DownloadFileOptions as DownloadFileOptions, mod$5_FileEncoding as FileEncoding, mod$5_ReadFileContent as ReadFileContent, mod$5_ReadOptions as ReadOptions, mod$5_StatOptions as StatOptions, mod$5_UnionDownloadFileOptions as UnionDownloadFileOptions, mod$5_UnionUploadFileOptions as UnionUploadFileOptions, mod$5_UploadFileOptions as UploadFileOptions, mod$5_WriteFileContent as WriteFileContent, mod$5_ZipFromUrlOptions as ZipFromUrlOptions }; } /** * 图片处理模块,提供从 URL 或文件创建图片的功能。 * @module image */ /** * 从URL创建图片。 * @param url - 图片URL。 * @returns Image对象。 * @since 1.7.0 * @example * ```ts * const img = createImageFromUrl('https://example.com/image.png'); * img.onload = () => { * console.log('图片加载完成', img.width, img.height); * }; * ``` */ declare function createImageFromUrl(url: string): HTMLImageElement | WechatMinigame.Image; /** * 从文件创建图片。 * @param filePath - 文件路径。 * @returns 异步的Image对象。 * @since 1.7.0 * @example * ```ts * const result = await createImageFromFile('/path/to/image.png'); * if (result.isOk()) { * const img = result.unwrap(); * console.log('图片尺寸:', img.width, 'x', img.height); * } * ``` */ declare function createImageFromFile(filePath: string): AsyncIOResult; declare const mod$4_createImageFromFile: typeof createImageFromFile; declare const mod$4_createImageFromUrl: typeof createImageFromUrl; declare namespace mod$4 { export { mod$4_createImageFromFile as createImageFromFile, mod$4_createImageFromUrl as createImageFromUrl, }; } /** * geo 坐标。 * @since 1.7.0 * @example * ```ts * import { lbs, type GeoPosition } from 'minigame-std'; * * const result = await lbs.getCurrentPosition(); * if (result.isOk()) { * const pos: GeoPosition = result.unwrap(); * console.log('纬度:', pos.latitude, '经度:', pos.longitude); * } * ``` */ interface GeoPosition { /** * 纬度。 */ latitude: number; /** * 经度。 */ longitude: number; } /** * 位置服务模块(Location Based Service),提供获取地理位置坐标的功能。 * @module lbs */ /** * 获取当前 geo 坐标。 * @returns 当前经纬度。 * @since 1.7.0 * @example * ```ts * const result = await getCurrentPosition(); * if (result.isOk()) { * const pos = result.unwrap(); * console.log('纬度:', pos.latitude); * console.log('经度:', pos.longitude); * } else { * console.error('获取位置失败:', result.unwrapErr()); * } * ``` */ declare function getCurrentPosition(): AsyncIOResult; type mod$3_GeoPosition = GeoPosition; declare const mod$3_getCurrentPosition: typeof getCurrentPosition; declare namespace mod$3 { export { mod$3_getCurrentPosition as getCurrentPosition }; export type { mod$3_GeoPosition as GeoPosition }; } /** * 网络状态,混合了 web 和小游戏环境。 * @since 1.0.9 * @example * ```ts * import { getNetworkType, type NetworkType } from 'minigame-std'; * * const networkType: NetworkType = await getNetworkType(); * if (networkType === 'wifi') { * console.log('当前使用 WiFi 网络'); * } * ``` */ type NetworkType = 'wifi' | 'slow-2g' | '2g' | '3g' | '4g' | '5g' | 'unknown' | 'none'; /** * 获取网络状态。 * @returns 根据浏览器支持情况不同,返回值可能为 `wifi` | `none` | `unknown` | `slow-2g` | `2g` | `3g` | `4g` * @since 1.0.9 * @example * ```ts * const networkType = await getNetworkType(); * console.log('当前网络类型:', networkType); * if (networkType === 'none') { * console.log('当前无网络连接'); * } * ``` */ declare function getNetworkType(): Promise; /** * 监听网络状态变化。 * @param listener - 网络状态变化的回调函数。 * @returns 返回一个函数,调用该函数可以移除监听器。 * @since 1.0.9 * @example * ```ts * const removeListener = addNetworkChangeListener((type) => { * console.log('网络状态变化:', type); * if (type === 'none') { * console.log('网络已断开'); * } * }); * * // 移除监听器 * removeListener(); * ``` */ declare function addNetworkChangeListener(listener: (type: NetworkType) => void): () => void; /** * 参见`performance.now()` * @returns 当前时间以毫秒为单位的时间戳 * @since 2.0.0 * @example * ```ts * const start = getPerformanceNow(); * // 执行一些操作... * const end = getPerformanceNow(); * console.log('耗时:', end - start, 'ms'); * ``` */ declare function getPerformanceNow(): number; /** * 平台类型,Web 或者小游戏。 * @since 1.0.0 * @example * ```ts * import { platform, type TargetType } from 'minigame-std'; * * const type: TargetType = platform.getTargetType(); * console.log(type); // 'minigame' 或 'web' * ``` */ type TargetType = 'minigame' | 'web'; /** * 获取当前的平台类型。 * @returns 返回当前的运行环境类型,可能是 'minigame' 或 'web'。 * @since 1.0.0 * @example * ```ts * const type = getTargetType(); * console.log('当前平台:', type); // 'minigame' 或 'web' * ``` */ declare function getTargetType(): TargetType; /** * 判断当前是否在 Web 环境中。 * @returns 如果在 Web 环境中返回 true,否则返回 false。 * @since 1.0.0 * @example * ```ts * if (isWeb()) { * console.log('当前在浏览器环境'); * } * ``` */ declare function isWeb(): boolean; /** * 判断当前是否在小游戏环境中。 * @returns 如果在小游戏环境中返回 true,否则返回 false。 * @since 1.0.0 * @example * ```ts * if (isMiniGame()) { * console.log('当前在小游戏环境'); * } * ``` */ declare function isMiniGame(): boolean; /** * 获取设备信息。 * @returns 返回小游戏的设备信息对象。 * @since 1.0.0 * @example * ```ts * const info = getDeviceInfo(); * console.log('设备平台:', info.platform); * console.log('设备品牌:', info.brand); * console.log('设备型号:', info.model); * ``` */ declare function getDeviceInfo(): DeviceInfo; /** * 获取设备性能等级, web 环境返回 -2。 * @returns 返回设备性能等级。 * @since 1.10.0 * @example * ```ts * const result = await getDeviceBenchmarkLevel(); * if (result.isOk()) { * const level = result.unwrap(); * if (level >= 30) { * console.log('高性能设备'); * } else if (level >= 20) { * console.log('中等性能设备'); * } else { * console.log('低性能设备'); * } * } * ``` */ declare function getDeviceBenchmarkLevel(): AsyncIOResult; /** * 获取窗口信息。 * @returns 包含窗口和屏幕相关信息的对象。 * @since 1.7.0 * @example * ```ts * const info = getWindowInfo(); * console.log('窗口尺寸:', info.windowWidth, 'x', info.windowHeight); * console.log('屏幕尺寸:', info.screenWidth, 'x', info.screenHeight); * console.log('设备像素比:', info.pixelRatio); * ``` */ declare function getWindowInfo(): WechatMinigame.WindowInfo; /** * 平台类型。 * @since 1.0.0 * @example * ```ts * import { platform, type Platform } from 'minigame-std'; * * const info = platform.getDeviceInfo(); * const devicePlatform: Platform = info.platform; * console.log(devicePlatform); // 'ios' | 'android' | 'mac' | ... * ``` */ type Platform = 'ios' | 'android' | 'mac' | 'windows' | 'ohos' | 'ohos_pc' | 'devtools' | 'linux' | 'unknown'; /** * 设备信息类型。 * 修正了 `memorySize` 的类型为 `number`(小游戏 API 实际返回数字,但官方类型定义错误地声明为 string)。 * @see https://github.com/wechat-miniprogram/minigame-api-typings/issues/27 * @since 1.0.0 * @example * ```ts * import { platform, type DeviceInfo } from 'minigame-std'; * * const info: DeviceInfo = platform.getDeviceInfo(); * console.log('平台:', info.platform); * console.log('内存:', info.memorySize, 'MB'); * ``` */ type DeviceInfo = Omit & { abi?: string; cpuType?: string; deviceAbi?: string; /** 设备内存大小,单位为 MB */ memorySize: number; /** 设备平台 */ platform: Platform; }; /** * 判断当前是否在小游戏的运行时环境中。 * @returns 如果在小游戏的运行时环境中返回 true,否则返回 false。 * @since 1.9.0 * @example * ```ts * if (isMiniGameRuntime()) { * console.log('在小游戏真机环境中'); * } * ``` */ declare function isMiniGameRuntime(): boolean; /** * 判断当前是否在小游戏的开发者工具中。 * @returns 如果在小游戏的开发者工具中返回 true,否则返回 false。 * @since 1.9.0 * @example * ```ts * if (isMiniGameDevtools()) { * console.log('在开发者工具中'); * } * ``` */ declare function isMiniGameDevtools(): boolean; /** * 判断当前是否在小游戏的 iOS 环境中。 * @returns 如果在小游戏的 iOS 环境中返回 true,否则返回 false。 * @since 1.9.0 * @example * ```ts * if (isMiniGameIOS()) { * console.log('在 iOS 设备上运行'); * } * ``` */ declare function isMiniGameIOS(): boolean; /** * 判断当前是否在小游戏的 Android 环境中。 * @returns 如果在小游戏的 Android 环境中返回 true,否则返回 false。 * @since 1.9.0 * @example * ```ts * if (isMiniGameAndroid()) { * console.log('在 Android 设备上运行'); * } * ``` */ declare function isMiniGameAndroid(): boolean; /** * 判断当前是否在小游戏的 Windows 环境中。 * @returns 如果在小游戏的 Windows 环境中返回 true,否则返回 false。 * @since 1.9.0 * @example * ```ts * if (isMiniGameWin()) { * console.log('在 Windows 设备上运行'); * } * ``` */ declare function isMiniGameWin(): boolean; /** * 判断当前是否在小游戏的 Mac 环境中。 * @returns 如果在小游戏的 Mac 环境中返回 true,否则返回 false。 * @since 1.9.0 * @example * ```ts * if (isMiniGameMac()) { * console.log('在 Mac 设备上运行'); * } * ``` */ declare function isMiniGameMac(): boolean; /** * 判断当前是否在小游戏的 HarmonyOS 环境中。 * @returns 如果在小游戏的 HarmonyOS 环境中返回 true,否则返回 false。 * @since 1.9.0 * @example * ```ts * if (isMiniGameHarmonyOS()) { * console.log('在 HarmonyOS 设备上运行'); * } * ``` */ declare function isMiniGameHarmonyOS(): boolean; /** * 平台信息模块,提供设备信息、平台检测等功能。 * @module platform */ type mod$2_DeviceInfo = DeviceInfo; type mod$2_Platform = Platform; type mod$2_TargetType = TargetType; declare const mod$2_getDeviceBenchmarkLevel: typeof getDeviceBenchmarkLevel; declare const mod$2_getDeviceInfo: typeof getDeviceInfo; declare const mod$2_getTargetType: typeof getTargetType; declare const mod$2_getWindowInfo: typeof getWindowInfo; declare const mod$2_isMiniGame: typeof isMiniGame; declare const mod$2_isMiniGameAndroid: typeof isMiniGameAndroid; declare const mod$2_isMiniGameDevtools: typeof isMiniGameDevtools; declare const mod$2_isMiniGameHarmonyOS: typeof isMiniGameHarmonyOS; declare const mod$2_isMiniGameIOS: typeof isMiniGameIOS; declare const mod$2_isMiniGameMac: typeof isMiniGameMac; declare const mod$2_isMiniGameRuntime: typeof isMiniGameRuntime; declare const mod$2_isMiniGameWin: typeof isMiniGameWin; declare const mod$2_isWeb: typeof isWeb; declare namespace mod$2 { export { mod$2_getDeviceBenchmarkLevel as getDeviceBenchmarkLevel, mod$2_getDeviceInfo as getDeviceInfo, mod$2_getTargetType as getTargetType, mod$2_getWindowInfo as getWindowInfo, mod$2_isMiniGame as isMiniGame, mod$2_isMiniGameAndroid as isMiniGameAndroid, mod$2_isMiniGameDevtools as isMiniGameDevtools, mod$2_isMiniGameHarmonyOS as isMiniGameHarmonyOS, mod$2_isMiniGameIOS as isMiniGameIOS, mod$2_isMiniGameMac as isMiniGameMac, mod$2_isMiniGameRuntime as isMiniGameRuntime, mod$2_isMiniGameWin as isMiniGameWin, mod$2_isWeb as isWeb }; export type { mod$2_DeviceInfo as DeviceInfo, mod$2_Platform as Platform, mod$2_TargetType as TargetType }; } /** * WebSocket 连接状态,小游戏环境可用。 * @since 1.6.0 * @example * ```ts * import { SocketReadyState, connectSocket } from 'minigame-std'; * * const socket = connectSocket('wss://example.com'); * if (socket.readyState === SocketReadyState.OPEN) { * console.log('连接已打开'); * } * ``` */ declare const SocketReadyState: { /** * WebSocket.CONNECTING */ readonly CONNECTING: 0; /** * WebSocket.OPEN */ readonly OPEN: 1; /** * WebSocket.CLOSING */ readonly CLOSING: 2; /** * WebSocket.CLOSED */ readonly CLOSED: 3; }; /** * WebSocket 事件监听器映射接口,定义了与 WebSocket 事件对应的回调函数类型。 * @since 1.0.0 * @example * ```ts * import type { SocketListenerMap } from 'minigame-std'; * * const onMessage: SocketListenerMap['message'] = (data) => { * console.log('收到消息:', data); * }; * ``` */ interface SocketListenerMap { /** * 当 WebSocket 连接成功打开时触发。 */ open(): void; /** * 当 WebSocket 连接关闭时触发。 * @param code - 表示关闭连接的状态码。 * @param reason - 表示关闭连接的原因。 */ close(code: number, reason: string): void; /** * 当 WebSocket 接收到消息时触发。 * @param data - 接收到的消息数据,可以是字符串或者 ArrayBuffer。 */ message(data: string | ArrayBuffer): void; /** * 当 WebSocket 连接发生错误时触发。 * @param err - 发生的错误对象。 */ error(err: Error): void; } /** * WebSocket 接口定义,描述了 WebSocket 的基本操作方法。 * @since 1.0.0 * @example * ```ts * import type { ISocket } from 'minigame-std'; * * function handleSocket(socket: ISocket) { * socket.addEventListener('message', (data) => { * console.log('收到:', data); * }); * socket.send('Hello'); * } * ``` */ interface ISocket { /** * WebSocket 的连接状态。 */ readonly readyState: number; /** * 添加事件监听器到 WebSocket 对象。 * @typeParam K - 限定为 WebSocketEventMap 的键类型。 * @param type - 事件类型,如 'open', 'close', 'message', 'error'。 * @param listener - 对应事件的监听器回调函数。 * @returns 返回对应的`removeEventListener代理函数`。 */ addEventListener(type: K, listener: SocketListenerMap[K]): () => void; /** * 发送数据到 WebSocket 服务器。 * @param data - 要发送的数据,可以是字符串、ArrayBuffer 或 ArrayBufferView。 * @returns 返回一个 Promise,其解析为发送结果,成功时返回 true,失败时返回 Error。 */ send(data: DataSource): AsyncVoidIOResult; /** * 关闭 WebSocket 连接。 * @param code - 可选的状态码,表示关闭连接的原因。 * @param reason - 可选的字符串,解释为什么要关闭连接。 */ close(code?: number, reason?: string): void; } /** * 创建Socket的可选参数。 * @since 1.0.0 * @example * ```ts * import { connectSocket, type SocketOptions } from 'minigame-std'; * * const options: SocketOptions = { * protocols: ['protocol1', 'protocol2'], * header: { 'Authorization': 'Bearer token' }, * }; * const socket = connectSocket('wss://example.com', options); * ``` */ type SocketOptions = Omit; /** * WebSocket 模块,提供创建和管理 WebSocket 连接的功能。 * @module socket */ /** * 创建并返回一个 WebSocket 连接。 * @param url - WebSocket 服务器的 URL。 * @param options - 可选的参数。 * @returns 返回一个实现了 ISocket 接口的 WebSocket 对象。 * @since 1.0.0 * @example * ```ts * const socket = connectSocket('wss://echo.websocket.org'); * * socket.addEventListener('open', () => { * console.log('连接已建立'); * socket.send('Hello, Server!'); * }); * * socket.addEventListener('message', (data) => { * console.log('收到消息:', data); * }); * * socket.addEventListener('close', (code, reason) => { * console.log('连接已关闭:', code, reason); * }); * * socket.addEventListener('error', (error) => { * console.error('连接错误:', error); * }); * * // 关闭连接 * socket.close(); * ``` */ declare function connectSocket(url: string, options?: SocketOptions): IOResult; /** * 本地存储模块,提供同步和异步的键值对存储功能。 * @module storage */ /** * 将数据存储在本地缓存中。 * @param key - 数据的键名。 * @param data - 要存储的数据。 * @returns 存储操作的异步结果。 * @since 1.0.0 * @example * ```ts * const result = await setItem('username', 'john'); * if (result.isOk()) { * console.log('存储成功'); * } * ``` */ declare function setItem(key: string, data: string): AsyncVoidIOResult; /** * 从本地缓存中读取数据。 * @param key - 数据的键名。 * @returns 包含数据的异步结果,如果不存在则返回空字符串。 * @since 1.0.0 * @example * ```ts * const result = await getItem('username'); * if (result.isOk()) { * console.log('用户名:', result.unwrap()); * } * ``` */ declare function getItem(key: string): AsyncIOResult; /** * 从本地缓存中移除指定的数据。 * @param key - 数据的键名。 * @returns 移除操作的异步结果。 * @since 1.0.0 * @example * ```ts * const result = await removeItem('username'); * if (result.isOk()) { * console.log('移除成功'); * } * ``` */ declare function removeItem(key: string): AsyncVoidIOResult; /** * 清除所有的本地存储数据。 * @returns 清除操作的异步结果。 * @since 1.0.0 * @example * ```ts * const result = await clear(); * if (result.isOk()) { * console.log('所有数据已清除'); * } * ``` */ declare function clear(): AsyncVoidIOResult; /** * 获取本地存储数据的项数。 * @returns 包含存储项数的异步结果。 * @since 1.2.0 * @example * ```ts * const result = await getLength(); * if (result.isOk()) { * console.log('存储项数:', result.unwrap()); * } * ``` */ declare function getLength(): AsyncIOResult; /** * 检查本地存储中是否存在指定的数据。 * @param key - 数据的键名。 * @returns 包含是否存在的布尔值的异步结果。 * @since 1.9.3 * @example * ```ts * const result = await hasItem('username'); * if (result.isOk() && result.unwrap()) { * console.log('键存在'); * } * ``` */ declare function hasItem(key: string): AsyncIOResult; /** * `setItem` 的同步版本,将数据存储在本地缓存中。 * @param key - 数据的键名。 * @param data - 要存储的数据。 * @returns 存储操作的结果。 * @since 1.0.0 * @example * ```ts * const result = setItemSync('username', 'john'); * if (result.isOk()) { * console.log('存储成功'); * } * ``` */ declare function setItemSync(key: string, data: string): VoidIOResult; /** * `getItem` 的同步版本,从本地缓存中读取数据。 * @param key - 数据的键名。 * @returns 包含数据的操作结果。 * @since 1.0.0 * @example * ```ts * const result = getItemSync('username'); * if (result.isOk()) { * console.log('用户名:', result.unwrap()); * } * ``` */ declare function getItemSync(key: string): IOResult; /** * `removeItem` 的同步版本,从本地缓存中移除指定的数据。 * @param key - 数据的键名。 * @returns 移除操作的结果。 * @since 1.0.0 * @example * ```ts * const result = removeItemSync('username'); * if (result.isOk()) { * console.log('移除成功'); * } * ``` */ declare function removeItemSync(key: string): VoidIOResult; /** * `clear` 的同步版本,清除所有的本地存储数据。 * @returns 清除操作的结果。 * @since 1.0.0 * @example * ```ts * const result = clearSync(); * if (result.isOk()) { * console.log('所有数据已清除'); * } * ``` */ declare function clearSync(): VoidIOResult; /** * `getLength` 的同步版本,获取本地存储数据的项数。 * @returns 包含存储项数的操作结果。 * @since 1.2.0 * @example * ```ts * const result = getLengthSync(); * if (result.isOk()) { * console.log('存储项数:', result.unwrap()); * } * ``` */ declare function getLengthSync(): IOResult; /** * `hasItem` 的同步版本,检查本地存储中是否存在指定的数据。 * @param key - 数据的键名。 * @returns 包含是否存在的布尔值的操作结果。 * @since 1.9.3 * @example * ```ts * const result = hasItemSync('username'); * if (result.isOk() && result.unwrap()) { * console.log('键存在'); * } * ``` */ declare function hasItemSync(key: string): IOResult; declare const mod$1_clear: typeof clear; declare const mod$1_clearSync: typeof clearSync; declare const mod$1_getItem: typeof getItem; declare const mod$1_getItemSync: typeof getItemSync; declare const mod$1_getLength: typeof getLength; declare const mod$1_getLengthSync: typeof getLengthSync; declare const mod$1_hasItem: typeof hasItem; declare const mod$1_hasItemSync: typeof hasItemSync; declare const mod$1_removeItem: typeof removeItem; declare const mod$1_removeItemSync: typeof removeItemSync; declare const mod$1_setItem: typeof setItem; declare const mod$1_setItemSync: typeof setItemSync; declare namespace mod$1 { export { mod$1_clear as clear, mod$1_clearSync as clearSync, mod$1_getItem as getItem, mod$1_getItemSync as getItemSync, mod$1_getLength as getLength, mod$1_getLengthSync as getLengthSync, mod$1_hasItem as hasItem, mod$1_hasItemSync as hasItemSync, mod$1_removeItem as removeItem, mod$1_removeItemSync as removeItemSync, mod$1_setItem as setItem, mod$1_setItemSync as setItemSync, }; } /** * 将小游戏异步 API 转换为返回 `AsyncResult` 的新函数,需要转换的 API 必须是接受可选 `success` 和 `fail` 回调的函数,并且其返回值必须是 `void` 或 `PromiseLike`。 * * 其中 `T` 为 `success` 回调的参数类型,`E` 为 `fail` 回调的参数类型。 * * @param api - 小游戏异步 API。 * @returns 返回一个新的函数,该函数返回 `AsyncResult`。 * @since 2.0.0 * @example * ```ts * // 将 wx.setStorage 转换为 AsyncResult 风格 * const setStorageAsync = asyncResultify(wx.setStorage); * const result = await setStorageAsync({ key: 'test', data: 'value' }); * if (result.isOk()) { * console.log('存储成功'); * } else { * console.error('存储失败:', result.unwrapErr()); * } * ``` */ declare function asyncResultify unknown, T = ResultifySuccessType, E = ResultifyFailType>(api: F): ResultifyValidAPI extends true ? (...args: Parameters) => AsyncResult : never; /** * `asyncResultify` 的变体,将小游戏异步 API 转换为返回 `AsyncIOResult` 的新函数。 * * 与 `asyncResultify` 不同的是,此函数会将 `fail` 回调的 `WechatMinigame.GeneralCallbackResult` 转换为 `Error` 类型。 * * @param api - 小游戏异步 API。 * @returns 返回一个新的函数,该函数返回 `AsyncIOResult`。 * @since 2.0.0 * @example * ```ts * // 将 wx.setStorage 转换为 AsyncIOResult 风格 * const setStorageAsync = asyncIOResultify(wx.setStorage); * const result = await setStorageAsync({ key: 'test', data: 'value' }); * if (result.isOk()) { * console.log('存储成功'); * } else { * console.error('存储失败:', result.unwrapErr().message); * } * ``` */ declare function asyncIOResultify unknown, T = ResultifySuccessType>(api: F): IOResultifyValidAPI extends true ? (...args: Parameters) => AsyncIOResult : never; /** * 将小游戏同步 API 转换为返回 `IOResult` 的新函数。 * * 功能类似于 `tryGeneralSyncOp`,但以函数包装的方式使用,将可能抛出的异常捕获并转换为 `IOResult`。 * * @param api - 小游戏同步 API。 * @returns 返回一个新的函数,该函数返回 `IOResult`。 * @since 2.0.0 * @example * ```ts * // 将 wx.getStorageSync 转换为 IOResult 风格 * const getStorageSync = syncIOResultify(wx.getStorageSync); * const result = getStorageSync('test'); * if (result.isOk()) { * console.log('获取成功:', result.unwrap()); * } else { * console.error('获取失败:', result.unwrapErr().message); * } * ``` */ declare function syncIOResultify unknown>(api: F): (...args: Parameters) => IOResult>; /** * 通用回调函数类型。 */ type AnyCallback = (...args: never[]) => unknown; /** * 类型工具:判断 API 是否符合 resultify 条件。 * * 要求 API 返回 `void` 或 `PromiseLike`,且参数包含 `success` 或 `fail` 回调。 * @typeParam T - 待检查的 API 函数类型。 */ type ResultifyValidAPI = T extends (params: infer P) => infer R ? R extends void | PromiseLike ? P extends { success?: AnyCallback; } | undefined ? true : P extends { fail?: AnyCallback; } | undefined ? true : false : false : false; /** * 类型工具:判断 API 是否符合 asyncIOResultify 条件。 * * 在 `ResultifyValidAPI` 基础上,额外要求 `fail` 回调参数类型必须精确为 `GeneralCallbackResult`。 * @typeParam T - 待检查的 API 函数类型。 */ type IOResultifyValidAPI = ResultifyValidAPI extends true ? ResultifyFailType extends WechatMinigame.GeneralCallbackResult ? WechatMinigame.GeneralCallbackResult extends ResultifyFailType ? true : false : false : false; /** * 类型工具:提取成功回调参数类型。 * * 从 API 函数的 `success` 回调中提取返回类型。 * @typeParam T - API 函数类型。 */ type ResultifySuccessType = T extends (params: infer P) => unknown ? P extends { success?: (res: infer S) => unknown; } ? S : never : never; /** * 类型工具:提取失败回调参数类型。 * * 从 API 函数的 `fail` 回调中提取错误类型。 * @typeParam T - API 函数类型。 */ type ResultifyFailType = T extends (params: infer P) => unknown ? P extends { fail?: (err: infer E) => unknown; } ? E : never : never; /** * 创建视频播放器。 * @param options - 视频配置选项。 * @returns Video对象。 * @since 2.0.0 * @example * ```ts * const video = createVideo({ * src: 'https://example.com/video.mp4', * width: 640, * height: 360, * autoplay: false, * }); * video.play(); * // 销毁视频 * video.destroy(); * ``` */ declare function createVideo(options: WechatMinigame.CreateVideoOption): WechatMinigame.Video; declare const mod_createVideo: typeof createVideo; declare namespace mod { export { mod_createVideo as createVideo, }; } export { SocketReadyState, addErrorListener, addNetworkChangeListener, addResizeListener, addUnhandledrejectionListener, asyncIOResultify, asyncResultify, mod$9 as audio, mod$8 as clipboard, connectSocket, mod$6 as cryptos, decodeUtf8, encodeUtf8, fetchT, mod$5 as fs, getNetworkType, getPerformanceNow, mod$4 as image, mod$3 as lbs, mod$2 as platform, mod$1 as storage, syncIOResultify, mod as video }; export type { DataSource, ISocket, MinaFetchInit, NetworkType, SocketListenerMap, SocketOptions, UnionFetchInit };