minigame-std
Version:
Mini Game Standard Development Library.
1,653 lines (1,617 loc) • 72.2 kB
JavaScript
'use strict';
var invariant = require('tiny-invariant');
var happyRusty = require('happy-rusty');
var happyOpfs = require('happy-opfs');
var posix = require('@std/path/posix');
var fflate = require('fflate/browser');
var tinyFuture = require('tiny-future');
var rsaOaepEncryption = require('rsa-oaep-encryption');
var fetchT$1 = require('@happy-ts/fetch-t');
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var happyOpfs__namespace = /*#__PURE__*/_interopNamespaceDefault(happyOpfs);
var fflate__namespace = /*#__PURE__*/_interopNamespaceDefault(fflate);
function assertString(str) {
invariant(typeof str === "string", () => `Param must be a string but received ${str}`);
}
function assertSafeUrl(url) {
invariant(typeof url === "string", () => `Url must be a string but received ${url}`);
invariant(url.startsWith("https://"), () => `Url must start with https:// but received ${url}`);
}
function assertSafeSocketUrl(url) {
invariant(typeof url === "string", () => `SocketUrl must be a string but received ${url}`);
invariant(url.startsWith("wss://"), () => `SocketUrl must start with wss:// but received ${url}`);
}
function isMinaEnv() {
return __MINIGAME_STD_MINA__;
}
function convertFileSystemHandleLikeToStats(handleLike) {
const { kind } = handleLike;
const isFile = kind === "file";
const isDirectory = kind === "directory";
let size = 0;
let lastModifiedTime = 0;
if (isFile) {
const file = handleLike;
size = file.size;
lastModifiedTime = file.lastModified;
}
const stats = {
isFile: () => isFile,
isDirectory: () => isDirectory,
size,
lastModifiedTime,
lastAccessedTime: 0,
mode: 0
};
return stats;
}
async function convertFileSystemHandleToStats(handle) {
const handleLike = await happyOpfs.toFileSystemHandleLike(handle);
return convertFileSystemHandleLikeToStats(handleLike);
}
function createAbortError() {
const error = new Error();
error.name = happyOpfs.ABORT_ERROR;
return error;
}
function promisifyWithResult(api) {
return (...args) => {
const future = new tinyFuture.Future();
const options = args[0] ?? {};
const { success, fail } = options;
options.success = (res2) => {
success?.(res2);
future.resolve(happyRusty.Ok(res2));
};
options.fail = (err) => {
fail?.(err);
future.resolve(happyRusty.Err(err));
};
const res = api(options);
if (res instanceof Promise) {
return happyRusty.promiseToAsyncResult(res);
} else if (res != null) {
throw new Error("API must return void or Promise. Otherwise the return value will be discarded.");
}
return future.promise;
};
}
function miniGameFailureToError(err) {
return new Error(err.errMsg ?? err.message);
}
function miniGameFailureToResult(err) {
return happyRusty.Err(miniGameFailureToError(err));
}
function tryGeneralSyncOp(op) {
try {
return happyRusty.Ok(op());
} catch (e) {
return miniGameFailureToResult(e);
}
}
async function tryGeneralAsyncOp(op) {
try {
return happyRusty.Ok(await op());
} catch (e) {
return miniGameFailureToResult(e);
}
}
function tryDOMSyncOp(op) {
try {
return happyRusty.Ok(op());
} catch (e) {
return happyRusty.Err(e);
}
}
async function tryDOMAsyncOp(op) {
try {
return happyRusty.Ok(await op());
} catch (e) {
return happyRusty.Err(e);
}
}
function bufferSource2U8a(data) {
if (data instanceof Uint8Array) {
return data;
}
if (data instanceof ArrayBuffer) {
return new Uint8Array(data);
}
if (ArrayBuffer.isView(data)) {
return new Uint8Array(data.byteOffset === 0 ? data.buffer : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength));
}
throw new TypeError(`BufferSource is not ArrayBuffer or ArrayBufferView`);
}
function bufferSource2Ab(data) {
if (data instanceof ArrayBuffer) {
return data;
}
if (ArrayBuffer.isView(data)) {
return data.byteOffset === 0 ? data.buffer : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
}
throw new TypeError(`BufferSource is not ArrayBuffer or ArrayBufferView`);
}
let fs;
function getFs() {
fs ??= wx.getFileSystemManager();
return fs;
}
let rootPath;
let rootUsrPath;
function getRootUsrPath() {
rootUsrPath ??= wx.env.USER_DATA_PATH;
rootPath ??= rootUsrPath.slice(0, rootUsrPath.indexOf("usr"));
return rootUsrPath;
}
function getAbsolutePath(path) {
assertString(path);
const usrPath = getRootUsrPath();
if (path.startsWith(rootPath)) {
return path;
}
happyOpfs.assertAbsolutePath(path);
return usrPath + path;
}
function isNotFoundIOError(err) {
return err.errCode === 1300002 || (err.errMsg ?? err.message).includes("no such file or directory");
}
function isAlreadyExistsIOError(err) {
return err.errCode === 1301005 || (err.errMsg ?? err.message).includes("already exists");
}
function fileErrorToResult(err) {
const error = miniGameFailureToError(err);
if (isNotFoundIOError(err)) {
error.name = happyOpfs.NOT_FOUND_ERROR;
}
return happyRusty.Err(error);
}
function isNotFoundError(err) {
return err.name === happyOpfs.NOT_FOUND_ERROR;
}
function errToMkdirResult(err) {
return isAlreadyExistsIOError(err) ? happyRusty.RESULT_VOID : fileErrorToResult(err);
}
function getReadFileEncoding(options) {
let encoding = options?.encoding;
if (!encoding || encoding === "binary") {
encoding = void 0;
}
return encoding;
}
function errToRemoveResult(err) {
return isNotFoundIOError(err) ? happyRusty.RESULT_VOID : fileErrorToResult(err);
}
function getWriteFileContents(contents) {
const isBin = typeof contents !== "string";
const encoding = isBin ? void 0 : "utf8";
const data = isBin ? bufferSource2Ab(contents) : contents;
const res = {
data,
encoding
};
return res;
}
function getExistsResult(statsResult, options) {
return statsResult.andThen((stats) => {
const { isDirectory = false, isFile = false } = options ?? {};
if (isDirectory && isFile) {
throw new TypeError("ExistsOptions.isDirectory and ExistsOptions.isFile must not be true together.");
}
const notExist = isDirectory && stats.isFile() || isFile && stats.isDirectory();
return happyRusty.Ok(!notExist);
}).orElse((err) => {
return isNotFoundError(err) ? happyRusty.RESULT_FALSE : happyRusty.Err(err);
});
}
async function mkdir$1(dirPath) {
const absPath = getAbsolutePath(dirPath);
if (absPath === getRootUsrPath()) {
return happyRusty.RESULT_VOID;
}
const statRes = await stat$1(absPath);
if (statRes.isOk()) {
return happyRusty.RESULT_VOID;
}
const future = new tinyFuture.Future();
getFs().mkdir({
dirPath: absPath,
recursive: true,
success() {
future.resolve(happyRusty.RESULT_VOID);
},
fail(err) {
future.resolve(errToMkdirResult(err));
}
});
return future.promise;
}
function move$1(srcPath, destPath) {
const absSrcPath = getAbsolutePath(srcPath);
const absDestPath = getAbsolutePath(destPath);
const future = new tinyFuture.Future();
getFs().rename({
oldPath: absSrcPath,
newPath: absDestPath,
success() {
future.resolve(happyRusty.RESULT_VOID);
},
fail(err) {
future.resolve(fileErrorToResult(err));
}
});
return future.promise;
}
function readDir$1(dirPath) {
const absPath = getAbsolutePath(dirPath);
const future = new tinyFuture.Future();
getFs().readdir({
dirPath: absPath,
success(res) {
future.resolve(happyRusty.Ok(res.files));
},
fail(err) {
future.resolve(fileErrorToResult(err));
}
});
return future.promise;
}
function readFile$1(filePath, options) {
const absPath = getAbsolutePath(filePath);
const encoding = getReadFileEncoding(options);
const future = new tinyFuture.Future();
getFs().readFile({
filePath: absPath,
encoding,
success(res) {
future.resolve(happyRusty.Ok(res.data));
},
fail(err) {
future.resolve(fileErrorToResult(err));
}
});
return future.promise;
}
async function remove$1(path) {
const statRes = await stat$1(path);
if (statRes.isErr()) {
return isNotFoundError(statRes.unwrapErr()) ? happyRusty.RESULT_VOID : statRes.asErr();
}
const absPath = getAbsolutePath(path);
const future = new tinyFuture.Future();
if (statRes.unwrap().isDirectory()) {
getFs().rmdir({
dirPath: absPath,
recursive: true,
success() {
future.resolve(happyRusty.RESULT_VOID);
},
fail(err) {
future.resolve(errToRemoveResult(err));
}
});
} else {
getFs().unlink({
filePath: absPath,
success() {
future.resolve(happyRusty.RESULT_VOID);
},
fail(err) {
future.resolve(errToRemoveResult(err));
}
});
}
return future.promise;
}
function stat$1(path, options) {
const absPath = getAbsolutePath(path);
const future = new tinyFuture.Future();
getFs().stat({
path: absPath,
recursive: options?.recursive ?? false,
success(res) {
future.resolve(happyRusty.Ok(res.stats));
},
fail(err) {
future.resolve(fileErrorToResult(err));
}
});
return future.promise;
}
async function writeFile$1(filePath, contents, options) {
const absPath = getAbsolutePath(filePath);
const { append = false, create = true } = options ?? {};
if (create) {
const res = await mkdir$1(posix.dirname(absPath));
if (res.isErr()) {
return res;
}
}
const fs = getFs();
let method = fs.writeFile;
if (append) {
const res = await exists$1(absPath);
if (res.isErr()) {
return res.asErr();
}
if (res.unwrap()) {
method = fs.appendFile;
}
}
const { data, encoding } = getWriteFileContents(contents);
const future = new tinyFuture.Future();
method({
filePath: absPath,
data,
encoding,
success() {
future.resolve(happyRusty.RESULT_VOID);
},
fail(err) {
future.resolve(fileErrorToResult(err));
}
});
return future.promise;
}
function appendFile$1(filePath, contents) {
return writeFile$1(filePath, contents, {
append: true
});
}
function copyFile(srcPath, destPath) {
const future = new tinyFuture.Future();
getFs().copyFile({
srcPath,
destPath,
success() {
future.resolve(happyRusty.RESULT_VOID);
},
fail(err) {
future.resolve(fileErrorToResult(err));
}
});
return future.promise;
}
async function copy$1(srcPath, destPath) {
const absSrcPath = getAbsolutePath(srcPath);
const absDestPath = getAbsolutePath(destPath);
return (await stat$1(absSrcPath, {
recursive: true
})).andThenAsync(async (statsArray) => {
if (Array.isArray(statsArray)) {
for (const { path, stats } of statsArray) {
const srcEntryPath = absSrcPath + path;
const destEntryPath = absDestPath + path;
const res = await (stats.isDirectory() ? mkdir$1(destEntryPath) : copyFile(srcEntryPath, destEntryPath));
if (res.isErr()) {
return res;
}
}
return happyRusty.RESULT_VOID;
} else {
return (await mkdir$1(posix.dirname(absDestPath))).andThenAsync(() => {
return copyFile(absSrcPath, absDestPath);
});
}
});
}
async function exists$1(path, options) {
const res = await stat$1(path);
return getExistsResult(res, options);
}
async function emptyDir$1(dirPath) {
const res = await readDir$1(dirPath);
if (res.isErr()) {
return isNotFoundError(res.unwrapErr()) ? mkdir$1(dirPath) : res.asErr();
}
const tasks = res.unwrap().map((name) => remove$1(posix.join(dirPath, name)));
const allRes = await Promise.all(tasks);
const fail = allRes.find((x) => x.isErr());
return fail ?? happyRusty.RESULT_VOID;
}
async function readJsonFile$1(filePath) {
return (await readTextFile$1(filePath)).andThenAsync(async (contents) => {
try {
return happyRusty.Ok(JSON.parse(contents));
} catch (e) {
return happyRusty.Err(e);
}
});
}
function readTextFile$1(filePath) {
return readFile$1(filePath, {
encoding: "utf8"
});
}
function downloadFile$1(fileUrl, filePath, options) {
assertSafeUrl(fileUrl);
let absFilePath = void 0;
if (typeof filePath === "string") {
absFilePath = getAbsolutePath(filePath);
} else {
options = filePath;
}
const {
onProgress,
...rest
} = options ?? {};
let aborted = false;
const future = new tinyFuture.Future();
let task;
const download = () => {
task = wx.downloadFile({
...rest,
url: fileUrl,
filePath: absFilePath,
async success(res) {
if (aborted) {
future.resolve(happyRusty.Err(createAbortError()));
return;
}
const { statusCode } = res;
if (statusCode >= 200 && statusCode < 300) {
future.resolve(happyRusty.Ok(res));
return;
}
if (res.filePath) {
await remove$1(res.filePath);
}
future.resolve(happyRusty.Err(new Error(statusCode.toString())));
},
fail(err) {
future.resolve(aborted ? happyRusty.Err(createAbortError()) : miniGameFailureToResult(err));
}
});
if (typeof onProgress === "function") {
task.onProgressUpdate((res) => {
const { totalBytesExpectedToWrite, totalBytesWritten } = res;
onProgress(typeof totalBytesExpectedToWrite === "number" && typeof totalBytesWritten === "number" ? happyRusty.Ok({
totalByteLength: totalBytesExpectedToWrite,
completedByteLength: totalBytesWritten
}) : happyRusty.Err(new Error(`Unknown download progress ${totalBytesWritten}/${totalBytesExpectedToWrite}`)));
});
}
};
if (typeof absFilePath === "string" && absFilePath) {
mkdir$1(posix.dirname(absFilePath)).then((res) => {
if (aborted) {
future.resolve(happyRusty.Err(createAbortError()));
return;
}
if (res.isErr()) {
future.resolve(res.asErr());
return;
}
download();
});
} else {
download();
}
return {
abort() {
aborted = true;
task?.abort();
},
get aborted() {
return aborted;
},
get response() {
return future.promise;
}
};
}
function uploadFile$1(filePath, fileUrl, options) {
assertSafeUrl(fileUrl);
const absPath = getAbsolutePath(filePath);
let aborted = false;
const future = new tinyFuture.Future();
const task = wx.uploadFile({
name: posix.basename(filePath),
...options,
url: fileUrl,
filePath: absPath,
success(res) {
future.resolve(happyRusty.Ok(res));
},
fail(err) {
future.resolve(miniGameFailureToResult(err));
}
});
return {
abort() {
aborted = true;
task?.abort();
},
get aborted() {
return aborted;
},
get response() {
return future.promise;
}
};
}
function unzip$1(zipFilePath, targetPath) {
const absZipPath = getAbsolutePath(zipFilePath);
const absTargetPath = getAbsolutePath(targetPath);
const future = new tinyFuture.Future();
getFs().unzip({
zipFilePath: absZipPath,
targetPath: absTargetPath,
success() {
future.resolve(happyRusty.RESULT_VOID);
},
fail(err) {
future.resolve(fileErrorToResult(err));
}
});
return future.promise;
}
async function unzipFromUrl$1(zipFileUrl, targetPath, options) {
return (await downloadFile$1(zipFileUrl, options).response).andThenAsync(({ tempFilePath }) => {
return unzip$1(tempFilePath, targetPath);
});
}
async function zip$1(sourcePath, zipFilePath, options) {
const absSourcePath = getAbsolutePath(sourcePath);
let absZipFilePath;
if (typeof zipFilePath === "string") {
absZipFilePath = getAbsolutePath(zipFilePath);
} else {
options = zipFilePath;
}
return (await stat$1(absSourcePath)).andThenAsync(async (stats) => {
const zipped = {};
const sourceName = posix.basename(absSourcePath);
if (stats.isFile()) {
const res = await readFile$1(absSourcePath);
if (res.isErr()) {
return res.asErr();
}
zipped[sourceName] = new Uint8Array(res.unwrap());
} else {
const res = await stat$1(absSourcePath, {
recursive: true
});
if (res.isErr()) {
return res.asErr();
}
const preserveRoot = options?.preserveRoot ?? true;
for (const { path, stats: stats2 } of res.unwrap()) {
if (stats2.isFile()) {
const entryName = preserveRoot ? posix.join(sourceName, path) : path;
const res2 = await readFile$1(absSourcePath + path);
if (res2.isErr()) {
return res2.asErr();
}
zipped[entryName] = new Uint8Array(res2.unwrap());
}
}
}
const future = new tinyFuture.Future();
fflate__namespace.zip(zipped, {
consume: true
}, async (err, u8a) => {
if (err) {
future.resolve(happyRusty.Err(err));
return;
}
if (absZipFilePath) {
const res = await writeFile$1(absZipFilePath, u8a);
future.resolve(res);
} else {
future.resolve(happyRusty.Ok(u8a));
}
});
return await future.promise;
});
}
async function zipFromUrl$1(sourceUrl, zipFilePath, options) {
if (typeof zipFilePath !== "string") {
options = zipFilePath;
zipFilePath = void 0;
}
return (await downloadFile$1(sourceUrl, options).response).andThenAsync(async ({ tempFilePath }) => {
return await (zipFilePath ? zip$1(tempFilePath, zipFilePath, options) : zip$1(tempFilePath, options));
});
}
function mkdir(dirPath) {
return (isMinaEnv() ? mkdir$1 : happyOpfs.mkdir)(dirPath);
}
function move(srcPath, destPath) {
return (isMinaEnv() ? move$1 : happyOpfs.move)(srcPath, destPath);
}
async function readDir(dirPath) {
if (isMinaEnv()) {
return readDir$1(dirPath);
}
return (await happyOpfs.readDir(dirPath)).andThenAsync(async (entries) => {
const items = [];
for await (const { path } of entries) {
items.push(path);
}
return happyRusty.Ok(items);
});
}
function readFile(filePath) {
return (isMinaEnv() ? readFile$1 : happyOpfs.readFile)(filePath);
}
function remove(path) {
return (isMinaEnv() ? remove$1 : happyOpfs.remove)(path);
}
async function stat(path, options) {
if (isMinaEnv()) {
return await stat$1(path, options);
}
return (await happyOpfs.stat(path)).andThenAsync(async (handle) => {
const entryStats = await convertFileSystemHandleToStats(handle);
if (entryStats.isFile() || !options?.recursive) {
return happyRusty.Ok(entryStats);
}
return (await happyOpfs.readDir(path)).andThenAsync(async (entries) => {
const statsArr = [{
path,
stats: entryStats
}];
for await (const { path: path2, handle: handle2 } of entries) {
statsArr.push({
path: path2,
stats: await convertFileSystemHandleToStats(handle2)
});
}
return happyRusty.Ok(statsArr);
});
});
}
function writeFile(filePath, contents, options) {
return (isMinaEnv() ? writeFile$1 : happyOpfs.writeFile)(filePath, contents, options);
}
function appendFile(filePath, contents) {
return (isMinaEnv() ? appendFile$1 : happyOpfs.appendFile)(filePath, contents);
}
function copy(srcPath, destPath) {
return (isMinaEnv() ? copy$1 : happyOpfs.copy)(srcPath, destPath);
}
function exists(path) {
return (isMinaEnv() ? exists$1 : happyOpfs.exists)(path);
}
function emptyDir(dirPath) {
return (isMinaEnv() ? emptyDir$1 : happyOpfs.emptyDir)(dirPath);
}
function readJsonFile(filePath) {
return (isMinaEnv() ? readJsonFile$1 : happyOpfs.readJsonFile)(filePath);
}
function readTextFile(filePath) {
return (isMinaEnv() ? readTextFile$1 : happyOpfs.readTextFile)(filePath);
}
function downloadFile(fileUrl, filePath, options) {
if (typeof filePath === "string") {
return isMinaEnv() ? downloadFile$1(fileUrl, filePath, options) : happyOpfs.downloadFile(fileUrl, filePath, options);
} else {
return isMinaEnv() ? downloadFile$1(fileUrl, filePath) : happyOpfs.downloadFile(fileUrl, filePath);
}
}
function uploadFile(filePath, fileUrl, options) {
return (isMinaEnv() ? uploadFile$1 : happyOpfs.uploadFile)(filePath, fileUrl, options);
}
function unzip(zipFilePath, targetPath) {
return (isMinaEnv() ? unzip$1 : happyOpfs.unzip)(zipFilePath, targetPath);
}
async function unzipFromUrl(zipFileUrl, targetPath, options) {
return (isMinaEnv() ? unzipFromUrl$1 : happyOpfs.unzipFromUrl)(zipFileUrl, targetPath, options);
}
function zip(sourcePath, zipFilePath, options) {
if (typeof zipFilePath === "string") {
return isMinaEnv() ? zip$1(sourcePath, zipFilePath, options) : happyOpfs.zip(sourcePath, zipFilePath, options);
} else {
return isMinaEnv() ? zip$1(sourcePath, zipFilePath) : happyOpfs.zip(sourcePath, zipFilePath);
}
}
function zipFromUrl(sourceUrl, zipFilePath, options) {
if (typeof zipFilePath === "string") {
return isMinaEnv() ? zipFromUrl$1(sourceUrl, zipFilePath, options) : happyOpfs.zipFromUrl(sourceUrl, zipFilePath, options);
} else {
return isMinaEnv() ? zipFromUrl$1(sourceUrl, zipFilePath) : happyOpfs.zipFromUrl(sourceUrl, zipFilePath);
}
}
function trySyncOp(op, errToResult = fileErrorToResult) {
try {
const res = op();
return happyRusty.Ok(res);
} catch (e) {
return errToResult(e);
}
}
function mkdirSync$1(dirPath) {
const absPath = getAbsolutePath(dirPath);
return trySyncOp(() => getFs().mkdirSync(absPath, true), errToMkdirResult);
}
function moveSync$1(srcPath, destPath) {
const absSrcPath = getAbsolutePath(srcPath);
const absDestPath = getAbsolutePath(destPath);
return trySyncOp(() => getFs().renameSync(absSrcPath, absDestPath));
}
function readDirSync$1(dirPath) {
const absPath = getAbsolutePath(dirPath);
return trySyncOp(() => getFs().readdirSync(absPath));
}
function readFileSync$1(filePath, options) {
const absPath = getAbsolutePath(filePath);
const encoding = getReadFileEncoding(options);
return trySyncOp(() => getFs().readFileSync(absPath, encoding));
}
function removeSync$1(path) {
const statRes = statSync$1(path);
if (statRes.isErr()) {
return isNotFoundError(statRes.unwrapErr()) ? happyRusty.RESULT_VOID : statRes.asErr();
}
const absPath = getAbsolutePath(path);
return trySyncOp(() => {
if (statRes.unwrap().isDirectory()) {
getFs().rmdirSync(absPath, true);
} else {
getFs().unlinkSync(absPath);
}
}, errToRemoveResult);
}
function statSync$1(path, options) {
const absPath = getAbsolutePath(path);
return trySyncOp(() => getFs().statSync(absPath, options?.recursive ?? false));
}
function writeFileSync$1(filePath, contents, options) {
const absPath = getAbsolutePath(filePath);
const { append = false, create = true } = options ?? {};
if (create) {
const res = mkdirSync$1(posix.dirname(absPath));
if (res.isErr()) {
return res;
}
}
const { data, encoding } = getWriteFileContents(contents);
return trySyncOp(() => (append ? getFs().appendFileSync : getFs().writeFileSync)(absPath, data, encoding));
}
function appendFileSync$1(filePath, contents) {
return writeFileSync$1(filePath, contents, {
append: true
});
}
function copyFileSync(srcPath, destPath) {
return trySyncOp(() => getFs().copyFile({
srcPath,
destPath
}));
}
function copySync$1(srcPath, destPath) {
const absSrcPath = getAbsolutePath(srcPath);
const absDestPath = getAbsolutePath(destPath);
return statSync$1(absSrcPath, {
recursive: true
}).andThen((statsArray) => {
if (Array.isArray(statsArray)) {
for (const { path, stats } of statsArray) {
const srcEntryPath = absSrcPath + path;
const destEntryPath = absDestPath + path;
const res = stats.isDirectory() ? mkdirSync$1(destEntryPath) : copyFileSync(srcEntryPath, destEntryPath);
if (res.isErr()) {
return res;
}
}
return happyRusty.RESULT_VOID;
} else {
return copyFileSync(absSrcPath, absDestPath);
}
});
}
function existsSync$1(path, options) {
const res = statSync$1(path);
return getExistsResult(res, options);
}
function emptyDirSync$1(dirPath) {
const res = readDirSync$1(dirPath);
if (res.isErr()) {
return isNotFoundError(res.unwrapErr()) ? mkdirSync$1(dirPath) : res.asErr();
}
for (const name of res.unwrap()) {
const res2 = removeSync$1(posix.join(dirPath, name));
if (res2.isErr()) {
return res2.asErr();
}
}
return happyRusty.RESULT_VOID;
}
function readJsonFileSync$1(filePath) {
return readTextFileSync$1(filePath).andThen((contents) => {
try {
return happyRusty.Ok(JSON.parse(contents));
} catch (e) {
return happyRusty.Err(e);
}
});
}
function readTextFileSync$1(filePath) {
return readFileSync$1(filePath, {
encoding: "utf8"
});
}
function unzipSync$1(zipFilePath, targetPath) {
const absZipPath = getAbsolutePath(zipFilePath);
const absTargetPath = getAbsolutePath(targetPath);
return readFileSync$1(absZipPath).andThen((buffer) => {
const data = new Uint8Array(buffer);
try {
const unzipped = fflate__namespace.unzipSync(data);
for (const path in unzipped) {
if (path.at(-1) !== posix.SEPARATOR) {
const res = writeFileSync$1(`${absTargetPath}/${path}`, unzipped[path]);
if (res.isErr()) {
return res.asErr();
}
}
}
return happyRusty.RESULT_VOID;
} catch (e) {
return happyRusty.Err(e);
}
});
}
function zipSync$1(sourcePath, zipFilePath, options) {
const absSourcePath = getAbsolutePath(sourcePath);
const absZipPath = getAbsolutePath(zipFilePath);
return statSync$1(absSourcePath).andThen((stats) => {
const zipped = {};
const sourceName = posix.basename(absSourcePath);
if (stats.isFile()) {
const res = readFileSync$1(absSourcePath);
if (res.isErr()) {
return res.asErr();
}
zipped[sourceName] = new Uint8Array(res.unwrap());
} else {
const res = statSync$1(absSourcePath, {
recursive: true
});
if (res.isErr()) {
return res.asErr();
}
const preserveRoot = options?.preserveRoot ?? true;
for (const { path, stats: stats2 } of res.unwrap()) {
if (stats2.isFile()) {
const entryName = preserveRoot ? posix.join(sourceName, path) : path;
const res2 = readFileSync$1(absSourcePath + path);
if (res2.isErr()) {
return res2.asErr();
}
zipped[entryName] = new Uint8Array(res2.unwrap());
}
}
}
try {
const u8a = fflate__namespace.zipSync(zipped);
return writeFileSync$1(absZipPath, u8a);
} catch (e) {
return happyRusty.Err(e);
}
});
}
function mkdirSync(dirPath) {
return (isMinaEnv() ? mkdirSync$1 : happyOpfs.mkdirSync)(dirPath);
}
function moveSync(srcPath, destPath) {
return (isMinaEnv() ? moveSync$1 : happyOpfs.moveSync)(srcPath, destPath);
}
function readDirSync(dirPath) {
return isMinaEnv() ? readDirSync$1(dirPath) : happyOpfs.readDirSync(dirPath).map((x) => {
return x.map((y) => y.path);
});
}
function readFileSync(filePath) {
return (isMinaEnv() ? readFileSync$1 : happyOpfs.readFileSync)(filePath);
}
function removeSync(path) {
return (isMinaEnv() ? removeSync$1 : happyOpfs.removeSync)(path);
}
function statSync(path, options) {
if (isMinaEnv()) {
return statSync$1(path, options);
}
return happyOpfs.statSync(path).andThen((handleLike) => {
const entryStats = convertFileSystemHandleLikeToStats(handleLike);
if (entryStats.isFile() || !options?.recursive) {
return happyRusty.Ok(entryStats);
}
return happyOpfs.readDirSync(path).andThen((entries) => {
const statsArr = [{
path,
stats: entryStats
}];
for (const { path: path2, handle } of entries) {
statsArr.push({
path: path2,
stats: convertFileSystemHandleLikeToStats(handle)
});
}
return happyRusty.Ok(statsArr);
});
});
}
function writeFileSync(filePath, contents) {
return (isMinaEnv() ? writeFileSync$1 : happyOpfs.writeFileSync)(filePath, contents);
}
function copySync(srcPath, destPath) {
return (isMinaEnv() ? copySync$1 : happyOpfs.copySync)(srcPath, destPath);
}
function appendFileSync(filePath, contents) {
return (isMinaEnv() ? appendFileSync$1 : happyOpfs.appendFileSync)(filePath, contents);
}
function existsSync(path) {
return (isMinaEnv() ? existsSync$1 : happyOpfs.existsSync)(path);
}
function emptyDirSync(dirPath) {
return (isMinaEnv() ? emptyDirSync$1 : happyOpfs.emptyDirSync)(dirPath);
}
function readJsonFileSync(filePath) {
return (isMinaEnv() ? readJsonFileSync$1 : happyOpfs.readJsonFileSync)(filePath);
}
function readTextFileSync(filePath) {
return (isMinaEnv() ? readTextFileSync$1 : happyOpfs.readTextFileSync)(filePath);
}
function unzipSync(zipFilePath, targetPath) {
return (isMinaEnv() ? unzipSync$1 : happyOpfs.unzipSync)(zipFilePath, targetPath);
}
function zipSync(sourcePath, zipFilePath, options) {
return (isMinaEnv() ? zipSync$1 : happyOpfs.zipSync)(sourcePath, zipFilePath, options);
}
var mod$8 = /*#__PURE__*/Object.freeze({
__proto__: null,
appendFile: appendFile,
appendFileSync: appendFileSync,
copy: copy,
copySync: copySync,
downloadFile: downloadFile,
emptyDir: emptyDir,
emptyDirSync: emptyDirSync,
exists: exists,
existsSync: existsSync,
mkdir: mkdir,
mkdirSync: mkdirSync,
move: move,
moveSync: moveSync,
opfs: happyOpfs__namespace,
readDir: readDir,
readDirSync: readDirSync,
readFile: readFile,
readFileSync: readFileSync,
readJsonFile: readJsonFile,
readJsonFileSync: readJsonFileSync,
readTextFile: readTextFile,
readTextFileSync: readTextFileSync,
remove: remove,
removeSync: removeSync,
stat: stat,
statSync: statSync,
unzip: unzip,
unzipFromUrl: unzipFromUrl,
unzipSync: unzipSync,
uploadFile: uploadFile,
writeFile: writeFile,
writeFileSync: writeFileSync,
zip: zip,
zipFromUrl: zipFromUrl,
zipSync: zipSync
});
let audioContext;
function getGlobalAudioContext() {
audioContext ??= createWebAudioContext();
return audioContext;
}
async function closeGlobalAudioContext() {
try {
await audioContext?.close();
audioContext = null;
return happyRusty.RESULT_VOID;
} catch (e) {
return happyRusty.Err(e);
}
}
function createWebAudioContext() {
return isMinaEnv() ? wx.createWebAudioContext() : new AudioContext();
}
function playWebAudioFromAudioBuffer(buffer, options) {
const {
loop = false,
autoDisconnect = true
} = options ?? {};
const context = getGlobalAudioContext();
const source = context.createBufferSource();
source.buffer = buffer;
source.loop = loop;
source.connect(context.destination);
if (autoDisconnect) {
source.onended = () => {
source.disconnect();
};
}
source.start();
return source;
}
async function playWebAudioFromArrayBuffer(buffer, options) {
const context = getGlobalAudioContext();
const audioBuffer = await context.decodeAudioData(bufferSource2Ab(buffer));
return playWebAudioFromAudioBuffer(audioBuffer, options);
}
async function playWebAudioFromFile(filePath, options) {
return (await readFile(filePath)).andThenAsync(async (buffer) => {
return happyRusty.Ok(await playWebAudioFromArrayBuffer(buffer, options));
});
}
var mod$7 = /*#__PURE__*/Object.freeze({
__proto__: null,
closeGlobalAudioContext: closeGlobalAudioContext,
createWebAudioContext: createWebAudioContext,
getGlobalAudioContext: getGlobalAudioContext,
playWebAudioFromArrayBuffer: playWebAudioFromArrayBuffer,
playWebAudioFromAudioBuffer: playWebAudioFromAudioBuffer,
playWebAudioFromFile: playWebAudioFromFile
});
const FORMAT = "utf8";
function textEncode$2(data) {
return typeof wx.encode === "function" ? wx.encode({
data,
format: FORMAT
}) : utf8String2AB(data);
}
function textDecode$2(data) {
return typeof wx.decode === "function" ? wx.decode({
data,
format: FORMAT
}) : ab2Utf8String(data);
}
function utf8String2AB(str) {
const utf8 = [];
for (let i = 0; i < str.length; i++) {
const codePoint = str.charCodeAt(i);
if (codePoint < 128) {
utf8.push(codePoint);
} else if (codePoint < 2048) {
utf8.push(192 | codePoint >> 6, 128 | codePoint & 63);
} else if (codePoint < 65536) {
utf8.push(224 | codePoint >> 12, 128 | codePoint >> 6 & 63, 128 | codePoint & 63);
} else if (codePoint < 1114112) {
utf8.push(240 | codePoint >> 18, 128 | codePoint >> 12 & 63, 128 | codePoint >> 6 & 63, 128 | codePoint & 63);
}
}
return new Uint8Array(utf8).buffer;
}
function ab2Utf8String(data) {
const u8a = new Uint8Array(data);
let str = "";
let i = 0;
while (i < u8a.length) {
const byte1 = u8a[i];
if (byte1 < 128) {
str += String.fromCharCode(byte1);
i += 1;
} else if (byte1 < 224) {
const byte2 = u8a[i + 1];
str += String.fromCharCode((byte1 & 31) << 6 | byte2 & 63);
i += 2;
} else if (byte1 < 240) {
const byte2 = u8a[i + 1];
const byte3 = u8a[i + 2];
str += String.fromCharCode((byte1 & 15) << 12 | (byte2 & 63) << 6 | byte3 & 63);
i += 3;
} else if (byte1 < 248) {
const byte2 = u8a[i + 1];
const byte3 = u8a[i + 2];
const byte4 = u8a[i + 3];
str += String.fromCharCode((byte1 & 7) << 18 | (byte2 & 63) << 12 | (byte3 & 63) << 6 | byte4 & 63);
i += 4;
} else {
throw new Error("Invalid UTF-8 byte sequence");
}
}
return str;
}
let encoder;
let decoder;
function getEncoder() {
encoder ??= new TextEncoder();
return encoder;
}
function getDecoder() {
decoder ??= new TextDecoder();
return decoder;
}
function textEncode$1(data) {
return getEncoder().encode(data);
}
function textDecode$1(data) {
return getDecoder().decode(data);
}
function textEncode(data) {
return isMinaEnv() ? bufferSource2U8a(textEncode$2(data)) : textEncode$1(data);
}
function textDecode(data) {
return isMinaEnv() ? textDecode$2(bufferSource2Ab(data)) : textDecode$1(data);
}
function hexFromBuffer(buffer) {
return Array.from(bufferSource2U8a(buffer)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
}
function byteStringToBuffer(str) {
const { length } = str;
const u8a = new Uint8Array(length);
for (let i = 0; i < length; i++) {
u8a[i] = str.charCodeAt(i);
}
return u8a;
}
function byteStringFromBuffer(buffer) {
return String.fromCharCode(...bufferSource2U8a(buffer));
}
function toByteString(data) {
const buffer = typeof data === "string" ? textEncode(data) : data;
return byteStringFromBuffer(buffer);
}
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const base64abc = chars.split("");
const lookup = (() => {
const lookupTemp = new Uint8Array(256);
for (let i = 0; i < base64abc.length; i++) {
lookupTemp[base64abc[i].charCodeAt(0)] = i;
}
return lookupTemp;
})();
function base64FromBuffer(data) {
let result = "";
const u8a = bufferSource2U8a(data);
const len = u8a.length;
let i;
for (i = 2; i < len; i += 3) {
result += base64abc[u8a[i - 2] >> 2];
result += base64abc[(u8a[i - 2] & 3) << 4 | u8a[i - 1] >> 4];
result += base64abc[(u8a[i - 1] & 15) << 2 | u8a[i] >> 6];
result += base64abc[u8a[i] & 63];
}
if (i === len + 1) {
result += base64abc[u8a[i - 2] >> 2];
result += base64abc[(u8a[i - 2] & 3) << 4];
result += "==";
}
if (i === len) {
result += base64abc[u8a[i - 2] >> 2];
result += base64abc[(u8a[i - 2] & 3) << 4 | u8a[i - 1] >> 4];
result += base64abc[(u8a[i - 1] & 15) << 2];
result += "=";
}
return result;
}
function base64ToBuffer(data) {
const len = data.length;
let bufferLength = len * 0.75;
if (data[len - 1] === "=") {
bufferLength--;
if (data[len - 2] === "=") {
bufferLength--;
}
}
const u8a = new Uint8Array(bufferLength);
let pos = 0;
for (let i = 0; i < len; i += 4) {
const encoded1 = lookup[data.charCodeAt(i)];
const encoded2 = lookup[data.charCodeAt(i + 1)];
const encoded3 = lookup[data.charCodeAt(i + 2)];
const encoded4 = lookup[data.charCodeAt(i + 3)];
u8a[pos++] = encoded1 << 2 | encoded2 >> 4;
u8a[pos++] = (encoded2 & 15) << 4 | encoded3 >> 2;
u8a[pos++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return u8a;
}
function encodeBase64$2(data) {
return base64FromBuffer(textEncode(data));
}
function decodeBase64$2(data) {
return textDecode(base64ToBuffer(data));
}
function encodeBase64$1(data) {
return btoa(byteStringFromBuffer(textEncode(data)));
}
function decodeBase64$1(data) {
return textDecode(byteStringToBuffer(atob(data)));
}
function encodeBase64(data) {
return (isMinaEnv() ? encodeBase64$2 : encodeBase64$1)(data);
}
function decodeBase64(data) {
return (isMinaEnv() ? decodeBase64$2 : decodeBase64$1)(data);
}
async function writeText$2(data) {
assertString(data);
return tryGeneralAsyncOp(async () => {
await wx.setClipboardData({
data
});
});
}
async function readText$2() {
return tryGeneralAsyncOp(async () => {
const res = await wx.getClipboardData();
return res.data;
});
}
async function writeText$1(data) {
assertString(data);
return tryDOMAsyncOp(async () => {
await navigator.clipboard.writeText(data);
});
}
async function readText$1() {
return tryDOMAsyncOp(async () => {
const data = await navigator.clipboard.readText();
return data;
});
}
function writeText(data) {
return (isMinaEnv() ? writeText$2 : writeText$1)(data);
}
function readText() {
return (isMinaEnv() ? readText$2 : readText$1)();
}
var mod$6 = /*#__PURE__*/Object.freeze({
__proto__: null,
readText: readText,
writeText: writeText
});
function createHMAC$1(sha, key) {
let shaAlgorithmCreator;
switch (sha.replace("-", "").toLowerCase()) {
case "sha1": {
shaAlgorithmCreator = rsaOaepEncryption.sha1;
break;
}
case "sha256": {
shaAlgorithmCreator = rsaOaepEncryption.sha256;
break;
}
case "sha384": {
shaAlgorithmCreator = rsaOaepEncryption.sha384;
break;
}
case "sha512": {
shaAlgorithmCreator = rsaOaepEncryption.sha512;
break;
}
default: {
throw new Error(`Unsupported hash algorithm ${sha}`);
}
}
const shaAlgorithm = shaAlgorithmCreator.create();
let keyBuffer = new rsaOaepEncryption.ByteStringBuffer(key);
let keylen = keyBuffer.length();
if (keylen > shaAlgorithm.blockLength) {
shaAlgorithm.start();
shaAlgorithm.update(keyBuffer.bytes());
keyBuffer = shaAlgorithm.digest();
}
const ipadding = new rsaOaepEncryption.ByteStringBuffer();
const opadding = new rsaOaepEncryption.ByteStringBuffer();
keylen = keyBuffer.length();
for (let i = 0; i < keylen; ++i) {
const tmp = keyBuffer.at(i);
ipadding.putByte(54 ^ tmp);
opadding.putByte(92 ^ tmp);
}
if (keylen < shaAlgorithm.blockLength) {
const tmp = shaAlgorithm.blockLength - keylen;
for (let i = 0; i < tmp; ++i) {
ipadding.putByte(54);
opadding.putByte(92);
}
}
shaAlgorithm.start();
shaAlgorithm.update(ipadding.bytes());
const ctx = {
/**
* Updates the HMAC with the given message bytes.
*
* @param bytes the bytes to update with.
*/
update(bytes) {
shaAlgorithm.update(bytes);
},
/**
* Produces the Message Authentication Code (MAC).
*
* @return a byte buffer containing the digest value.
*/
digest() {
const inner = shaAlgorithm.digest().bytes();
shaAlgorithm.start();
shaAlgorithm.update(opadding.bytes());
shaAlgorithm.update(inner);
return shaAlgorithm.digest();
}
};
return ctx;
}
async function createHMAC(hash, key, data) {
const encodedKey = typeof key === "string" ? textEncode(key) : key;
const encodedData = typeof data === "string" ? textEncode(data) : data;
const cryptoKey = await crypto.subtle.importKey(
"raw",
// 密钥格式
encodedKey,
// 密钥数据
{ name: "HMAC", hash: { name: hash } },
// 算法
false,
// 是否可导出
["sign"]
// 用途
);
const hashBuffer = await crypto.subtle.sign(
"HMAC",
// 算法
cryptoKey,
// 密钥
encodedData
// 消息
);
return hexFromBuffer(hashBuffer);
}
function shaHMAC(sha, key, data) {
if (isMinaEnv()) {
const hmac = createHMAC$1(sha, toByteString(key));
hmac.update(toByteString(data));
return Promise.resolve(hmac.digest().toHex());
}
return createHMAC(sha, key, data);
}
function sha1HMAC(key, data) {
return shaHMAC("SHA-1", key, data);
}
function sha256HMAC(key, data) {
return shaHMAC("SHA-256", key, data);
}
function sha384HMAC(key, data) {
return shaHMAC("SHA-384", key, data);
}
function sha512HMAC(key, data) {
return shaHMAC("SHA-512", key, data);
}
const BLOCK_SIZE = 64;
class Md5 {
a = 1732584193;
b = 4023233417;
c = 2562383102;
d = 271733878;
block = new Uint8Array(BLOCK_SIZE);
pos = 0;
n0 = 0;
n1 = 0;
addLength(len) {
let n0 = this.n0;
n0 += len;
if (n0 > 4294967295) this.n1 += 1;
this.n0 = n0 >>> 0;
}
hash(block) {
let a = this.a;
let b = this.b;
let c = this.c;
let d = this.d;
const blk = (i) => block[i] | block[i + 1] << 8 | block[i + 2] << 16 | block[i + 3] << 24;
const rol32 = (x, n) => x << n | x >>> 32 - n;
const x0 = blk(0);
const x1 = blk(4);
const x2 = blk(8);
const x3 = blk(12);
const x4 = blk(16);
const x5 = blk(20);
const x6 = blk(24);
const x7 = blk(28);
const x8 = blk(32);
const x9 = blk(36);
const xa = blk(40);
const xb = blk(44);
const xc = blk(48);
const xd = blk(52);
const xe = blk(56);
const xf = blk(60);
a = b + rol32(((c ^ d) & b ^ d) + a + x0 + 3614090360, 7);
d = a + rol32(((b ^ c) & a ^ c) + d + x1 + 3905402710, 12);
c = d + rol32(((a ^ b) & d ^ b) + c + x2 + 606105819, 17);
b = c + rol32(((d ^ a) & c ^ a) + b + x3 + 3250441966, 22);
a = b + rol32(((c ^ d) & b ^ d) + a + x4 + 4118548399, 7);
d = a + rol32(((b ^ c) & a ^ c) + d + x5 + 1200080426, 12);
c = d + rol32(((a ^ b) & d ^ b) + c + x6 + 2821735955, 17);
b = c + rol32(((d ^ a) & c ^ a) + b + x7 + 4249261313, 22);
a = b + rol32(((c ^ d) & b ^ d) + a + x8 + 1770035416, 7);
d = a + rol32(((b ^ c) & a ^ c) + d + x9 + 2336552879, 12);
c = d + rol32(((a ^ b) & d ^ b) + c + xa + 4294925233, 17);
b = c + rol32(((d ^ a) & c ^ a) + b + xb + 2304563134, 22);
a = b + rol32(((c ^ d) & b ^ d) + a + xc + 1804603682, 7);
d = a + rol32(((b ^ c) & a ^ c) + d + xd + 4254626195, 12);
c = d + rol32(((a ^ b) & d ^ b) + c + xe + 2792965006, 17);
b = c + rol32(((d ^ a) & c ^ a) + b + xf + 1236535329, 22);
a = b + rol32(((b ^ c) & d ^ c) + a + x1 + 4129170786, 5);
d = a + rol32(((a ^ b) & c ^ b) + d + x6 + 3225465664, 9);
c = d + rol32(((d ^ a) & b ^ a) + c + xb + 643717713, 14);
b = c + rol32(((c ^ d) & a ^ d) + b + x0 + 3921069994, 20);
a = b + rol32(((b ^ c) & d ^ c) + a + x5 + 3593408605, 5);
d = a + rol32(((a ^ b) & c ^ b) + d + xa + 38016083, 9);
c = d + rol32(((d ^ a) & b ^ a) + c + xf + 3634488961, 14);
b = c + rol32(((c ^ d) & a ^ d) + b + x4 + 3889429448, 20);
a = b + rol32(((b ^ c) & d ^ c) + a + x9 + 568446438, 5);
d = a + rol32(((a ^ b) & c ^ b) + d + xe + 3275163606, 9);
c = d + rol32(((d ^ a) & b ^ a) + c + x3 + 4107603335, 14);
b = c + rol32(((c ^ d) & a ^ d) + b + x8 + 1163531501, 20);
a = b + rol32(((b ^ c) & d ^ c) + a + xd + 2850285829, 5);
d = a + rol32(((a ^ b) & c ^ b) + d + x2 + 4243563512, 9);
c = d + rol32(((d ^ a) & b ^ a) + c + x7 + 1735328473, 14);
b = c + rol32(((c ^ d) & a ^ d) + b + xc + 2368359562, 20);
a = b + rol32((b ^ c ^ d) + a + x5 + 4294588738, 4);
d = a + rol32((a ^ b ^ c) + d + x8 + 2272392833, 11);
c = d + rol32((d ^ a ^ b) + c + xb + 1839030562, 16);
b = c + rol32((c ^ d ^ a) + b + xe + 4259657740, 23);
a = b + rol32((b ^ c ^ d) + a + x1 + 2763975236, 4);
d = a + rol32((a ^ b ^ c) + d + x4 + 1272893353, 11);
c = d + rol32((d ^ a ^ b) + c + x7 + 4139469664, 16);
b = c + rol32((c ^ d ^ a) + b + xa + 3200236656, 23);
a = b + rol32((b ^ c ^ d) + a + xd + 681279174, 4);
d = a + rol32((a ^ b ^ c) + d + x0 + 3936430074, 11);
c = d + rol32((d ^ a ^ b) + c + x3 + 3572445317, 16);
b = c + rol32((c ^ d ^ a) + b + x6 + 76029189, 23);
a = b + rol32((b ^ c ^ d) + a + x9 + 3654602809, 4);
d = a + rol32((a ^ b ^ c) + d + xc + 3873151461, 11);
c = d + rol32((d ^ a ^ b) + c + xf + 530742520, 16);
b = c + rol32((c ^ d ^ a) + b + x2 + 3299628645, 23);
a = b + rol32((c ^ (b | ~d)) + a + x0 + 4096336452, 6);
d = a + rol32((b ^ (a | ~c)) + d + x7 + 1126891415, 10);
c = d + rol32((a ^ (d | ~b)) + c + xe + 2878612391, 15);
b = c + rol32((d ^ (c | ~a)) + b + x5 + 4237533241, 21);
a = b + rol32((c ^ (b | ~d)) + a + xc + 1700485571, 6);
d = a + rol32((b ^ (a | ~c)) + d + x3 + 2399980690, 10);
c = d + rol32((a ^ (d | ~b)) + c + xa + 4293915773, 15);
b = c + rol32((d ^ (c | ~a)) + b + x1 + 2240044497, 21);
a = b + rol32((c ^ (b | ~d)) + a + x8 + 1873313359, 6);
d = a + rol32((b ^ (a | ~c)) + d + xf + 4264355552, 10);
c = d + rol32((a ^ (d | ~b)) + c + x6 + 2734768916, 15);
b = c + rol32((d ^ (c | ~a)) + b + xd + 1309151649, 21);
a = b + rol32((c ^ (b | ~d)) + a + x4 + 4149444226, 6);
d = a + rol32((b ^ (a | ~c)) + d + xb + 3174756917, 10);
c = d + rol32((a ^ (d | ~b)) + c + x2 + 718787259, 15);
b = c + rol32((d ^ (c | ~a)) + b + x9 + 3951481745, 21);
this.a = this.a + a >>> 0;
this.b = this.b + b >>> 0;
this.c = this.c + c >>> 0;
this.d = this.d + d >>> 0;
}
/**
* Update internal state.
* @param data data to update, data cannot exceed 2^32 bytes.
*/
update(data) {
const msg = typeof data === "string" ? textEncode(data) : bufferSource2U8a(data);
let pos = this.pos;
const free = BLOCK_SIZE - pos;
if (msg.length < free) {
this.block.set(msg, pos);
pos += msg.length;
} else {
this.block.set(msg.slice(0, free), pos);
this.hash(this.block);
let i = free;
while (i + BLOCK_SIZE <= msg.length) {
this.hash(msg.slice(i, i + BLOCK_SIZE));
i += BLOCK_SIZE;
}
this.block.fill(0).set(msg.slice(i), 0);
pos = msg.length - i;
}
this.pos = pos;
this.addLength(msg.length);
return this;
}
/**
* Returns final hash.
*/
digest() {
let padLen = BLOCK_SIZE - this.pos;
if (padLen < 9) padLen += BLOCK_SIZE;
const pad = new Uint8Array(padLen);
pad[0] = 128;
const n0 = this.n0 << 3;
const n1 = this.n1 << 3 | this.n0 >>> 29;
pad[pad.length - 8] = n0 & 255;
pad[pad.length - 7] = n0 >>> 8 & 255;
pad[pad.length - 6] = n0 >>> 16 & 255;
pad[pad.length - 5] = n0 >>> 24 & 255;
pad[pad.length - 4] = n1 & 255;
pad[pad.length - 3] = n1 >>> 8 & 255;
pad[pad.length - 2] = n1 >>> 16 & 255;
pad[pad.length - 1] = n1 >>> 24 & 255;
this.update(pad.buffer);
const hash = new ArrayBuffer(16);
const hashView = new DataView(hash);
hashView.setUint32(0, this.a, true);
hashView.setUint32(4, this.b, true);
hashView.setUint32(8, this.c, true);
hashView.setUint32(12, this.d, true);
return hash;
}
/**
* Returns hash as a hex string.
*/
toString() {
return hexFromBuffer(this.digest());
}
}
function md5(data) {
return new Md5().update(data).toString();
}
function getRandomValues$2(length) {
const future = new tinyFuture.Future();
wx.getUserCryptoManager().getRandomValues({
length,
success(res) {
future.resolve(happyRusty.Ok(new Uint8Array(res.randomValues)));
},
fail(err) {
future.resolve(miniGameFailureToResult(err));
}
});
return future.promise;
}
async function randomUUID$2() {
return (await getRandomValues$2(16)).map((bytes) => {
bytes[6] = bytes[6] & 15 | 64;
bytes[8] = bytes[8] & 63 | 128;
const hex = hexFromBuffer(bytes);
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
});
}
function getRandomValues$1(length) {
const u8a = new Uint8Array(length);
crypto.getRandomValues(u8a);
return u8a;
}
function randomUUID$1() {
return crypto.randomUUID();
}
function getRandomValues(length) {
return isMinaEnv() ? getRandomValues$2(length) : Promise.resolve(happyRusty.Ok(getRandomValues$1(length)));
}
function randomUUID() {
return isMinaEnv() ? randomUUID$2() : Promise.resolve(happyRusty.Ok(randomUUID$1()));
}
const SHAs = {
"sha1": rsaOaepEncryption.sha1,
"sha256": rsaOaepEncryption.sha256,
"sha384": rsaOaepEncryption.sha384,
"sha512": rsaOaepEncryption.sha512
};
function importPublicKey$2(pem, hash) {
const publicKey = rsaOaepEncryption.importPublicKey(pem);
const encrypt = (data) => {
const sha = hash.replace("-", "").toLowerCase();
return publicKey.encrypt(data, SHAs[sha].create());
};
return {
encrypt(data) {
return Promise.resolve(encrypt(data));
},
encryptToString(data) {