repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
stan-js | github_2023 | codemask-labs | typescript | getAction | const getAction = <K extends TKey>(key: K) => actions[getActionKey(key)] as (value: unknown) => void | // @ts-expect-error - TS doesn't know that all keys are in actions object | https://github.com/codemask-labs/stan-js/blob/2bee695bc462a15d4fc5f4fe610ddabbe81ae3b2/src/vanilla/createStore.ts#L43-L43 | 2bee695bc462a15d4fc5f4fe610ddabbe81ae3b2 |
nuxt-oidc-auth | github_2023 | itpropro | typescript | refresh | async function refresh(): Promise<void> {
const currentProvider = sessionState.value?.provider || undefined
sessionState.value = (await useRequestFetch()('/api/_auth/refresh', {
headers: {
Accept: 'text/json',
},
method: 'POST',
}).catch(() => login()) as UserSession)
if (!loggedIn.value) {
await logout(currentProvider)
}
} | /**
* Manually refreshes the authentication session.
*
* @returns {Promise<void>}
*/ | https://github.com/itpropro/nuxt-oidc-auth/blob/bc044d93f213d9e5e732c9c114181acc9e5fb94a/src/runtime/composables/oidcAuth.ts#L28-L39 | bc044d93f213d9e5e732c9c114181acc9e5fb94a |
nuxt-oidc-auth | github_2023 | itpropro | typescript | login | async function login(provider?: ProviderKeys | 'dev', params?: Record<string, string>): Promise<void> {
const queryParams = params ? `?${new URLSearchParams(params).toString()}` : ''
await navigateTo(`/auth${provider ? `/${provider}` : ''}/login${queryParams}`, { external: true, redirectCode: 302 })
} | /**
* Signs in the user by navigating to the appropriate sign-in URL.
*
* @param {ProviderKeys | 'dev'} [provider] - The authentication provider to use. If not specified, uses the default provider.
* @param {Record<string, string>} [params] - Additional parameters to include in the login request. Each parameters has to be listed in 'allowedClientAuthParameters' in the provider configuration.
* @returns {Promise<void>}
*/ | https://github.com/itpropro/nuxt-oidc-auth/blob/bc044d93f213d9e5e732c9c114181acc9e5fb94a/src/runtime/composables/oidcAuth.ts#L48-L51 | bc044d93f213d9e5e732c9c114181acc9e5fb94a |
nuxt-oidc-auth | github_2023 | itpropro | typescript | logout | async function logout(provider?: ProviderKeys | 'dev', logoutRedirectUri?: string): Promise<void> {
await navigateTo(`/auth${provider ? `/${provider}` : currentProvider.value ? `/${currentProvider.value}` : ''}/logout${logoutRedirectUri ? `?logout_redirect_uri=${logoutRedirectUri}` : ''}`, { external: true, redirectCode: 302 })
if (sessionState.value) {
sessionState.value = undefined as unknown as UserSession
}
} | /**
* Logs out the user by navigating to the appropriate logout URL.
*
* @param {ProviderKeys | 'dev'} [provider] - The provider key or 'dev' for development. If provided, the user will be logged out from the specified provider.
* @param {string} [logoutRedirectUri] - The URI to redirect to after logout if 'logoutRedirectParameterName' is set. If not provided, the user will be redirected to the root site.
* @returns {Promise<void>}
*/ | https://github.com/itpropro/nuxt-oidc-auth/blob/bc044d93f213d9e5e732c9c114181acc9e5fb94a/src/runtime/composables/oidcAuth.ts#L60-L65 | bc044d93f213d9e5e732c9c114181acc9e5fb94a |
nuxt-oidc-auth | github_2023 | itpropro | typescript | clear | async function clear() {
await useRequestFetch()(('/api/_auth/session'), {
method: 'DELETE',
headers: {
Accept: 'text/json',
},
onResponse({ response: { headers } }: { response: { headers: Headers } }) {
// See https://github.com/atinux/nuxt-auth-utils/blob/main/src/runtime/app/composables/session.ts
// Forward the Set-Cookie header to the main server event
if (import.meta.server && serverEvent) {
for (const setCookie of headers.getSetCookie()) {
appendResponseHeader(serverEvent, 'Set-Cookie', setCookie)
}
}
},
})
if (sessionState.value) {
sessionState.value = undefined as unknown as UserSession
}
} | /**
* Clears the current user session. Mainly for debugging, in production, always use the `logout` function, which completely cleans the state.
*/ | https://github.com/itpropro/nuxt-oidc-auth/blob/bc044d93f213d9e5e732c9c114181acc9e5fb94a/src/runtime/composables/oidcAuth.ts#L70-L89 | bc044d93f213d9e5e732c9c114181acc9e5fb94a |
nuxt-oidc-auth | github_2023 | itpropro | typescript | encryptMessage | async function encryptMessage(text: string, key: CryptoKey, iv: Uint8Array) {
const encoded = new TextEncoder().encode(text)
const ciphertext = await subtle.encrypt(
{
name: 'AES-GCM',
iv,
},
key,
encoded,
)
return arrayBufferToBase64(ciphertext, { urlSafe: false })
} | /**
* Encrypts a message with AES-GCM.
* @param text The text to encrypt.
* @param key The key to use for encryption.
* @returns The base64 encoded encrypted message.
*/ | https://github.com/itpropro/nuxt-oidc-auth/blob/bc044d93f213d9e5e732c9c114181acc9e5fb94a/src/runtime/server/utils/security.ts#L59-L70 | bc044d93f213d9e5e732c9c114181acc9e5fb94a |
nuxt-oidc-auth | github_2023 | itpropro | typescript | decryptMessage | async function decryptMessage(text: string, key: CryptoKey, iv: Uint8Array) {
const decoded = base64ToUint8Array(text)
return await subtle.decrypt({ name: 'AES-GCM', iv }, key, decoded)
} | /**
* Decrypts a message with AES-GCM.
* @param text The text to decrypt.
* @param key The key to use for decryption.
* @returns The decrypted message.
*/ | https://github.com/itpropro/nuxt-oidc-auth/blob/bc044d93f213d9e5e732c9c114181acc9e5fb94a/src/runtime/server/utils/security.ts#L78-L81 | bc044d93f213d9e5e732c9c114181acc9e5fb94a |
aspoem | github_2023 | meetqy | typescript | getLocale | function getLocale() {
const headers = { "accept-language": defaultLocale };
const languages = new Negotiator({ headers }).languages();
return match(languages, locales, defaultLocale); // -> 'en-US'
} | // Get the preferred locale, similar to the above or using a library | https://github.com/meetqy/aspoem/blob/5812d0166754b004b344410385961f0568a232d2/src/middleware.ts#L7-L12 | 5812d0166754b004b344410385961f0568a232d2 |
aspoem | github_2023 | meetqy | typescript | createContext | const createContext = async (req: NextRequest) => {
return createTRPCContext({
headers: req.headers,
});
}; | /**
* This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when
* handling a HTTP request (e.g. when you make requests from Client Components).
*/ | https://github.com/meetqy/aspoem/blob/5812d0166754b004b344410385961f0568a232d2/src/app/api/trpc/[trpc]/route.ts#L12-L16 | 5812d0166754b004b344410385961f0568a232d2 |
FluentRead | github_2023 | Bistutu | typescript | clearAllTranslations | function clearAllTranslations() {
// 1. 移除所有翻译结果元素
document.querySelectorAll('.fluent-read-translation').forEach(el => el.remove());
// 2. 移除所有加载状态
document.querySelectorAll('.fluent-read-loading').forEach(el => el.remove());
// 3. 移除所有错误状态
document.querySelectorAll('.fluent-read-failure').forEach(el => el.remove());
// 4. 移除所有翻译相关的类名
document.querySelectorAll('.fluent-read-processed').forEach(el => {
el.classList.remove('fluent-read-processed');
});
// 5. 清除内存中的缓存
cache.clean();
console.log('已清除所有翻译缓存');
} | // 清除所有翻译的函数 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/content.ts#L174-L193 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | shouldSkipNode | function shouldSkipNode(node: any, tag: string): boolean {
// 1. 判断标签是否在 skipSet 内
// 2. 检查是否具有 notranslate 类
// 3. 判断节点是否可编辑
// 4. 判断文本是否过长
return skipSet.has(tag) ||
node.classList?.contains('notranslate') ||
node.isContentEditable ||
isTextTooLong(node);
} | // 检查是否应该跳过节点 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L65-L74 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | isTextTooLong | function isTextTooLong(node: any): boolean {
// 1. 若文本内容长度超过 3072
// 2. 或者 outerHTML 长度超过 4096,都视为过长
return node.textContent.length > 3072 ||
(node.outerHTML && node.outerHTML.length > 4096);
} | // 检查文本长度 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L77-L82 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | isButton | function isButton(node: any, tag: string): boolean {
// 1. 若当前标签就是 button
// 2. 或者当前标签为 span 并且其父节点为 button,则视为按钮
return tag === 'button' ||
(tag === 'span' && node.parentNode?.tagName.toLowerCase() === 'button');
} | // 检查是否为按钮 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L85-L90 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | handleButtonTranslation | function handleButtonTranslation(node: any): void {
// 1. 若文本非空,则调用 handleBtnTranslation 进行按钮文本翻译处理
if (node.textContent.trim()) {
handleBtnTranslation(node);
}
} | // 处理按钮翻译 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L93-L98 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | isInlineElement | function isInlineElement(node: any, tag: string): boolean {
// 1. 判断是否在 inlineSet 中
// 2. 判断是否文本节点
// 3. 检查子元素中是否包含非内联元素
return inlineSet.has(tag) ||
node.nodeType === Node.TEXT_NODE ||
detectChildMeta(node);
} | // 检查是否为内联元素 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L101-L108 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | findTranslatableParent | function findTranslatableParent(node: any): any {
// 1. 递归调用 grabNode 查找父节点是否可翻译
// 2. 若父节点不可翻译,则返回当前节点
const parentResult = grabNode(node.parentNode);
return parentResult || node;
} | // 查找可翻译的父节点 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L111-L116 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | handleFirstLineText | function handleFirstLineText(node: any): boolean {
// 1. 遍历子节点,找到首个文本节点
// 2. 若存在可翻译文本,则通过 browser.runtime.sendMessage 进行翻译
// 3. 翻译成功后,替换该文本;出现错误时,打印错误日志
let child = node.firstChild;
while (child) {
if (child.nodeType === Node.TEXT_NODE && child.textContent.trim()) {
browser.runtime.sendMessage({
context: document.title,
origin: child.textContent
})
.then((text: string) => child.textContent = text)
.catch((error: any) => console.error('翻译失败:', error));
return false;
}
child = child.nextSibling;
}
return false;
} | // 处理首行文本 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L119-L137 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | detectChildMeta | function detectChildMeta(parent: any): boolean {
// 1. 逐个检查子节点
// 2. 若发现非内联元素则返回 false;否则全部检查通过则返回 true
let child = parent.firstChild;
while (child) {
if (child.nodeType === Node.ELEMENT_NODE && !inlineSet.has(child.nodeName.toLowerCase())) {
return false;
}
child = child.nextSibling;
}
return true;
} | // 检测子元素中是否包含指定标签以外的元素 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L140-L151 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | replaceSensitiveWords | function replaceSensitiveWords(text: string): string {
// 1. 使用正则匹配大小写敏感词
// 2. 逐个替换为正确大小写形式
return text.replace(/viewbox|preserveaspectratio|clippathunits|gradienttransform|patterncontentunits|lineargradient|clippath/gi, (match) => {
switch (match.toLowerCase()) {
case 'viewbox':
return 'viewBox';
case 'preserveaspectratio':
return 'preserveAspectRatio';
case 'clippathunits':
return 'clipPathUnits';
case 'gradienttransform':
return 'gradientTransform';
case 'patterncontentunits':
return 'patternContentUnits';
case 'lineargradient':
return 'linearGradient';
case 'clippath':
return 'clipPath';
default:
return match;
}
});
} | // 替换 svg 标签中的一些大小写敏感的词(html 不区分大小写,但 svg 标签区分大小写) | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L183-L206 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | translating | const translating = (failCount = 0) => {
browser.runtime.sendMessage({context: document.title, origin: origin})
.then((text: string) => {
clearTimeout(timeout);
spinner.remove();
htmlSet.delete(nodeOuterHTML);
bilingualAppendChild(node, text);
cache.localSet(origin, text);
})
.catch((error: { toString: () => any; }) => {
clearTimeout(timeout);
if (failCount < 3) {
setTimeout(() => {
translating(failCount + 1);
}, 1000);
} else {
insertFailedTip(node, error.toString() || "", spinner);
}
});
} | // 正在翻译...允许失败重试 3 次 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/trans.ts#L117-L136 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | translating | const translating = (failCount = 0) => {
browser.runtime.sendMessage({context: document.title, origin: origin})
.then((text: string) => {
clearTimeout(timeout);
spinner.remove();
text = beautyHTML(text);
if (!text || origin === text) return;
let oldOuterHtml = node.outerHTML;
node.innerHTML = text;
let newOuterHtml = node.outerHTML;
// 缓存翻译结果
cache.localSetDual(oldOuterHtml, newOuterHtml);
cache.set(htmlSet, newOuterHtml, 250);
htmlSet.delete(oldOuterHtml);
})
.catch((error: { toString: () => any; }) => {
clearTimeout(timeout);
if (failCount < 3) {
setTimeout(() => {
translating(failCount + 1);
}, 1000);
} else {
insertFailedTip(node, error.toString() || "", spinner);
}
});
} | // 正在翻译...允许失败重试 3 次 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/trans.ts#L154-L183 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | parseJwt | function parseJwt(token: string) {
try {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
} catch (e) {
return null;
}
} | // 解析 jwt,返回解析后对象 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/service/microsoft.ts#L40-L51 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | tongyi | async function tongyi(message: any) {
// 构建请求头
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', `Bearer ${config.token[services.tongyi]}`);
// 判断是否使用代理
let url: string = config.proxy[config.service] ? config.proxy[config.service] : urls[services.tongyi]
const resp = await fetch(url, {
method: method.POST,
headers: headers,
body: tongyiMsgTemplate(message.origin)
});
if (resp.ok) {
let result = await resp.json();
if (config.model[config.service] === "qwen-long") return result.output.choices[0].message.content;
else return result.output.text
} else {
console.log(resp)
throw new Error(`翻译失败: ${resp.status} ${resp.statusText} body: ${await resp.text()}`);
}
} | // 文档:https://help.aliyun.com/zh/dashscope/developer-reference/tongyi-thousand-questions-metering-and-billing | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/service/tongyi.ts#L7-L30 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | yiyan | async function yiyan(message: any) {
let model = config.model[services.yiyan]
// model 参数转换
if (model === "ERNIE-Bot 4.0") model = "completions_pro"
else if (model === "ERNIE-Bot") model = "completions"
else if (model === "ERNIE-Speed-8K") model = "ernie_speed"
else if (model === "ERNIE-Speed-128K") model = "ernie-speed-128k"
const secret = await getSecret();
const url = `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/${model}?access_token=${secret}`;
// 发起 fetch 请求
const resp = await fetch(url, {
method: method.POST,
headers: {'Content-Type': 'application/json'},
body: yiyanMsgTemplate(message.origin)
});
if (resp.ok) {
let result = await resp.json();
if (result.error_code) throw new Error(`翻译失败: ${result.error_code} ${result.error_msg}`)
return result.result
} else {
console.log(resp)
throw new Error(`翻译失败: ${resp.status} ${resp.statusText} body: ${await resp.text()}`);
}
} | // ERNIE-Bot 4.0 模型,模型定价页面:https://console.bce.baidu.com/qianfan/chargemanage/list | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/service/yiyan.ts#L10-L37 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | zhipu | async function zhipu(message: any) {
// 智谱根据 token 获取 secret(签名密钥) 和 expiration
let token = config.token[services.zhipu];
let secret, expiration;
config.extra[services.zhipu] && ({secret, expiration} = config.extra[services.zhipu]);
if (!secret || expiration <= Date.now()) {
secret = generateToken(token);
if (!secret) throw new Error('无法生成令牌');
// 保存 secret 和 expiration
config.extra[services.zhipu] = {secret, expiration: Date.now() + 3600000 * 24};
await storage.setItem('local:config', JSON.stringify(config));
}
// 构建请求头
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', `Bearer ${secret}`);
// 发起 fetch 请求
const resp = await fetch(urls[services.zhipu], {
method: method.POST,
headers: headers,
body: commonMsgTemplate(message.origin)
});
if (resp.ok) {
let result = await resp.json();
return result.choices[0].message.content;
} else {
console.log(resp)
throw new Error(`翻译失败: ${resp.status} ${resp.statusText} body: ${await resp.text()}`);
}
} | // 文档参考:https://open.bigmodel.cn/dev/api#nosdk | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/service/zhipu.ts#L9-L41 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | generateJWT | function generateJWT(secret: string, header: any, payload: any) {
// 对header和payload部分进行UTF-8编码,然后转换为Base64URL格式
const encodedHeader = base64UrlSafe(btoa(JSON.stringify(header)));
const encodedPayload = base64UrlSafe(btoa(JSON.stringify(payload)));
// 生成 jwt 签名
let hmacsha256 = base64UrlSafe(CryptoJS.HmacSHA256(encodedHeader + "." + encodedPayload, secret).toString(CryptoJS.enc.Base64))
return `${encodedHeader}.${encodedPayload}.${hmacsha256}`;
} | // 生成JWT(JSON Web Token) | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/service/zhipu.ts#L59-L66 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | base64UrlSafe | function base64UrlSafe(base64String: string) {
return base64String.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
} | // 将Base64字符串转换为Base64URL格式的函数 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/service/zhipu.ts#L69-L71 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | buildKey | function buildKey(message: string) {
const { service, model, to, style, customModel } = config;
const selectedModel = model[service] === customModelString ? customModel[service] : model[service];
// 前缀_服务_模型_目标语言_消息
return [prefix, style, service, selectedModel, to, message].join('_');
} | // fluent read cache | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/cache.ts#L8-L13 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | loadConfig | async function loadConfig() {
try {
// 获取存储中的配置
const value = await storage.getItem('local:config');
if (isValidConfig(value)) {
// 如果配置有效,合并到当前 config 中
Object.assign(config, JSON.parse(value));
}
} catch (error) {
console.error('Error getting config:', error);
}
} | // 异步加载配置并应用 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/config.ts#L7-L18 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | isValidConfig | function isValidConfig(value: any): value is string {
return typeof value === 'string' && value.trim().length > 0;
} | // 检查配置是否有效 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/config.ts#L21-L23 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | handleRetryClick | function handleRetryClick(node: HTMLElement, wrapper: HTMLElement) {
return (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
wrapper.remove(); // 移除错误提示元素,重新翻译
node.classList.remove("fluent-read-failure"); // 移除失败标记
// 根据当前配置的翻译模式决定使用哪种翻译方式
if (config.display === styles.bilingualTranslation) {
handleBilingualTranslation(node, false);
} else {
handleSingleTranslation(node, false);
}
};
} | // 处理重试按钮点击事件 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/icon.ts#L58-L73 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | handleErrorClick | function handleErrorClick(errMsg: string) {
return (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
const message = getErrorMessage(errMsg);
sendErrorMessage(message); // 发送错误提示
};
} | // 处理错误提示按钮点击事件 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/icon.ts#L76-L84 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | getErrorMessage | function getErrorMessage(errMsg: string): string {
if (errMsg.includes("auth failed") || errMsg.includes("API key")) {
return "Token 似乎有点问题,请前往设置页面重新配置后再试。";
} else if (errMsg.includes("quota") || errMsg.includes("limit")) {
const service = options.services.find((s: { value: string; label: string }) => s.value === config.service);
return "你的请求频率过高,被【" + (service?.label || config.service) + "】拒绝了,请稍后再试吧~";
} else if (errMsg.includes("network error")) {
return "网络连接好像不稳定,请检查网络后再试。";
} else if (errMsg.includes("model")) {
return "模型配置可能有误,请前往设置页面进行检查和调整。";
} else if (errMsg.includes("timeout")) {
return "请求超时啦,请稍后再试一次。";
} else {
return errMsg || "出现了未知错误,请前往开源社区联系开发者吧~";
}
} | // 根据错误信息返回错误提示 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/icon.ts#L87-L102 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | createIconElement | function createIconElement(iconContent: string): HTMLElement {
const iconElement = document.createElement("div");
iconElement.innerHTML = iconContent;
return iconElement;
} | // 创建图标元素 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/icon.ts#L105-L109 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | Config.constructor | constructor() {
this.on = true;
this.from = defaultOption.from;
this.to = defaultOption.to;
this.style = defaultOption.style;
this.display = defaultOption.display;
this.hotkey = defaultOption.hotkey;
this.service = defaultOption.service;
this.token = {};
this.ak = '';
this.sk = '';
this.appid = '';
this.key = '';
this.model = {};
this.customModel = {};
this.proxy = {};
this.custom = defaultOption.custom;
this.extra = {};
this.robot_id = {};
this.system_role = systemRoleFactory();
this.user_role = userRoleFactory();
this.count = 0;
this.theme = 'auto'; // 默认跟随系统
} | // 主题模式:'auto' | 'light' | 'dark' | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/model.ts#L36-L59 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | systemRoleFactory | function systemRoleFactory(): IMapping {
let systems_role: IMapping = {};
Object.keys(services).forEach(key => systems_role[key] = defaultOption.system_role);
return systems_role;
} | // 构建所有服务的 system_role | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/model.ts#L63-L67 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | userRoleFactory | function userRoleFactory(): IMapping {
let users_role: IMapping = {};
Object.keys(services).forEach(key => users_role[key] = defaultOption.user_role);
return users_role;
} | // 构建所有服务的 user_role | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/model.ts#L70-L74 | 9b513e9fd44e62926de681b0ef366baa0615836a |
counterscale | github_2023 | benvinegar | typescript | getMidnightDate | function getMidnightDate(): Date {
const midnight = new Date();
midnight.setHours(0, 0, 0, 0);
return midnight;
} | // Cookieless visitor/session tracking | https://github.com/benvinegar/counterscale/blob/d0b8e1960fb170b286f35bd6bfa3e6f9d95c8b4e/packages/server/app/analytics/collect.ts#L11-L15 | d0b8e1960fb170b286f35bd6bfa3e6f9d95c8b4e |
counterscale | github_2023 | benvinegar | typescript | accumulateCountsFromRowResult | function accumulateCountsFromRowResult(
counts: AnalyticsCountResult,
row: {
count: number;
isVisitor: number;
isBounce: number;
},
) {
if (row.isVisitor == 1) {
counts.visitors += Number(row.count);
}
if (row.isBounce && row.isBounce != 0) {
// bounce is either 1 or -1
counts.bounces += Number(row.count) * row.isBounce;
}
counts.views += Number(row.count);
} | /** Given an AnalyticsCountResult object, and an object representing a row returned from
* CF Analytics Engine w/ counts grouped by isVisitor, accumulate view,
* visit, and visitor counts.
*/ | https://github.com/benvinegar/counterscale/blob/d0b8e1960fb170b286f35bd6bfa3e6f9d95c8b4e/packages/server/app/analytics/query.ts#L30-L46 | d0b8e1960fb170b286f35bd6bfa3e6f9d95c8b4e |
counterscale | github_2023 | benvinegar | typescript | generateEmptyRowsOverInterval | function generateEmptyRowsOverInterval(
intervalType: "DAY" | "HOUR",
startDateTime: Date,
endDateTime: Date,
tz?: string,
): { [key: string]: AnalyticsCountResult } {
if (!tz) {
tz = "Etc/UTC";
}
const initialRows: { [key: string]: AnalyticsCountResult } = {};
while (startDateTime.getTime() < endDateTime.getTime()) {
const key = dayjs(startDateTime).utc().format("YYYY-MM-DD HH:mm:ss");
initialRows[key] = {
views: 0,
visitors: 0,
bounces: 0,
};
if (intervalType === "DAY") {
// WARNING: Daylight savings hack. Cloudflare Workers uses a different Date
// implementation than Node 20.x, which doesn't seem to respect DST
// boundaries the same way(see: https://github.com/benvinegar/counterscale/issues/108).
//
// To work around this, we add 25 hours to the start date/time, then get the
// start of the day, then convert it back to a Date object. This works in both
// Node 20.x and Cloudflare Workers environments.
startDateTime = dayjs(startDateTime)
.add(25, "hours")
.tz(tz)
.startOf("day")
.toDate();
} else if (intervalType === "HOUR") {
startDateTime = dayjs(startDateTime).add(1, "hour").toDate();
} else {
throw new Error("Invalid interval type");
}
}
return initialRows;
} | /**
* returns an object with keys of the form "YYYY-MM-DD HH:00:00" and values of 0
* example:
* {
* "2021-01-01 00:00:00": 0,
* "2021-01-01 02:00:00": 0,
* "2021-01-01 04:00:00": 0,
* ...
* }
*
* */ | https://github.com/benvinegar/counterscale/blob/d0b8e1960fb170b286f35bd6bfa3e6f9d95c8b4e/packages/server/app/analytics/query.ts#L86-L127 | d0b8e1960fb170b286f35bd6bfa3e6f9d95c8b4e |
pinia-colada | github_2023 | posva | typescript | delay | function delay(str: string) {
return new Promise((resolve) =>
setTimeout(() => {
resolve(str)
}, 200),
)
} | // delay to imitate fetch | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/playground/src/queries/issue-174.ts#L15-L21 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | shouldScheduleRefetch | function shouldScheduleRefetch(options: UseQueryOptions) {
const queryEnabled = toValue(options.autoRefetch) ?? autoRefetch
const staleTime = options.staleTime
return Boolean(queryEnabled && staleTime)
} | /**
* Whether to schedule a refetch for the given entry
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/plugins/auto-refetch/src/index.ts#L65-L69 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | applyTextStyles | function applyTextStyles(text: string) {
const styles: Array<{ pos: number, style: [string, string] }> = []
const newText = text
.replace(MD_BOLD_RE, (_m, text, pos) => {
styles.push({
pos,
style: ['font-weight: bold;', 'font-weight: normal;'],
})
return `%c${text}%c`
})
// .replace(MD_ITALIC_RE, (_m, text, pos) => {
// styles.push({
// pos,
// style: ['font-style: italic;', 'font-style: normal;'],
// })
// return `%c${text}%c`
// })
.replace(MD_CODE_RE, (_m, text, pos) => {
styles.push({
pos,
style: ['font-family: monospace;', 'font-family: inherit;'],
})
return `%c\`${text}\`%c`
})
return [
newText,
...styles.sort((a, b) => a.pos - b.pos).flatMap((s) => s.style),
]
} | /**
* Applies italic and bold style to markdown text.
* @param text - The text to apply styles to
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/plugins/debug/src/index.ts#L124-L153 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | track | function track(
entry: UseQueryEntry,
effect: EffectScope | ComponentInternalInstance | null | undefined,
) {
if (!effect) return
entry.deps.add(effect)
// clearTimeout ignores anything that isn't a timerId
clearTimeout(entry.gcTimeout)
entry.gcTimeout = undefined
triggerCache()
} | /**
* Tracks an effect or component that uses a query.
*
* @param entry - the entry of the query
* @param effect - the effect or component to untrack
*
* @see {@link untrack}
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/query-store.ts#L380-L390 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | untrack | function untrack(
entry: UseQueryEntry,
effect: EffectScope | ComponentInternalInstance | undefined | null,
) {
// avoid clearing an existing timeout
if (!effect || !entry.deps.has(effect)) return
entry.deps.delete(effect)
triggerCache()
if (entry.deps.size > 0 || !entry.options) return
clearTimeout(entry.gcTimeout)
// avoid setting a timeout with false, Infinity or NaN
if ((Number.isFinite as (val: unknown) => val is number)(entry.options.gcTime)) {
entry.gcTimeout = setTimeout(() => {
remove(entry)
}, entry.options.gcTime)
}
} | /**
* Untracks an effect or component that uses a query.
*
* @param entry - the entry of the query
* @param effect - the effect or component to untrack
*
* @see {@link track}
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/query-store.ts#L400-L418 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | getQueryData | function getQueryData<TResult = unknown>(key: EntryKey): TResult | undefined {
return caches.value.get(toCacheKey(key))?.state.value.data as TResult | undefined
} | /**
* Gets the data of a query entry in the cache based on the key of the query.
*
* @param key - the key of the query
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/query-store.ts#L765-L767 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | _serialize | function _serialize([key, tree]: [
key: EntryNodeKey,
tree: TreeMapNode<UseQueryEntry>,
]): UseQueryEntryNodeSerialized {
return [
key,
tree.value && queryEntry_toJSON(tree.value),
tree.children && [...tree.children.entries()].map(_serialize),
]
} | /**
* Internal function to recursively transform the tree into a compressed array.
* @internal
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/query-store.ts#L833-L842 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | appendToTree | function appendToTree(
parent: TreeMapNode<UseQueryEntry>,
[key, value, children]: UseQueryEntryNodeSerialized,
parentKey: EntryNodeKey[] = [],
) {
parent.children ??= new Map()
const node = new TreeMapNode<UseQueryEntry>(
[],
// NOTE: this could happen outside of an effect scope but since it's only for client side hydration, it should be
// fine to have global shallowRefs as they can still be cleared when needed
value && createQueryEntry([...parentKey, key], ...value),
)
parent.children.set(key, node)
if (children) {
for (const child of children) {
appendToTree(node, child)
}
}
} | /**
* @deprecated only used by {@link reviveTreeMap}
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/query-store.ts#L869-L887 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | TreeMapNode.set | set(keys: EntryNodeKey[], value?: T) {
if (keys.length === 0) {
this.value = value
} else {
// this.children ??= new Map<EntryNodeKey,
const [top, ...otherKeys] = keys
const node: TreeMapNode<T> | undefined = this.children?.get(top)
if (node) {
node.set(otherKeys, value)
} else {
this.children ??= new Map()
this.children.set(top, new TreeMapNode(otherKeys, value))
}
}
} | /**
* Sets the value while building the tree
*
* @param keys - key as an array
* @param value - value to set
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/tree-map.ts#L30-L44 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | TreeMapNode.find | find(keys: EntryNodeKey[]): TreeMapNode<T> | undefined {
if (keys.length === 0) {
return this
} else {
const [top, ...otherKeys] = keys
return this.children?.get(top)?.find(otherKeys)
}
} | /**
* Finds the node at the given path of keys.
*
* @param keys - path of keys
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/tree-map.ts#L51-L58 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | TreeMapNode.get | get(keys: EntryNodeKey[]): T | undefined {
return this.find(keys)?.value
} | /**
* Gets the value at the given path of keys.
*
* @param keys - path of keys
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/tree-map.ts#L65-L67 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | TreeMapNode.delete | delete(keys: EntryNodeKey[]) {
if (keys.length === 1) {
this.children?.delete(keys[0])
} else {
const [top, ...otherKeys] = keys
this.children?.get(top)?.delete(otherKeys)
}
} | /**
* Delete the node at the given path of keys and all its children.
*
* @param keys - path of keys
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/tree-map.ts#L74-L81 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | errorCatcher | const errorCatcher = () => entry.value.state.value | // adapter that returns the entry state | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/use-query.ts#L165-L165 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
LeagueAkari | github_2023 | Hanxven | typescript | AutoGameflowMain._adjustDodgeTimer | private _adjustDodgeTimer(msLeft: number, threshold: number) {
const dodgeIn = Math.max(msLeft - threshold * 1e3, 0)
this._log.info(`时间校正:将在 ${dodgeIn} ms 后秒退`)
this._dodgeTask.start(dodgeIn)
this.state.setDodgeAt(Date.now() + dodgeIn)
} | /**
* @deprecated 已无法使用
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/auto-gameflow/index.ts#L306-L311 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | AutoSelectMain._calculateAppropriateDelayMs | private _calculateAppropriateDelayMs(delayMs: number, margin: number = 1200) {
const info = this.state.currentPhaseTimerInfo
if (!info || info.isInfinite) {
return delayMs
}
const maxAllowedDelayMs = info.totalTimeInPhase - margin
const desiredDelayMs = Math.min(delayMs, maxAllowedDelayMs)
const adjustedDelayMs = desiredDelayMs - info.adjustedTimeElapsedInPhase
return Math.max(0, adjustedDelayMs)
} | /**
* 确保用户设置时间的合理性
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/auto-select/index.ts#L180-L191 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | ClientInstallationMain._updateTencentPathsByReg | private async _updateTencentPathsByReg() {
try {
const list: string[] = []
if (!this.state.tencentInstallationPath) {
list.push(ClientInstallationMain.TENCENT_REG_INSTALL_PATH)
}
if (!this.state.weGameExecutablePath) {
list.push(ClientInstallationMain.WEGAME_DEFAULTICON_PATH)
}
const result = await regedit.promisified.list(list)
const item1 = result[ClientInstallationMain.TENCENT_REG_INSTALL_PATH]
const item2 = result[ClientInstallationMain.WEGAME_DEFAULTICON_PATH]
if (item1 && item1.exists) {
const p = item1.values[ClientInstallationMain.TENCENT_REG_INSTALL_VALUE]
if (!p) {
return
}
try {
await fs.promises.access(p.value as string)
} catch {
this._log.info('注册表检测到腾讯服英雄联盟安装位置但无法访问, 可能并不存在', p.value)
return
}
this._log.info('注册表检测到腾讯服英雄联盟安装位置', p.value)
this.state.setTencentInstallationPath(p.value as string)
try {
const tclsPath = path.resolve(p.value as string, 'Launcher', 'Client.exe')
await fs.promises.access(tclsPath)
this.state.setHasTcls(true)
} catch {
this._log.info('TCLS 无法访问, 可能并不存在', p.value)
return
}
try {
const weGamePath = path.resolve(p.value as string, 'WeGameLauncher', 'launcher.exe')
await fs.promises.access(weGamePath)
this.state.setHasWeGameLauncher(true)
} catch {
this._log.info('WeGame 启动器无法访问, 可能并不存在', p.value)
return
}
}
if (item2 && item2.exists) {
const p = item2.values[''].value as string
const match = p.match(/"([^"]+)"/)
if (match) {
try {
await fs.promises.access(match[1])
} catch {
this._log.info('检测到 WeGame 但无法访问, 可能并不存在', match[1])
return
}
this._log.info('注册表检测到 WeGame 安装位置', match[1])
this.state.setWeGameExecutablePath(match[1])
}
}
} catch (error) {
this._log.warn(`使用注册表信息读取安装目录时发生错误`, error)
}
} | /**
* 通过注册表来找寻位置
* @returns
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/client-installation/index.ts#L68-L140 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | ClientInstallationMain._updateTencentPathsByFile | private async _updateTencentPathsByFile() {
if (this.state.tencentInstallationPath) {
return
}
const drives = await this._getDrives()
this._log.info('当前的逻辑磁盘', drives)
for (const drive of drives) {
const installation = path.join(
drive,
ClientInstallationMain.TENCENT_INSTALL_DIRNAME,
ClientInstallationMain.TENCENT_LOL_DIRNAME
)
try {
await fs.promises.access(installation)
this._log.info('通过文件检测到腾讯服英雄联盟安装位置', installation)
this.state.setTencentInstallationPath(installation)
const tcls = path.resolve(installation, 'Launcher', 'Client.exe')
const weGameLauncher = path.resolve(installation, 'WeGameLauncher', 'launcher.exe')
try {
await fs.promises.access(tcls)
this.state.setHasTcls(true)
this._log.info('通过文件检测到腾讯服 TCLS 安装位置', tcls)
} catch {}
try {
await fs.promises.access(weGameLauncher)
this.state.setHasWeGameLauncher(true)
this._log.info('通过文件检测到腾讯服 WeGameLauncher 安装位置', weGameLauncher)
} catch {}
// 如果都找到了,则直接退出
if (this.state.hasTcls && this.state.hasWeGameLauncher) {
return
}
} catch (error) {
continue
}
}
} | /**
* 通过扫盘来更新腾讯服安装位置
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/client-installation/index.ts#L158-L204 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | ConfigMigrateMain._migrateFrom126 | private async _migrateFrom126(manager: EntityManager) {
const hasMigratedSymbol = await manager.findOneBy(Setting, {
key: Equal(ConfigMigrateMain.MIGRATION_FROM_126)
})
if (hasMigratedSymbol) {
return
}
this._log.info('开始迁移设置项', ConfigMigrateMain.MIGRATION_FROM_126)
await this._do(manager, 'auxiliary-window/opacity', 'window-manager-main/auxWindowOpacity')
await this._do(manager, 'auxiliary-window/enabled', 'window-manager-main/auxWindowEnabled')
await this._do(manager, 'respawn-timer/enabled', 'respawn-timer-main/enabled')
await this._do(manager, 'auto-reply/text', 'auto-reply-main/text')
await this._do(manager, 'auto-reply/enabled', 'auto-reply-main/enabled')
await this._do(manager, 'auto-reply/enableOnAway', 'auto-reply-main/enableOnAway')
await this._do(
manager,
'auxiliary-window/functionality',
'window-manager-main/auxWindowFunctionality'
)
await this._do(manager, 'auto-gameflow/autoHonorEnabled', 'auto-gameflow-main/autoHonorEnabled')
await this._do(manager, 'auto-gameflow/playAgainEnabled', 'auto-gameflow-main/playAgainEnabled')
await this._do(
manager,
'auto-gameflow/autoAcceptEnabled',
'auto-gameflow-main/autoAcceptEnabled'
)
await this._do(
manager,
'auto-gameflow/autoAcceptDelaySeconds',
'auto-gameflow-main/autoAcceptDelaySeconds'
)
await this._do(
manager,
'auto-gameflomanager, w/autoMatchmakingEnabled',
'auto-gameflomanager, w-main/autoMatchmakingEnabled'
),
await this._do(
manager,
'auto-gameflomanager, w/autoMatchmakingDelaySeconds',
'auto-gameflomanager, w-main/autoMatchmakingDelaySeconds'
),
await this._do(
manager,
'auto-gameflomanager, w/autoMatchmakingMinimumMembers',
'auto-gameflomanager, w-main/autoMatchmakingMinimumMembers'
),
await this._do(
manager,
'auto-gameflomanager, w/autoMatchmakingWaitForInvitees',
'auto-gameflomanager, w-main/autoMatchmakingWaitForInvitees'
),
await this._do(
manager,
'auto-gameflomanager, w/autoMatchmakingRematchStrategy',
'auto-gameflomanager, w-main/autoMatchmakingRematchStrategy'
),
await this._do(
manager,
'auto-gameflomanager, w/autoMatchmakingRematchFixedDuration',
'auto-gameflomanager, w-main/autoMatchmakingRematchFixedDuration'
),
await this._do(
manager,
'app/showFreeSoftwareDeclaration',
'app-common-main/showFreeSoftwareDeclaration'
)
await this._do(manager, 'app/useWmic', 'league-client-ux-main/useWmic')
await this._do(manager, 'app/isInKyokoMode', 'app-common-main/isInKyokoMode')
await this._do(manager, 'auto-update/autoCheckUpdates', 'self-update-main/autoCheckUpdates')
await this._do(manager, 'auto-update/downloadSource', 'self-update-main/downloadSource')
await this._do(manager, 'auxiliary-window/isPinned', 'window-manager-main/auxWindowPinned')
await this._do(
manager,
'auxiliary-window/showSkinSelector',
'window-manager-main/auxWindowShowSkinSelector'
)
await this._do(manager, 'lcu-connection/autoConnect', 'league-client-main/autoConnect')
await this._do(manager, 'auto-select/normalModeEnabled', 'auto-select-main/normalModeEnabled')
await this._do(manager, 'auto-select/expectedChampions', 'auto-select-main/expectedChampions')
await this._do(
manager,
'auto-select/manager, selectTeammateIntendedChampion',
'auto-select-manager, main/selectTeammateIntendedChampion'
),
await this._do(manager, 'auto-select/showIntent', 'auto-select-main/showIntent')
await this._do(manager, 'auto-select/benchModeEnabled', 'auto-select-main/benchModeEnabled')
await this._do(
manager,
'auto-select/benchExpectedChampions',
'auto-select-main/benchExpectedChampions'
)
await this._do(manager, 'auto-select/grabDelaySeconds', 'auto-select-main/grabDelaySeconds')
await this._do(manager, 'auto-select/banEnabled', 'auto-select-main/banEnabled')
await this._do(manager, 'auto-select/bannedChampions', 'auto-select-main/bannedChampions')
await this._do(
manager,
'auto-select/banTeammateIntendedChampion',
'auto-select-main/banTeammateIntendedChampion'
)
await this._do(
manager,
'core-functionality/fetchAfterGame',
'match-history-tabs-renderer/refreshTabsAfterGameEnds'
)
await this._do(
manager,
'core-functionality/playerAnalysisFetchConcurrency',
'ongoing-game-main/concurrency'
)
await this._do(
manager,
'core-functionality/ongoingAnalysisEnabled',
'ongoing-game-main/enabled'
)
await this._do(
manager,
'core-functionality/matchHistoryLoadCount',
'ongoing-game-main/matchHistoryLoadCount'
)
await this._do(
manager,
'core-functionality/preMadeTeamThreshold',
'ongoing-game-main/premadeTeamThreshold'
)
await this._do(
manager,
'auto-update/lastReadAnnouncementSha',
'self-update-main/lastReadAnnouncementSha'
)
await this._do(
manager,
'auto-select/benchSelectFirstAvailableChampion',
'auto-select-main/benchSelectFirstAvailableChampion'
)
await this._do(
manager,
'core-functionality/useSgpApi',
'ongoing-game-main/matchHistoryUseSgpApi'
)
await this._do(
manager,
'auto-gameflow/autoAcceptInvitationEnabled',
'auto-gameflow-main/autoHandleInvitationsEnabled'
)
await this._do(
manager,
'auto-gameflow/invitationHandlingStrategies',
'auto-gameflow-main/invitationHandlingStrategies'
)
await this._do(
manager,
'auto-gameflow/autoReconnectEnabled',
'auto-gameflow-main/autoReconnectEnabled'
)
await manager.save(
Setting.create(ConfigMigrateMain.MIGRATION_FROM_126, ConfigMigrateMain.MIGRATION_FROM_126)
)
this._log.info(`迁移完成, 到 ${ConfigMigrateMain.MIGRATION_FROM_126}`)
} | // NOTE: drop support before League Akari 1.1.x | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/config-migrate/index.ts#L44-L207 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | GameClientMain._completeSpectatorCredential | private async _completeSpectatorCredential(config: LaunchSpectatorConfig) {
const {
sgpServerId,
gameId,
gameMode,
locale = 'zh_CN',
observerEncryptionKey,
observerServerIp,
observerServerPort
} = config
if (this._lc.state.connectionState === 'connected') {
try {
const { data: location } = await this._lc.http.get<{
gameExecutablePath: string
gameInstallRoot: string
}>('/lol-patch/v1/products/league_of_legends/install-location')
return {
sgpServerId,
gameId,
gameMode,
locale,
observerEncryptionKey,
observerServerIp,
observerServerPort,
gameInstallRoot: location.gameInstallRoot,
gameExecutablePath: location.gameExecutablePath
}
} catch (error) {
const err = new Error('Cannot get game installation path')
err.name = 'CannotGetGameInstallationPath'
throw err
}
} else {
if (this._ci.state.tencentInstallationPath) {
const gameExecutablePath = path.resolve(
this._ci.state.tencentInstallationPath,
'Game',
GameClientMain.GAME_CLIENT_PROCESS_NAME
)
const gameInstallRoot = path.resolve(this._ci.state.tencentInstallationPath, 'Game')
return {
sgpServerId,
gameId,
gameMode,
locale,
observerEncryptionKey,
observerServerIp,
observerServerPort,
gameInstallRoot,
gameExecutablePath
}
} else if (this._ci.state.leagueClientExecutablePaths.length) {
const gameExecutablePath = path.resolve(
this._ci.state.leagueClientExecutablePaths[0],
'..',
'Game',
GameClientMain.GAME_CLIENT_PROCESS_NAME
)
try {
await ofs.promises.access(gameExecutablePath)
const gameInstallRoot = path.resolve(gameExecutablePath, '..')
return {
sgpServerId,
gameId,
gameMode,
locale,
observerEncryptionKey,
observerServerIp,
observerServerPort,
gameInstallRoot,
gameExecutablePath
}
} catch {
const err = new Error('Cannot get game installation path')
err.name = 'CannotGetGameInstallationPath'
throw err
}
} else {
const err = new Error('Cannot get game installation path')
err.name = 'CannotGetGameInstallationPath'
throw err
}
}
} | /**
* 连接情况下, 通过 LCU API 获取安装位置
* 未连接的情况下, 默认使用腾讯服务端的安装位置
* @param config
* @returns
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/game-client/index.ts#L190-L279 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | InGameSendMain._sendSeparatedStringLines | private async _sendSeparatedStringLines(
messages: string[],
type: 'champ-select-chat' | 'keyboard' = 'keyboard', // 选人界面发送 or 键盘模拟游戏中发送
identifier: string | null = null
) {
const tasks: (() => Promise<void>)[] = []
const interval = this.settings.sendInterval
if (type === 'champ-select-chat') {
const csRoomId = this._lc.data.chat.conversations.championSelect?.id
if (csRoomId) {
for (let i = 0; i < messages.length; i++) {
tasks.push(async () => {
await this._lc.api.chat.chatSend(csRoomId, messages[i])
})
if (i !== messages.length - 1) {
tasks.push(() => sleep(interval))
}
}
}
} else {
for (let i = 0; i < messages.length; i++) {
tasks.push(async () => {
await input.sendKeyAsync(InGameSendMain.ENTER_KEY_CODE, true)
await sleep(InGameSendMain.ENTER_KEY_INTERNAL_DELAY)
await input.sendKeyAsync(InGameSendMain.ENTER_KEY_CODE, false)
await sleep(interval)
await input.sendKeysAsync(messages[i])
await sleep(interval)
await input.sendKeyAsync(InGameSendMain.ENTER_KEY_CODE, true)
await sleep(InGameSendMain.ENTER_KEY_INTERNAL_DELAY)
await input.sendKeyAsync(InGameSendMain.ENTER_KEY_CODE, false)
})
if (i !== messages.length - 1) {
tasks.push(() => sleep(interval))
}
}
}
let isCancelled = false
let isEnd = false
this._currentSendingInfo = {
id: identifier,
isEnd: () => isEnd,
isCancelled: () => isCancelled,
cancel: () => {
isCancelled = true
}
}
for (const task of tasks) {
if (isCancelled) {
break
}
await task()
}
isEnd = true
} | /**
* 模拟游戏中的发送流程
* @param messages
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/in-game-send/index.ts#L139-L201 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | InGameSendMain._deleteCustomSend | private async _deleteCustomSend(id: string) {
const targetId = `${InGameSendMain.id}/custom-send/${id}`
if (this._kbd.unregisterByTargetId(targetId)) {
this._log.info(`已删除快捷键 ${targetId}`)
}
this._setting.set(
'customSend',
this.settings.customSend.filter((item) => item.id !== id)
)
return id
} | /**
* 删除快捷键并更新状态
* @param id
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/in-game-send/index.ts#L452-L465 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | InGameSendMain._dryRunStatsSend | private async _dryRunStatsSend(target = 'all') {
if (this._og.state.queryStage.phase === 'unavailable') {
this._log.warn('Dry-Run: 当前不在可发送阶段,无数据')
return { error: true, reason: 'stage-unavailable', data: [] }
}
const usingFn = this.settings.sendStatsUseDefaultTemplate
? this._defaultCompliedFn
: this._customCompiledFn
if (!usingFn) {
this._log.warn('Dry-Run: 目标模板未编译, 无法发送')
return { error: true, reason: 'not-compiled', data: [] }
}
try {
const messages = usingFn
.call(
this._eta,
this._createTemplateEnv({
akariVersion: this._shared.global.version,
target: target as 'ally' | 'enemy' | 'all'
})
)
.split('\n')
.filter((m) => m.trim().length > 0)
return { error: false, reason: null, data: messages }
} catch (error) {
this._log.warn('Dry-Run: 执行模板发生错误', error)
return { error: true, reason: 'execution-error', data: [], extra: (error as Error).message }
}
} | /**
* 仅用于测试发送内容, 返回字符串
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/in-game-send/index.ts#L756-L788 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | AkariIpcMain._handleRendererRegister | private _handleRendererRegister(event: IpcMainInvokeEvent, action = 'register') {
const id = event.sender.id
if (action === 'register' && !this._renderers.has(id)) {
this._renderers.add(id)
event.sender.on('destroyed', () => this._renderers.delete(id))
return { success: true }
} else if (action === 'unregister' && this._renderers.has(id)) {
this._renderers.delete(id)
return { success: true }
}
return { success: false, error: { message: `invalid action "${action}"` } }
} | /**
* 处理来自渲染进程的事件订阅
* @param event
* @param action 可选值 register / unregister
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ipc/index.ts#L56-L69 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | AkariIpcMain.sendEvent | sendEvent(namespace: string, eventName: string, ...args: any[]) {
this._renderers.forEach((id) =>
webContents.fromId(id)?.send('akari-event', namespace, eventName, ...args)
)
} | /**
* 发送到所有已注册的渲染进程, 事件名使用 kebab-case
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ipc/index.ts#L100-L104 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | AkariIpcMain.onCall | onCall(
namespace: string,
fnName: string,
cb: (event: IpcMainInvokeEvent, ...args: any[]) => Promise<any> | any
) {
const key = `${namespace}:${fnName}`
if (this._callMap.has(key)) {
throw new Error(`Function "${fnName}" in namespace "${namespace}" already exists`)
}
this._callMap.set(key, cb)
} | /**
* 处理来自渲染进程的调用, 方法名使用 camelCase
* @param cb
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ipc/index.ts#L122-L133 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | AkariIpcMain._handleError | private static _handleError(error: any): IpcMainDataType {
if (isAxiosError(error)) {
const errorWithResponse = {
response: error.response
? {
status: error.response.status,
statusText: error.response.statusText,
data: error.response.data
}
: null,
code: error.code,
message: error.message,
stack: error.stack,
name: error.name
}
return {
success: false,
isAxiosError: true,
error: errorWithResponse
}
} else if (error instanceof Error) {
return {
success: false,
error: {
message: error.message,
stack: error.stack,
name: error.name
}
}
}
return {
success: false,
error: { message: 'An error occurred' }
}
} | /**
* 处理一般错误和 axios 错误, 包含特例, 对业务错误网开一面
* @param error
* @returns
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ipc/index.ts#L140-L176 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | AkariIpcMain.getRegisteredRendererIds | getRegisteredRendererIds() {
return Array.from(this._renderers)
} | /**
* 获取已注册的渲染进程 ID 列表
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ipc/index.ts#L181-L183 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | KeyboardShortcutsMain._correctTrackingState | private async _correctTrackingState() {
const states = await input.getAllKeyStatesAsync()
this._pressedModifierKeys.clear()
this._pressedOtherKeys.clear()
states.forEach((key) => {
const { vkCode, pressed } = key
// 你知道吗? 当微信启动的时候, 会伸出一个无形的大手将 F22 (VK_CODE 133) 按下, 然后永远不松开
// 使用此逻辑以释放 F22
if (vkCode === KeyboardShortcutsMain.VK_CODE_F22 && pressed) {
this._log.info('F22 被按下, 试图释放')
input.sendKeyAsync(KeyboardShortcutsMain.VK_CODE_F22, false).catch(() => {})
return
}
if (isCommonModifierKey(vkCode)) {
return
}
if (isModifierKey(vkCode)) {
if (pressed) {
this._pressedModifierKeys.add(vkCode)
}
} else {
if (pressed) {
this._pressedOtherKeys.add(vkCode)
}
}
})
} | /**
* 修正当前的按键状态, 最大程度上保证状态的一致性
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/keyboard-shortcuts/index.ts#L278-L309 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | KeyboardShortcutsMain.register | register(
targetId: string,
shortcutId: string,
type: 'last-active' | 'normal',
cb: (details: ShortcutDetails) => void
) {
if (!this._app.state.isAdministrator) {
this._log.info(`当前位于普通权限, 忽略快捷键注册: ${shortcutId} (${type})`)
return
}
const originShortcut = this._targetIdMap.get(targetId)
if (originShortcut) {
const options = this._registrationMap.get(originShortcut)
if (options) {
if (options.targetId === targetId) {
this._registrationMap.delete(originShortcut)
} else {
throw new Error(`Shortcut with targetId ${targetId} already exists`)
}
}
}
this._registrationMap.set(shortcutId, { type, targetId, cb })
this._targetIdMap.set(targetId, shortcutId)
this._log.info(`注册快捷键 ${shortcutId} (${type})`)
} | /**
* 注册一个精准快捷键
* 同 targetId 的快捷键允许被覆盖, 否则会抛出异常
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/keyboard-shortcuts/index.ts#L315-L342 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | LeagueClientUxMain.update | async update() {
try {
this.state.setLaunchedClients(await this._queryUxCommandLine())
if (this._pollTimerId) {
clearInterval(this._pollTimerId)
}
this._pollTimerId = setInterval(
() => this.update(),
LeagueClientUxMain.CLIENT_CMD_DEFAULT_POLL_INTERVAL
)
} catch (error) {
this._ipc.sendEvent(LeagueClientUxMain.id, 'error-polling')
this._log.error(`获取 Ux 命令行信息时失败`, error)
}
} | /**
* 立即更新状态
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/league-client-ux/index.ts#L99-L114 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | LeagueClientMain._disconnect | private _disconnect() {
if (this._ws) {
this._ws.close()
}
this._ws = null
this._http = null
this._api = null
this.state.setDisconnected()
} | /**
* 断开与 LeagueClient 的连接, 主要是 WebSocket
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/league-client/index.ts#L256-L266 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | LeagueClientMain.fixWindowMethodA | async fixWindowMethodA(config?: { baseHeight: number; baseWidth: number }) {
const { data: zoom } = await this.http.get<number>('/riotclient/zoom-scale')
tools.fixWindowMethodA(zoom, config)
} | /**
* https://github.com/LeagueTavern/fix-lcu-window
* 不知道现在是否需要
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/league-client/index.ts#L569-L573 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | retryFetching | const retryFetching = async () => {
if (retryCount < LeagueClientSyncedData.SUMMONER_FETCH_MAX_RETRIES) {
try {
const data = (await this._i.api.summoner.getCurrentSummoner()).data
this.summoner.setMe(data)
retryCount = 0
this.summoner.setNewIdSystemEnabled(Boolean(data.tagLine))
} catch (error) {
error = error as Error
retryCount++
timerId = setTimeout(retryFetching, 1000)
}
} else {
if (timerId) {
clearTimeout(timerId)
timerId = null
}
this._ipc.sendEvent(this._C.id, 'error-sync-data', 'get-summoner')
this._log.warn(`获取召唤师信息失败,最大重试次数达到`)
}
} | /**
* 个人信息获取十分关键,因此必须优先获取,以实现后续功能
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/league-client/lc-state/index.ts#L925-L946 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | LoggerFactoryMain.create | create(namespace: string) {
return new AkariLogger(this, namespace)
} | /**
* 创建一个日志记录器实例, 应该用于每个对应模块中
* @param namespace
* @returns
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/logger-factory/index.ts#L93-L95 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | MobxUtilsMain.propSync | propSync<T extends object>(
namespace: string,
stateId: string,
obj: T,
propPath: Paths<T> | Paths<T>[]
) {
const key = `${namespace}:${stateId}`
if (!this._rendererSubscription.has(key)) {
this._rendererSubscription.set(key, new Set())
}
if (!this._registeredStates.has(key)) {
this._registeredStates.set(key, {
object: obj,
props: new Map()
})
}
const config = this._registeredStates.get(key)!
if (config.object !== obj) {
throw new Error(`State ${key} already registered with different object`)
}
const paths = Array.isArray(propPath) ? propPath : [propPath]
for (const path of paths) {
if (config.props.has(path)) {
throw new Error(`Prop path ${path} already registered for ${stateId}`)
}
config.props.set(path, {})
const fn = reaction(
() => _.get(obj, path),
(newValue) => {
this._rendererSubscription.get(key)?.forEach((wcId) => {
this._ipc.sendEventToWebContents(
wcId,
MobxUtilsMain.id,
`update-state-prop/${key}`,
path,
isObservable(newValue) ? toJS(newValue) : newValue,
{ action: 'update' }
)
})
}
)
this._disposables.add(fn)
}
} | /**
* 在本地的 Mobx 状态对象上注册任意个属性, 当发生变化时, 推送一个事件
* @param namespace 命名空间
* @param stateId 状态 ID
* @param obj Mobx 状态对象
* @param propPath 属性路径
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/mobx-utils/index.ts#L128-L180 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | MobxUtilsMain.reaction | reaction<T, FireImmediately extends boolean = false>(
expression: (r: IReactionPublic) => T,
effect: (
arg: T,
prev: FireImmediately extends true ? T | undefined : T,
r: IReactionPublic
) => void,
opts?: IReactionOptions<T, FireImmediately>
): () => void {
const disposer = reaction(expression, effect, opts)
this._disposables.add(disposer)
return () => {
if (this._disposables.has(disposer)) {
this._disposables.delete(disposer)
disposer()
}
}
} | /**
* 和 Mobx 的 reaction 方法类似, 但是会管理 reaction 的销毁
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/mobx-utils/index.ts#L185-L203 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | OngoingGameMain._champSelect | private _champSelect(options: { mhSignal: AbortSignal; signal: AbortSignal; force: boolean }) {
const { mhSignal, signal, force } = options
const puuids = this.getPuuidsToLoadForPlayers()
puuids.forEach((puuid) => {
this._loadPlayerMatchHistory(puuid, {
signal,
mhSignal,
force,
tag:
this.settings.matchHistoryTagPreference === 'current'
? this._getCurrentGameMatchHistoryTag()
: 'all',
count: this.settings.matchHistoryLoadCount,
useSgpApi: this.settings.matchHistoryUseSgpApi
})
this._loadPlayerSummoner(puuid, { signal, force })
this._loadPlayerRankedStats(puuid, { signal, force })
this._loadPlayerSavedInfo(puuid, {
signal,
force,
useSgpApi: this.settings.matchHistoryUseSgpApi
})
this._loadPlayerChampionMasteries(puuid, { signal, force })
})
} | /**
*
* @param options 其中的 force, 用于标识是否强制刷新. 若为 false, 在查询条件未发生变动时不会重新加载
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ongoing-game/index.ts#L324-L349 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | OngoingGameMain._inGame | private _inGame(options: { mhSignal: AbortSignal; signal: AbortSignal; force: boolean }) {
const { mhSignal, signal, force } = options
const puuids = this.getPuuidsToLoadForPlayers()
puuids.forEach((puuid) => {
this._loadPlayerMatchHistory(puuid, {
signal,
mhSignal,
force,
tag:
this.settings.matchHistoryTagPreference === 'current'
? this._getCurrentGameMatchHistoryTag()
: 'all',
count: this.settings.matchHistoryLoadCount,
useSgpApi: this.settings.matchHistoryUseSgpApi
})
this._loadPlayerSummoner(puuid, { signal, force })
this._loadPlayerRankedStats(puuid, { signal, force })
this._loadPlayerSavedInfo(puuid, {
signal,
force,
useSgpApi: this.settings.matchHistoryUseSgpApi
})
this._loadPlayerChampionMasteries(puuid, { signal, force })
})
} | /** 目前实现同 #._champSelect */ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ongoing-game/index.ts#L352-L377 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | OngoingGameState.championSelections | get championSelections() {
if (this.queryStage.phase === 'champ-select') {
if (!this._lcData.champSelect.session) {
return {}
}
const selections: Record<string, number> = {}
this._lcData.champSelect.session.myTeam.forEach((p) => {
if (p.puuid && p.puuid !== EMPTY_PUUID) {
selections[p.puuid] = p.championId || p.championPickIntent
}
})
this._lcData.champSelect.session.theirTeam.forEach((p) => {
if (p.puuid && p.puuid !== EMPTY_PUUID) {
selections[p.puuid] = p.championId || p.championPickIntent
}
})
return selections
} else if (this.queryStage.phase === 'in-game') {
if (!this._lcData.gameflow.session) {
return {}
}
const selections: Record<string, number> = {}
this._lcData.gameflow.session.gameData.playerChampionSelections.forEach((p) => {
if (p.puuid && p.puuid !== EMPTY_PUUID) {
selections[p.puuid] = p.championId
}
})
this._lcData.gameflow.session.gameData.teamOne.forEach((p) => {
if (p.championId) {
selections[p.puuid] = p.championId
}
})
this._lcData.gameflow.session.gameData.teamTwo.forEach((p) => {
if (p.championId) {
selections[p.puuid] = p.championId
}
})
return selections
}
return {}
} | /**
* 当前进行的英雄选择
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ongoing-game/state.ts#L82-L130 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | OngoingGameState.teams | get teams() {
if (this.queryStage.phase === 'champ-select') {
if (!this._lcData.champSelect.session) {
return {}
}
const teams: Record<string, string[]> = {}
this._lcData.champSelect.session.myTeam
.filter((p) => p.puuid && p.puuid !== EMPTY_PUUID)
.forEach((p) => {
const key = p.team ? `our-${p.team}` : 'our'
if (!teams[key]) {
teams[key] = []
}
teams[key].push(p.puuid)
})
this._lcData.champSelect.session.theirTeam
.filter((p) => p.puuid && p.puuid !== EMPTY_PUUID)
.forEach((p) => {
const key = p.team ? `their-${p.team}` : 'their'
if (!teams[key]) {
teams[key] = []
}
teams[key].push(p.puuid)
})
return teams
} else if (this.queryStage.phase === 'in-game') {
if (!this._lcData.gameflow.session) {
return {}
}
const teams: Record<string, string[]> = {
100: [],
200: []
}
this._lcData.gameflow.session.gameData.teamOne
.filter((p) => p.puuid && p.puuid !== EMPTY_PUUID)
.forEach((p) => {
teams['100'].push(p.puuid)
})
this._lcData.gameflow.session.gameData.teamTwo
.filter((p) => p.puuid && p.puuid !== EMPTY_PUUID)
.forEach((p) => {
teams['200'].push(p.puuid)
})
return teams
}
return {}
} | /**
* 当前对局的队伍分配
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ongoing-game/state.ts#L205-L260 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | OngoingGameState.queryStage | get queryStage() {
if (
this._lcData.gameflow.session &&
this._lcData.gameflow.session.phase === 'ChampSelect' &&
this._lcData.champSelect.session
) {
return {
phase: 'champ-select' as 'champ-select' | 'in-game',
gameInfo: {
queueId: this._lcData.gameflow.session.gameData.queue.id,
queueType: this._lcData.gameflow.session.gameData.queue.type,
gameId: this._lcData.gameflow.session.gameData.gameId,
gameMode: this._lcData.gameflow.session.gameData.queue.gameMode
}
}
}
if (
this._lcData.gameflow.session &&
(this._lcData.gameflow.session.phase === 'GameStart' ||
this._lcData.gameflow.session.phase === 'InProgress' ||
this._lcData.gameflow.session.phase === 'WaitingForStats' ||
this._lcData.gameflow.session.phase === 'PreEndOfGame' ||
this._lcData.gameflow.session.phase === 'EndOfGame' ||
this._lcData.gameflow.session.phase === 'Reconnect')
) {
return {
phase: 'in-game' as 'champ-select' | 'in-game',
gameInfo: {
queueId: this._lcData.gameflow.session.gameData.queue.id,
queueType: this._lcData.gameflow.session.gameData.queue.type,
gameId: this._lcData.gameflow.session.gameData.gameId,
gameMode: this._lcData.gameflow.session.gameData.queue.gameMode
}
}
}
return {
phase: 'unavailable' as const,
gameInfo: null
}
} | /**
* 当前游戏的进行状态简化,用于区分 League Akari 的几个主要阶段
*
* unavailable - 不需要介入的状态
*
* champ-select - 正在英雄选择阶段
*
* in-game - 在游戏中或游戏结算中
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ongoing-game/state.ts#L271-L312 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | OngoingGameState.isInEog | get isInEog() {
return (
this._lcData.gameflow.phase === 'WaitingForStats' ||
this._lcData.gameflow.phase === 'PreEndOfGame' ||
this._lcData.gameflow.phase === 'EndOfGame'
)
} | /**
* 在游戏结算时,League Akari 会额外进行一些操作
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ongoing-game/state.ts#L317-L323 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | RespawnTimerState.selfChampionInGameSelection | get selfChampionInGameSelection() {
if (!this._lcData.gameflow.session || !this._lcData.summoner.me) {
return null
}
const self = [
...this._lcData.gameflow.session.gameData.teamOne,
...this._lcData.gameflow.session.gameData.teamTwo
].find((v) => v.summonerId === this._lcData.summoner.me!.summonerId)
return self?.championId ?? null
} | /**
* 依赖于 LeagueClientSyncedData 的计算属性
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/respawn-timer/state.ts#L31-L42 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | RiotClientMain.constructor | constructor(deps: any) {
this._ipc = deps['akari-ipc-main']
this._mobx = deps['mobx-utils-main']
this._lc = deps['league-client-main']
this._loggerFactory = deps['logger-factory-main']
this._protocol = deps['akari-protocol-main']
this._log = this._loggerFactory.create(RiotClientMain.id)
this._handleProtocol()
} | // private _eventBus = new RadixEventEmitter() | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/riot-client/index.ts#L47-L56 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | RiotClientMain.request | async request<T = any, D = any>(config: AxiosRequestConfig<D>) {
if (!this._http) {
throw new Error('RC Uninitialized')
}
return this._http.request<T>(config)
} | /**
* RC 的请求, 🐰
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/riot-client/index.ts#L160-L166 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SavedPlayerMain.queryEncounteredGames | async queryEncounteredGames(query: EncounteredGameQueryDto) {
const pageSize = query.pageSize || SavedPlayerMain.ENCOUNTERED_GAME_QUERY_DEFAULT_PAGE_SIZE
const page = query.page || 1
const take = pageSize
const skip = (page - 1) * pageSize
const encounteredGames = await this._storage.dataSource.manager.find(EncounteredGame, {
where: {
selfPuuid: Equal(query.selfPuuid),
puuid: Equal(query.puuid),
queueType: query.queueType ? Equal(query.queueType) : undefined
},
order: { updateAt: query.timeOrder || 'desc' },
take,
skip
})
return encounteredGames
} | /**
*
* @param query
* @returns
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/saved-player/index.ts#L44-L63 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SavedPlayerMain.getPlayerTags | async getPlayerTags(query: SavedPlayerQueryDto) {
if (!query.puuid || !query.selfPuuid) {
throw new Error('puuid, selfPuuid or region cannot be empty')
}
const players = await this._storage.dataSource.manager.findBy(SavedPlayer, {
puuid: Equal(query.puuid)
})
return players
.filter((p) => p.tag)
.map((p) => {
return {
...p,
markedBySelf: p.selfPuuid === query.selfPuuid
}
})
} | /**
* 查询玩家的所有标记, 包括非此账号标记的
* 不可跨区服查询
* @param query
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/saved-player/index.ts#L162-L179 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SavedPlayerMain.updatePlayerTag | async updatePlayerTag(dto: UpdateTagDto) {
// 这里的 selfPuuid 是标记者的 puuid
if (!dto.puuid || !dto.selfPuuid) {
throw new Error('puuid, selfPuuid cannot be empty')
}
const player = await this._storage.dataSource.manager.findOneBy(SavedPlayer, {
puuid: Equal(dto.puuid),
selfPuuid: Equal(dto.selfPuuid)
})
if (player) {
player.tag = dto.tag
player.updateAt = new Date()
return this._storage.dataSource.manager.save(player)
} else {
if (dto.rsoPlatformId === undefined || dto.region === undefined) {
throw new Error('When creating tag, rsoPlatformId, region cannot be empty')
}
const newPlayer = new SavedPlayer()
const date = new Date()
newPlayer.puuid = dto.puuid
newPlayer.tag = dto.tag
newPlayer.selfPuuid = dto.selfPuuid
newPlayer.updateAt = date
newPlayer.rsoPlatformId = dto.rsoPlatformId
newPlayer.region = dto.region
return this._storage.dataSource.manager.save(newPlayer)
}
} | /**
* 更改某个玩家的 Tag, 提供标记者和被标记者的 puuid
* 提供为空则为删除标记
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/saved-player/index.ts#L185-L217 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SelfUpdateMain._updateReleaseUpdatesInfo | private async _updateReleaseUpdatesInfo(debug = false) {
if (this.state.isCheckingUpdates) {
return {
result: 'is-checking-updates'
}
}
this.state.setCheckingUpdates(true)
const sourceUrl = SelfUpdateMain.UPDATE_SOURCE[this.settings.downloadSource]
try {
const release = await this._fetchLatestReleaseInfo(sourceUrl, debug)
this.state.setLastCheckAt(new Date())
if (!release) {
return {
result: 'no-updates'
}
}
this.state.setNewUpdates({
source: this.settings.downloadSource,
currentVersion: app.getVersion(),
releaseNotes: release.body,
downloadUrl: release.archiveFile.browser_download_url,
releaseVersion: release.tag_name,
releaseNotesUrl: release.html_url,
filename: release.archiveFile.name
})
if (this._checkUpdateTimerId) {
clearInterval(this._checkUpdateTimerId)
this._checkUpdateTimerId = setInterval(() => {
this._updateReleaseUpdatesInfo()
}, SelfUpdateMain.UPDATES_CHECK_INTERVAL)
}
} catch (error: any) {
this._log.warn(`尝试检查时更新失败`, error)
return {
result: 'failed',
reason: error.message
}
} finally {
this.state.setCheckingUpdates(false)
}
return {
result: 'new-updates'
}
} | /**
* 尝试加载更新信息
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/self-update/index.ts#L224-L275 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SettingFactoryMain._hasKeyInStorage | _hasKeyInStorage(namespace: string, key: string) {
const key2 = `${namespace}/${key}`
return this._storage.dataSource.manager.existsBy(Setting, { key: key2 })
} | /**
* 拥有指定设置项吗?
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/index.ts#L73-L76 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SettingFactoryMain._saveToStorage | async _saveToStorage(namespace: string, key: string, value: any) {
const key2 = `${namespace}/${key}`
if (!key2 || value === undefined) {
throw new Error('key or value cannot be empty')
}
await this._storage.dataSource.manager.save(Setting.create(key2, value))
} | /**
* 设置指定设置项的值
* @param key
* @param value
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/index.ts#L104-L112 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SettingFactoryMain._removeFromStorage | async _removeFromStorage(namespace: string, key: string) {
const key2 = `${namespace}/${key}`
if (!key2) {
throw new Error('key is required')
}
await this._storage.dataSource.manager.delete(Setting, { key: key2 })
} | /**
* 删除设置项, 但通常没有用过
* @param key
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/index.ts#L118-L125 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SettingFactoryMain.readFromJsonConfigFile | async readFromJsonConfigFile<T = any>(namespace: string, filename: string): Promise<T> {
if (!namespace) {
throw new Error('domain is required')
}
const jsonPath = path.join(
app.getPath('userData'),
SetterSettingService.CONFIG_DIR_NAME,
namespace,
filename
)
if (!fs.existsSync(jsonPath)) {
throw new Error(`config file ${filename} does not exist`)
}
// 读取 UTF-8 格式的 JSON 文件
const content = await fs.promises.readFile(jsonPath, 'utf-8')
return JSON.parse(content)
} | /**
* 从应用目录读取某个 JSON 文件,提供一个文件名
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/index.ts#L130-L149 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SettingFactoryMain.writeToJsonConfigFile | async writeToJsonConfigFile(namespace: string, filename: string, data: any) {
if (!namespace) {
throw new Error('domain is required')
}
const jsonPath = path.join(
app.getPath('userData'),
SetterSettingService.CONFIG_DIR_NAME,
namespace,
filename
)
await fs.promises.mkdir(path.dirname(jsonPath), { recursive: true })
await fs.promises.writeFile(jsonPath, JSON.stringify(data, null, 2), 'utf-8')
} | /**
* 将某个东西写入到 JSON 文件中,提供一个文件名
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/index.ts#L154-L168 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SettingFactoryMain.jsonConfigFileExists | async jsonConfigFileExists(namespace: string, filename: string) {
if (!namespace) {
throw new Error('domain is required')
}
const jsonPath = path.join(
app.getPath('userData'),
SetterSettingService.CONFIG_DIR_NAME,
namespace,
filename
)
return fs.existsSync(jsonPath)
} | /**
* 检查某个 json 配置文件是否存在
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/index.ts#L173-L186 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SetterSettingService._getAllFromStorage | async _getAllFromStorage() {
const items: Record<string, any> = {}
const jobs = Object.entries(this._schema).map(async ([key, schema]) => {
const value = await this._ins._getFromStorage(this._namespace, key as any, schema.default)
items[key] = value
})
await Promise.all(jobs)
return items
} | /**
* 获取所有设置项
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/setter-setting-service.ts#L34-L42 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SetterSettingService.applyToState | async applyToState() {
const items = await this._getAllFromStorage()
Object.entries(items).forEach(([key, value]) => {
_.set(this._obj, key, value)
})
return items
} | /**
* 获取设置项, 并存储到这个 mobx 对象中
* @param obj Mobx Observable
* @returns 所有设置项
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/setter-setting-service.ts#L49-L56 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SetterSettingService.onChange | onChange(key: string, fn: OnChangeCallback) {
if (!this._schema[key]) {
throw new Error(`key ${key} not found in schema`)
}
const _fn = this._schema[key].onChange
// 重复设置, 会报错
if (_fn) {
throw new Error(`onChange for key ${key} already set`)
}
this._schema[key].onChange = fn
} | /**
* 当某个设置项发生变化时, 拦截此行为
* @param newValue
* @param extra
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/setter-setting-service.ts#L75-L87 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SetterSettingService.set | async set(key: string, newValue: any) {
const fn = this._schema[key]?.onChange
if (fn) {
const oldValue = this._obj[key as any]
await fn(newValue, {
oldValue,
key,
setter: async (v?: any) => {
if (v === undefined) {
runInAction(() => _.set(this._obj, key, newValue))
if (newValue === null) {
await this._ins._removeFromStorage(this._namespace, key)
} else {
await this._ins._saveToStorage(this._namespace, key as any, newValue)
}
} else {
runInAction(() => _.set(this._obj, key, v))
if (v === null) {
await this._ins._removeFromStorage(this._namespace, key)
} else {
await this._ins._saveToStorage(this._namespace, key as any, v)
}
}
}
})
} else {
runInAction(() => _.set(this._obj, key, newValue))
if (newValue === null) {
await this._ins._removeFromStorage(this._namespace, key)
} else {
await this._ins._saveToStorage(this._namespace, key, newValue)
}
}
} | /**
* 设置设置项的新值, 并更新状态
* @param key
* @param newValue
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/setter-setting-service.ts#L94-L131 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SetterSettingService.remove | remove(key: string): never {
console.error(`Deemo will finally find his ${key}, not Celia but Alice`)
throw new Error('not implemented')
} | /**
* placeholder
* @param key
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/setter-setting-service.ts#L141-L144 | f75d7cd05ff40722c81517152cc11097052c9433 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.