Apply formatting and fix web request utilities

Add consistent indent rule to ESLint and normalize formatting/indentation across multiple files. Refactor RequestUtil: improve cookie extraction, redirect handling, and HttpGetJson/HttpGetText request flow; fix cookie string builder formatting. Fix uploadGroupNoticeImage promise/error handling and network request flow. Also apply minor style/refactor tweaks in bridge web APIs, onebot handlers, message-store SQL alignment, and Proton AST collector utilities to improve readability and correctness.
This commit is contained in:
手瓜一十雪 committed 2026-05-20 19:16:06 +08:00
1 parent aea2676c31
commit 36c3ed031b
22 files changed
+2144 -2140

No files matched your search

+3
View File
@@ -30,6 +30,7 @@ export default defineConfig([
}, },
}, },
rules: { rules: {
'indent': ['error', 2, { SwitchCase: 1 }],
'no-unused-vars': 'off', 'no-unused-vars': 'off',
'no-useless-assignment': 'off', 'no-useless-assignment': 'off',
'prefer-const': 'off', 'prefer-const': 'off',
@@ -45,6 +46,7 @@ export default defineConfig([
}, },
}, },
rules: { rules: {
'indent': ['error', 2, { SwitchCase: 1 }],
'prefer-const': 'off', 'prefer-const': 'off',
'@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-empty-object-type': 'off', '@typescript-eslint/no-empty-object-type': 'off',
@@ -69,6 +71,7 @@ export default defineConfig([
}, },
}, },
rules: { rules: {
'indent': ['error', 2, { SwitchCase: 1 }],
'prefer-const': 'off', 'prefer-const': 'off',
'react-refresh/only-export-components': 'off', 'react-refresh/only-export-components': 'off',
'react-hooks/set-state-in-effect': 'off', 'react-hooks/set-state-in-effect': 'off',
+31 -31
View File
@@ -47,10 +47,10 @@ function convertBigIntToString(obj: any): any {
} }
export async function getGroupAlbumMediaList( export async function getGroupAlbumMediaList(
bridge: Bridge, bridge: Bridge,
groupId: number, groupId: number,
albumId: string, albumId: string,
attachInfo: string = '' attachInfo: string = ''
): Promise<GroupAlbumMediaResult> { ): Promise<GroupAlbumMediaResult> {
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
@@ -70,9 +70,9 @@ export async function getGroupAlbumMediaList(
}); });
const result = await bridge.sendRawPacket( const result = await bridge.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList', 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetMediaList',
body, body,
15000 15000
); );
if (!result.success || !result.gotResponse || !result.responseData) { if (!result.success || !result.gotResponse || !result.responseData) {
@@ -98,11 +98,11 @@ export async function getGroupAlbumMediaList(
export async function commentGroupAlbumMedia( export async function commentGroupAlbumMedia(
bridge: Bridge, bridge: Bridge,
groupId: number, groupId: number,
albumId: string, albumId: string,
lloc: string, lloc: string,
content: string content: string
): Promise<GroupAlbumCommentResult> { ): Promise<GroupAlbumCommentResult> {
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`; const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const clientKey = Date.now().toString(); const clientKey = Date.now().toString();
@@ -147,9 +147,9 @@ export async function commentGroupAlbumMedia(
}); });
const result = await bridge.sendRawPacket( const result = await bridge.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment', 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunComment',
body, body,
15000 15000
); );
if (!result.success || !result.gotResponse || !result.responseData) { if (!result.success || !result.gotResponse || !result.responseData) {
@@ -175,12 +175,12 @@ export async function commentGroupAlbumMedia(
} }
export async function likeGroupAlbumMedia( export async function likeGroupAlbumMedia(
bridge: Bridge, bridge: Bridge,
groupId: number, groupId: number,
albumId: string, albumId: string,
batchId: string, batchId: string,
lloc: string | undefined, lloc: string | undefined,
isLike: boolean isLike: boolean
): Promise<any> { ): Promise<any> {
const uin = bridge.identity.uin; const uin = bridge.identity.uin;
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
@@ -224,9 +224,9 @@ export async function likeGroupAlbumMedia(
}); });
const result = await bridge.sendRawPacket( const result = await bridge.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike', 'QunAlbum.trpc.qzone.webapp_qun_operation.FeedsWriter.DoQunLike',
body, body,
15000 15000
); );
if (!result.success || !result.gotResponse || !result.responseData) { if (!result.success || !result.gotResponse || !result.responseData) {
@@ -244,10 +244,10 @@ export async function likeGroupAlbumMedia(
} }
export async function deleteGroupAlbumMedia( export async function deleteGroupAlbumMedia(
bridge: Bridge, bridge: Bridge,
groupId: number, groupId: number,
albumId: string, albumId: string,
lloc: string lloc: string
): Promise<any> { ): Promise<any> {
const uin = bridge.identity.uin; const uin = bridge.identity.uin;
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`; const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
@@ -266,9 +266,9 @@ export async function deleteGroupAlbumMedia(
}); });
const result = await bridge.sendRawPacket( const result = await bridge.sendRawPacket(
'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias', 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias',
body, body,
15000 15000
); );
if (!result.success || !result.gotResponse || !result.responseData) { if (!result.success || !result.gotResponse || !result.responseData) {
@@ -120,8 +120,8 @@ export function getBknFromSKey(skey: string): number {
export async function getCookiesStr(bridge: Bridge, domain: string): Promise<string> { export async function getCookiesStr(bridge: Bridge, domain: string): Promise<string> {
const cookieObject = await getCookies(bridge, domain); const cookieObject = await getCookies(bridge, domain);
return Object.entries(cookieObject) return Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`) .map(([key, value]) => `${key}=${value}`)
.join('; '); .join('; ');
} }
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */ /** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
@@ -137,8 +137,8 @@ export async function getCsrfToken(bridge: Bridge): Promise<number> {
export async function getCredentials(bridge: Bridge, domain: string) { export async function getCredentials(bridge: Bridge, domain: string) {
const cookieObject = await getCookies(bridge, domain); const cookieObject = await getCookies(bridge, domain);
const cookiesStr = Object.entries(cookieObject) const cookiesStr = Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`) .map(([key, value]) => `${key}=${value}`)
.join('; '); .join('; ');
const skey = cookieObject['p_skey'] || cookieObject['skey'] || ''; const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
const token = skey ? getBknFromSKey(skey) : 0; const token = skey ? getBknFromSKey(skey) : 0;
+7 -7
View File
@@ -147,13 +147,13 @@ async function createAlbumUploadSession(
* 修复后的上传图片分片方法 * 修复后的上传图片分片方法
*/ */
async function uploadAlbumSlice( async function uploadAlbumSlice(
session: string, session: string,
filePath: string, filePath: string,
// 移除 offset 和 chunkSize 参数,改为在内部控制 // 移除 offset 和 chunkSize 参数,改为在内部控制
imgMd5: string, imgMd5: string,
skey: string, skey: string,
pskey: string, pskey: string,
uin: string uin: string
): Promise<void> { ): Promise<void> {
const img_size = statSync(filePath).size; const img_size = statSync(filePath).size;
const slice_size = 16384; // 严格使用 16KB const slice_size = 16384; // 严格使用 16KB
+34 -34
View File
@@ -19,53 +19,53 @@ export interface GroupEssenceMsgRet {
* 分页获取群精华消息 * 分页获取群精华消息
*/ */
export async function getGroupEssenceMsg( export async function getGroupEssenceMsg(
cookieObject: Record<string, string>, cookieObject: Record<string, string>,
groupCode: string, groupCode: string,
pageStart: number = 0, pageStart: number = 0,
pageLimit: number = 50 pageLimit: number = 50
): Promise<GroupEssenceMsgRet | undefined> { ): Promise<GroupEssenceMsgRet | undefined> {
const bkn = getBknFromCookie(cookieObject); const bkn = getBknFromCookie(cookieObject);
const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({ const url = `https://qun.qq.com/cgi-bin/group_digest/digest_list?${new URLSearchParams({
bkn: bkn, bkn: bkn,
page_start: pageStart.toString(), page_start: pageStart.toString(),
page_limit: pageLimit.toString(), page_limit: pageLimit.toString(),
group_code: groupCode, group_code: groupCode,
}).toString()}`; }).toString()}`;
try { try {
const ret = await RequestUtil.HttpGetJson<GroupEssenceMsgRet>( const ret = await RequestUtil.HttpGetJson<GroupEssenceMsgRet>(
url, url,
'GET', 'GET',
'', '',
{ Cookie: cookieToString(cookieObject) } { Cookie: cookieToString(cookieObject) }
); );
return ret.retcode === 0 ? ret : undefined; return ret.retcode === 0 ? ret : undefined;
} catch (e) { } catch (e) {
log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s', log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s',
groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e)); groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e));
return undefined; return undefined;
} }
} }
/** /**
* 获取所有群精华消息 (最多循环 20 页) * 获取所有群精华消息 (最多循环 20 页)
*/ */
export async function getGroupEssenceMsgAll( export async function getGroupEssenceMsgAll(
cookieObject: Record<string, string>, cookieObject: Record<string, string>,
groupCode: string groupCode: string
): Promise<GroupEssenceMsgRet[]> { ): Promise<GroupEssenceMsgRet[]> {
const ret: GroupEssenceMsgRet[] = []; const ret: GroupEssenceMsgRet[] = [];
for (let i = 0; i < 20; i++) { for (let i = 0; i < 20; i++) {
const data = await getGroupEssenceMsg(cookieObject, groupCode, i, 50); const data = await getGroupEssenceMsg(cookieObject, groupCode, i, 50);
if (!data) break; if (!data) break;
ret.push(data); ret.push(data);
if (data.data?.is_end) break; if (data.data?.is_end) break;
} }
return ret; return ret;
} }
+32 -32
View File
@@ -13,41 +13,41 @@ export enum WebHonorType {
async function fetchHonorData(cookieObject: Record<string, string>, groupCode: string, type: number) { async function fetchHonorData(cookieObject: Record<string, string>, groupCode: string, type: number) {
let resJson; let resJson;
try { try {
const res = await RequestUtil.HttpGetText( const res = await RequestUtil.HttpGetText(
`https://qun.qq.com/interactive/honorlist?${new URLSearchParams({ `https://qun.qq.com/interactive/honorlist?${new URLSearchParams({
gc: groupCode, gc: groupCode,
type: type.toString(), type: type.toString(),
}).toString()}`, }).toString()}`,
'GET', 'GET',
'', '',
{ Cookie: cookieToString(cookieObject) } { Cookie: cookieToString(cookieObject) }
); );
const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res); const match = /window\.__INITIAL_STATE__=(.*?);/.exec(res);
if (match?.[1]) { if (match?.[1]) {
resJson = JSON.parse(match[1].trim()); resJson = JSON.parse(match[1].trim());
}
return type === 1 ? resJson?.talkativeList : resJson?.actorList;
} catch (e) {
throw new Error(`获取群 ${groupCode} 类型 ${type} 的荣誉信息失败: ${e}`);
} }
return type === 1 ? resJson?.talkativeList : resJson?.actorList;
} catch (e) {
throw new Error(`获取群 ${groupCode} 类型 ${type} 的荣誉信息失败: ${e}`);
}
} }
export async function getHonorListWebAPI(cookieObject: Record<string, string>, groupCode: string, type: number) { export async function getHonorListWebAPI(cookieObject: Record<string, string>, groupCode: string, type: number) {
try { try {
const data = await fetchHonorData(cookieObject, groupCode, type); const data = await fetchHonorData(cookieObject, groupCode, type);
if (!data) return []; if (!data) return [];
return data.map((item: any) => ({ return data.map((item: any) => ({
user_id: item?.uin, user_id: item?.uin,
nickname: item?.name, nickname: item?.name,
avatar: item?.avatar, avatar: item?.avatar,
description: item?.desc, description: item?.desc,
})); }));
} catch (e) { } catch (e) {
log.warn('getHonorListWebAPI failed (group=%s type=%d): %s', log.warn('getHonorListWebAPI failed (group=%s type=%d): %s',
groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e)); groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e));
return []; return [];
} }
} }
+186 -186
View File
@@ -37,237 +37,237 @@ export interface WebApiGroupNoticeRet {
} }
export function calculateBkn(key: string): string { export function calculateBkn(key: string): string {
let hash = 5381; let hash = 5381;
for (let i = 0; i < key.length; i++) { for (let i = 0; i < key.length; i++) {
const code = key.charCodeAt(i); const code = key.charCodeAt(i);
hash = hash + (hash << 5) + code; hash = hash + (hash << 5) + code;
} }
return (hash & 0x7FFFFFFF).toString(); return (hash & 0x7FFFFFFF).toString();
} }
/** /**
* 发送群公告 Web API * 发送群公告 Web API
*/ */
export async function setGroupNoticeWebAPI( export async function setGroupNoticeWebAPI(
cookieObject: Record<string, string>, cookieObject: Record<string, string>,
groupCode: string, groupCode: string,
content: string, content: string,
pinned: number = 0, pinned: number = 0,
type: number = 1, type: number = 1,
isShowEditCard: number = 1, isShowEditCard: number = 1,
tipWindowType: number = 1, tipWindowType: number = 1,
confirmRequired: number = 1, confirmRequired: number = 1,
picId: string = '', picId: string = '',
imgWidth: number = 540, imgWidth: number = 540,
imgHeight: number = 300 imgHeight: number = 300
): Promise<SetNoticeRetSuccess | undefined> { ): Promise<SetNoticeRetSuccess | undefined> {
try { try {
// 分别获取 skey 和 p_skey // 分别获取 skey 和 p_skey
const skey = cookieObject['skey'] || ''; const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey; const pskey = cookieObject['p_skey'] || skey;
const bodyBkn = calculateBkn(skey); const bodyBkn = calculateBkn(skey);
const urlBkn = calculateBkn(pskey); const urlBkn = calculateBkn(pskey);
// //
// console.log(skey) // console.log(skey)
// console.log(pskey) // console.log(pskey)
// //
// console.log(urlBkn); // console.log(urlBkn);
// console.log(bodyBkn) // console.log(bodyBkn)
const settings = JSON.stringify({ const settings = JSON.stringify({
is_show_edit_card: isShowEditCard, is_show_edit_card: isShowEditCard,
tip_window_type: tipWindowType, tip_window_type: tipWindowType,
confirm_required: confirmRequired, confirm_required: confirmRequired,
}); });
const bodyParams: Record<string, string> = { const bodyParams: Record<string, string> = {
qid: groupCode, qid: groupCode,
bkn: bodyBkn, bkn: bodyBkn,
text: content, text: content,
pinned: pinned.toString(), pinned: pinned.toString(),
type: type.toString(), type: type.toString(),
settings, settings,
}; };
if (picId !== '') { if (picId !== '') {
bodyParams.pic = picId; bodyParams.pic = picId;
bodyParams.imgWidth = imgWidth.toString(); bodyParams.imgWidth = imgWidth.toString();
bodyParams.imgHeight = imgHeight.toString(); bodyParams.imgHeight = imgHeight.toString();
}
// 注意这里:URL 必须使用 skey 算出来的 bkn
const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${urlBkn}`;
const body = new URLSearchParams(bodyParams).toString();
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
url,
'POST',
body,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded'
},
true,
false
);
return ret;
} catch (e) {
log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
return undefined;
} }
// 注意这里:URL 必须使用 skey 算出来的 bkn
const url = `https://web.qun.qq.com/cgi-bin/announce/add_qun_notice?bkn=${urlBkn}`;
const body = new URLSearchParams(bodyParams).toString();
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
url,
'POST',
body,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded'
},
true,
false
);
return ret;
} catch (e) {
log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
return undefined;
}
} }
/** /**
* 获取群公告列表 Web API * 获取群公告列表 Web API
*/ */
export async function getGroupNoticeWebAPI( export async function getGroupNoticeWebAPI(
cookieObject: Record<string, string>, cookieObject: Record<string, string>,
groupCode: string, groupCode: string,
start: number = -1, // -1 表示第一页 start: number = -1, // -1 表示第一页
count: number = 20 // 抓包中是 10,你可以根据需要调整 count: number = 20 // 抓包中是 10,你可以根据需要调整
): Promise<WebApiGroupNoticeRet | undefined> { ): Promise<WebApiGroupNoticeRet | undefined> {
try { try {
const skey = cookieObject['skey'] || ''; const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey; const pskey = cookieObject['p_skey'] || skey;
const bodyBkn = calculateBkn(skey); // URL 使用 skey 算出的 bkn const bodyBkn = calculateBkn(skey); // URL 使用 skey 算出的 bkn
const urlBkn = calculateBkn(pskey); // Body 使用 p_skey 算出的 bkn const urlBkn = calculateBkn(pskey); // Body 使用 p_skey 算出的 bkn
const bodyParams = new URLSearchParams({ const bodyParams = new URLSearchParams({
qid: groupCode, qid: groupCode,
bkn: bodyBkn, // Body 中传入 p_skey 计算结果 bkn: bodyBkn, // Body 中传入 p_skey 计算结果
ft: '23', ft: '23',
s: start.toString(), // 分页游标 s: start.toString(), // 分页游标
n: count.toString(), // 获取数量 n: count.toString(), // 获取数量
i: '1', i: '1',
ni: '1' ni: '1'
}).toString(); }).toString();
const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`; const url = `https://web.qun.qq.com/cgi-bin/announce/list_announce?bkn=${urlBkn}`;
const ret = await RequestUtil.HttpGetJson<WebApiGroupNoticeRet>( const ret = await RequestUtil.HttpGetJson<WebApiGroupNoticeRet>(
url, url,
'POST', 'POST',
bodyParams, bodyParams,
{ {
Cookie: cookieToString(cookieObject), Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded', 'Content-Type': 'application/x-www-form-urlencoded',
'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148' 'Referer': 'https://web.qun.qq.com/mannounce/index.html?_wv=1031&_bid=148'
}, },
true, true,
false false
); );
// console.log(JSON.stringify(ret, null, 2)); // console.log(JSON.stringify(ret, null, 2));
return ret?.ec === 0 ? ret : undefined; return ret?.ec === 0 ? ret : undefined;
} catch (e) { } catch (e) {
log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e)); log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
return undefined; return undefined;
} }
} }
/** /**
* 上传群公告图片 Web API * 上传群公告图片 Web API
*/ */
export async function uploadGroupNoticeImage( export async function uploadGroupNoticeImage(
cookieObject: Record<string, string>, cookieObject: Record<string, string>,
imageBuffer: Buffer imageBuffer: Buffer
): Promise<{ id: string; width: number; height: number } | undefined> { ): Promise<{ id: string; width: number; height: number } | undefined> {
try { try {
const bkn = calculateBkn(cookieObject['skey']); const bkn = calculateBkn(cookieObject['skey']);
const boundary = `-----------------------------${Date.now()}`; const boundary = `-----------------------------${Date.now()}`;
const parts: Buffer[] = []; const parts: Buffer[] = [];
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`)); parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="bkn"\r\n\r\n${bkn}\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`)); parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="source"\r\n\r\ntroopNotice\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`)); parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="m"\r\n\r\n0\r\n`));
parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`)); parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="pic_up"; filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`));
parts.push(imageBuffer); parts.push(imageBuffer);
parts.push(Buffer.from(`\r\n--${boundary}--\r\n`)); parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
const body = Buffer.concat(parts); const body = Buffer.concat(parts);
const options = { const options = {
hostname: 'web.qun.qq.com', hostname: 'web.qun.qq.com',
path: '/cgi-bin/announce/upload_img', path: '/cgi-bin/announce/upload_img',
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': `multipart/form-data; boundary=${boundary}`, 'Content-Type': `multipart/form-data; boundary=${boundary}`,
'Content-Length': body.length, 'Content-Length': body.length,
'Cookie': cookieToString(cookieObject), 'Cookie': cookieToString(cookieObject),
}, },
}; };
return new Promise((resolve) => { return new Promise((resolve) => {
const req = https.request(options, (res) => { const req = https.request(options, (res) => {
let data = ''; let data = '';
res.on('data', (chunk) => { data += chunk; }); res.on('data', (chunk) => { data += chunk; });
res.on('end', () => { res.on('end', () => {
try { try {
const result = JSON.parse(data) as UploadImageRetSuccess; const result = JSON.parse(data) as UploadImageRetSuccess;
if (result.ec === 0 && result.id) { if (result.ec === 0 && result.id) {
const unescapedIdStr = result.id.replace(/&quot;/g, '"'); const unescapedIdStr = result.id.replace(/&quot;/g, '"');
const idObj = JSON.parse(unescapedIdStr); const idObj = JSON.parse(unescapedIdStr);
resolve({ id: idObj.id, width: parseInt(idObj.w), height: parseInt(idObj.h) }); resolve({ id: idObj.id, width: parseInt(idObj.w), height: parseInt(idObj.h) });
} else { } else {
resolve(undefined);
}
} catch {
resolve(undefined);
}
});
});
req.on('error', (err) => {
log.warn('uploadGroupNoticeImage transport error: %s', err.message);
resolve(undefined); resolve(undefined);
}); }
req.write(body); } catch {
req.end(); resolve(undefined);
}
}); });
} catch (e) { });
log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e)); req.on('error', (err) => {
return undefined; log.warn('uploadGroupNoticeImage transport error: %s', err.message);
} resolve(undefined);
});
req.write(body);
req.end();
});
} catch (e) {
log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e));
return undefined;
}
} }
/** /**
* 删除群公告 Web API * 删除群公告 Web API
*/ */
export async function deleteGroupNotice( export async function deleteGroupNotice(
cookieObject: Record<string, string>, cookieObject: Record<string, string>,
groupCode: string, groupCode: string,
fid: string fid: string
): Promise<boolean> { ): Promise<boolean> {
try { try {
const skey = cookieObject['skey'] || ''; const skey = cookieObject['skey'] || '';
const pskey = cookieObject['p_skey'] || skey; const pskey = cookieObject['p_skey'] || skey;
const bodyBkn = calculateBkn(skey); // Body 使用 skey 算出的 bkn const bodyBkn = calculateBkn(skey); // Body 使用 skey 算出的 bkn
const urlBkn = calculateBkn(pskey); // URL 使用 p_skey 算出的 bkn const urlBkn = calculateBkn(pskey); // URL 使用 p_skey 算出的 bkn
const params = new URLSearchParams({ const params = new URLSearchParams({
bkn: bodyBkn, // 注意这里:POST Body 放入 bodyBkn bkn: bodyBkn, // 注意这里:POST Body 放入 bodyBkn
fid: fid, fid: fid,
qid: groupCode, qid: groupCode,
}).toString(); }).toString();
// 注意这里:URL 拼接 urlBkn // 注意这里:URL 拼接 urlBkn
const url = `https://web.qun.qq.com/cgi-bin/announce/del_feed?bkn=${urlBkn}`; const url = `https://web.qun.qq.com/cgi-bin/announce/del_feed?bkn=${urlBkn}`;
const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>( const ret = await RequestUtil.HttpGetJson<SetNoticeRetSuccess>(
url, url,
'POST', 'POST',
params, params,
{ {
Cookie: cookieToString(cookieObject), Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded' 'Content-Type': 'application/x-www-form-urlencoded'
}, },
true, true,
false false
); );
return ret?.ec === 0; return ret?.ec === 0;
} catch (e) { } catch (e) {
log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e)); log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e));
return false; return false;
} }
} }
+101 -101
View File
@@ -2,126 +2,126 @@ import https from 'node:https';
import http from 'node:http'; import http from 'node:http';
export class RequestUtil { export class RequestUtil {
static async HttpsGetCookies(url: string): Promise<{ [key: string]: string; }> { static async HttpsGetCookies(url: string): Promise<{ [key: string]: string; }> {
const client = url.startsWith('https') ? https : http; const client = url.startsWith('https') ? https : http;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const req = client.get(url, (res) => { const req = client.get(url, (res) => {
const cookies: { [key: string]: string; } = {}; const cookies: { [key: string]: string; } = {};
res.on('data', () => { }); // 必须消耗流 res.on('data', () => { }); // 必须消耗流
res.on('end', () => { res.on('end', () => {
this.handleRedirect(res, url, cookies) this.handleRedirect(res, url, cookies)
.then(resolve) .then(resolve)
.catch(reject); .catch(reject);
});
if (res.headers['set-cookie']) {
this.extractCookies(res.headers['set-cookie'], cookies);
}
});
req.on('error', (error: Error) => {
reject(error);
});
}); });
}
private static async handleRedirect(res: http.IncomingMessage, url: string, cookies: { [key: string]: string; }): Promise<{ [key: string]: string; }> { if (res.headers['set-cookie']) {
if (res.statusCode === 301 || res.statusCode === 302) { this.extractCookies(res.headers['set-cookie'], cookies);
if (res.headers.location) {
const redirectUrl = new URL(res.headers.location, url);
const redirectCookies = await this.HttpsGetCookies(redirectUrl.href);
return { ...cookies, ...redirectCookies };
}
} }
return cookies; });
}
private static extractCookies(setCookieHeaders: string[], cookies: { [key: string]: string; }) { req.on('error', (error: Error) => {
setCookieHeaders.forEach((cookie) => { reject(error);
const parts = cookie.split(';')[0]?.split('='); });
if (parts) { });
const key = parts[0]; }
const value = parts[1];
if (key && value && key.length > 0 && value.length > 0) {
cookies[key] = value;
}
}
});
}
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: any, headers: { private static async handleRedirect(res: http.IncomingMessage, url: string, cookies: { [key: string]: string; }): Promise<{ [key: string]: string; }> {
if (res.statusCode === 301 || res.statusCode === 302) {
if (res.headers.location) {
const redirectUrl = new URL(res.headers.location, url);
const redirectCookies = await this.HttpsGetCookies(redirectUrl.href);
return { ...cookies, ...redirectCookies };
}
}
return cookies;
}
private static extractCookies(setCookieHeaders: string[], cookies: { [key: string]: string; }) {
setCookieHeaders.forEach((cookie) => {
const parts = cookie.split(';')[0]?.split('=');
if (parts) {
const key = parts[0];
const value = parts[1];
if (key && value && key.length > 0 && value.length > 0) {
cookies[key] = value;
}
}
});
}
static async HttpGetJson<T>(url: string, method: string = 'GET', data?: any, headers: {
[key: string]: string; [key: string]: string;
} = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise<T> { } = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise<T> {
const option = new URL(url); const option = new URL(url);
const protocol = url.startsWith('https://') ? https : http; const protocol = url.startsWith('https://') ? https : http;
const options = { const options = {
hostname: option.hostname, hostname: option.hostname,
port: option.port, port: option.port,
path: option.pathname + option.search, path: option.pathname + option.search,
method, method,
headers, headers,
}; };
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const req = protocol.request(options, (res: http.IncomingMessage) => { const req = protocol.request(options, (res: http.IncomingMessage) => {
if ((res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307 || res.statusCode === 308) && res.headers.location) { if ((res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307 || res.statusCode === 308) && res.headers.location) {
if (maxRedirects <= 0) { if (maxRedirects <= 0) {
reject(new Error('Too many redirects')); reject(new Error('Too many redirects'));
return; return;
} }
const redirectUrl = new URL(res.headers.location, url).href; const redirectUrl = new URL(res.headers.location, url).href;
this.HttpGetJson<T>(redirectUrl, method, data, headers, isJsonRet, isArgJson, maxRedirects - 1) this.HttpGetJson<T>(redirectUrl, method, data, headers, isJsonRet, isArgJson, maxRedirects - 1)
.then(resolve) .then(resolve)
.catch(reject); .catch(reject);
return; return;
} }
let responseBody = ''; let responseBody = '';
res.on('data', (chunk: string | Buffer) => { responseBody += chunk.toString(); }); res.on('data', (chunk: string | Buffer) => { responseBody += chunk.toString(); });
res.on('end', () => { res.on('end', () => {
try { try {
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) { if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
if (isJsonRet) { if (isJsonRet) {
resolve(JSON.parse(responseBody) as T); resolve(JSON.parse(responseBody) as T);
} else { } else {
resolve(responseBody as T); resolve(responseBody as T);
} }
} else { } else {
reject(new Error(`Unexpected status code: ${res.statusCode}`)); reject(new Error(`Unexpected status code: ${res.statusCode}`));
}
} catch (parseError: any) {
reject(new Error(parseError.message));
}
});
});
req.on('error', (error: Error) => reject(error));
if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
req.write(isArgJson ? JSON.stringify(data) : data);
} }
req.end(); } catch (parseError: any) {
reject(new Error(parseError.message));
}
}); });
} });
static async HttpGetText(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string; } = {}) { req.on('error', (error: Error) => reject(error));
return this.HttpGetJson<string>(url, method, data, headers, false, false); if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
} req.write(isArgJson ? JSON.stringify(data) : data);
}
req.end();
});
}
static async HttpGetText(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string; } = {}) {
return this.HttpGetJson<string>(url, method, data, headers, false, false);
}
} }
export function cookieToString(cookieObject: Record<string, string>): string { export function cookieToString(cookieObject: Record<string, string>): string {
return Object.entries(cookieObject) return Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`) .map(([key, value]) => `${key}=${value}`)
.join('; '); .join('; ');
} }
export function getBknFromCookie(cookieObject: Record<string, string>): string { export function getBknFromCookie(cookieObject: Record<string, string>): string {
const skey = cookieObject['p_skey'] || cookieObject['skey'] || ''; const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
let hash = 5381; let hash = 5381;
for (let i = 0; i < skey.length; i++) { for (let i = 0; i < skey.length; i++) {
hash += (hash << 5) + skey.charCodeAt(i); hash += (hash << 5) + skey.charCodeAt(i);
} }
return (hash & 2147483647).toString(); return (hash & 2147483647).toString();
} }
+10 -10
View File
@@ -1004,11 +1004,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
const data = await ctx.bridge.getMiniAppArk( const data = await ctx.bridge.getMiniAppArk(
String(type), String(type),
String(title), String(title),
String(desc), String(desc),
String(picUrl), String(picUrl),
String(jumpUrl) String(jumpUrl)
); );
return okResponse(data); return okResponse(data);
} catch (e) { } catch (e) {
@@ -1030,11 +1030,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
try { try {
const data = await ctx.bridge.clickInlineKeyboardButton( const data = await ctx.bridge.clickInlineKeyboardButton(
groupId, groupId,
botAppid, botAppid,
String(buttonId), String(buttonId),
String(callbackData), String(callbackData),
msgSeq msgSeq
); );
return okResponse(data); return okResponse(data);
} catch (e) { } catch (e) {
+3 -3
View File
@@ -243,9 +243,9 @@ function collectByName<T extends { name: string }>(
function pickAutoName(kind: keyof OneBotNetworks, used: Map<string, unknown>, counter: number): string { function pickAutoName(kind: keyof OneBotNetworks, used: Map<string, unknown>, counter: number): string {
const prefix = const prefix =
kind === 'httpServers' ? 'http' : kind === 'httpServers' ? 'http' :
kind === 'httpClients' ? 'httppost' : kind === 'httpClients' ? 'httppost' :
kind === 'wsServers' ? 'ws' : kind === 'wsServers' ? 'ws' :
'wsclient'; 'wsclient';
let candidate = `${prefix}-${counter}`; let candidate = `${prefix}-${counter}`;
while (used.has(candidate)) { while (used.has(candidate)) {
counter += 1; counter += 1;
+4 -4
View File
@@ -130,17 +130,17 @@ export class MessageStore {
// So for private messages, we only match by message_hash and is_group flag. // So for private messages, we only match by message_hash and is_group flag.
const row = isGroup const row = isGroup
? this.db.prepare( ? this.db.prepare(
`SELECT sequence `SELECT sequence
FROM messages FROM messages
WHERE is_group = 1 AND session_id = ? AND message_hash = ? WHERE is_group = 1 AND session_id = ? AND message_hash = ?
LIMIT 1` LIMIT 1`
).get(sessionId, messageId) as { sequence: number } | undefined ).get(sessionId, messageId) as { sequence: number } | undefined
: this.db.prepare( : this.db.prepare(
`SELECT sequence `SELECT sequence
FROM messages FROM messages
WHERE is_group = 0 AND message_hash = ? WHERE is_group = 0 AND message_hash = ?
LIMIT 1` LIMIT 1`
).get(messageId) as { sequence: number } | undefined; ).get(messageId) as { sequence: number } | undefined;
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) { if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) {
return null; return null;
+111 -111
View File
@@ -1,14 +1,14 @@
import ts from 'typescript'; import ts from 'typescript';
import { import {
WireType, WireType,
PB_MARKER, PB_REPEATED_MARKER, PB_MARKER, PB_REPEATED_MARKER,
type ProtobufField, type ProtobufMessage, type ProtobufField, type ProtobufMessage,
type GenericProtobufTemplate, type GenericFieldTemplate, type GenericProtobufTemplate, type GenericFieldTemplate,
} from './types.js'; } from './types.js';
import { isKeywordTypeNode, typeNodeToMangledName, type ImportedTypeNameResolver } from './utils.js'; import { isKeywordTypeNode, typeNodeToMangledName, type ImportedTypeNameResolver } from './utils.js';
function identityImportedTypeName(name: string): string { function identityImportedTypeName(name: string): string {
return name; return name;
} }
/** /**
@@ -19,147 +19,147 @@ function identityImportedTypeName(name: string): string {
* type; nested generic instantiations on its fields would otherwise be missed.) * type; nested generic instantiations on its fields would otherwise be missed.)
*/ */
export function* collectConcreteFieldGenericTypeArgs( export function* collectConcreteFieldGenericTypeArgs(
node: ts.InterfaceDeclaration, node: ts.InterfaceDeclaration,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): IterableIterator<ts.TypeNode> { ): IterableIterator<ts.TypeNode> {
if (node.typeParameters?.length) return; if (node.typeParameters?.length) return;
for (const m of node.members) { for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) continue; if (!ts.isPropertySignature(m) || !m.type) continue;
const parsed = parsePbTypeRef(m, resolveImportedTypeName); const parsed = parsePbTypeRef(m, resolveImportedTypeName);
if (!parsed) continue; if (!parsed) continue;
const ta = parsed.typeArgNode; const ta = parsed.typeArgNode;
if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) { if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) {
yield ta; yield ta;
}
} }
}
} }
/** Collect a concrete (non-generic) interface with pb<>/pb_repeated<> fields. */ /** Collect a concrete (non-generic) interface with pb<>/pb_repeated<> fields. */
export function collectInterface( export function collectInterface(
node: ts.InterfaceDeclaration, node: ts.InterfaceDeclaration,
sf: ts.SourceFile, sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): ProtobufMessage | null { ): ProtobufMessage | null {
const fields: ProtobufField[] = []; const fields: ProtobufField[] = [];
for (const m of node.members) { for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) continue; if (!ts.isPropertySignature(m) || !m.type) continue;
const f = extractField(m, sf, resolveImportedTypeName); const f = extractField(m, sf, resolveImportedTypeName);
if (f) fields.push(f); if (f) fields.push(f);
} }
// Register interfaces that are EXPLICITLY empty (`interface X {}`) as // Register interfaces that are EXPLICITLY empty (`interface X {}`) as
// zero-field proto messages — proto3 wire format allows them and // zero-field proto messages — proto3 wire format allows them and
// downstream code routinely uses them for "this OIDB call has no // downstream code routinely uses them for "this OIDB call has no
// meaningful response body" placeholders. Interfaces that have // meaningful response body" placeholders. Interfaces that have
// members but no pb-marked fields are NOT proto messages — they // members but no pb-marked fields are NOT proto messages — they
// belong to regular TS types and must stay unregistered to avoid // belong to regular TS types and must stay unregistered to avoid
// polluting the registry. // polluting the registry.
if (fields.length === 0 && node.members.length > 0) return null; if (fields.length === 0 && node.members.length > 0) return null;
return { name: node.name.text, fields }; return { name: node.name.text, fields };
} }
/** Collect a generic interface template. */ /** Collect a generic interface template. */
export function collectGenericInterface( export function collectGenericInterface(
node: ts.InterfaceDeclaration, node: ts.InterfaceDeclaration,
sf: ts.SourceFile, sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): GenericProtobufTemplate | null { ): GenericProtobufTemplate | null {
const typeParams = node.typeParameters!.map(p => p.name.text); const typeParams = node.typeParameters!.map(p => p.name.text);
const tpSet = new Set(typeParams); const tpSet = new Set(typeParams);
const fields: GenericFieldTemplate[] = []; const fields: GenericFieldTemplate[] = [];
for (const m of node.members) { for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) continue; if (!ts.isPropertySignature(m) || !m.type) continue;
const f = extractGenericField(m, sf, tpSet, resolveImportedTypeName); const f = extractGenericField(m, sf, tpSet, resolveImportedTypeName);
if (f) fields.push(f); if (f) fields.push(f);
} }
return fields.length ? { name: node.name.text, typeParams, fields } : null; return fields.length ? { name: node.name.text, typeParams, fields } : null;
} }
// ── helpers ─────────────────────────────────────────────────────────── // ── helpers ───────────────────────────────────────────────────────────
function parsePbTypeRef( function parsePbTypeRef(
member: ts.PropertySignature, member: ts.PropertySignature,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): { marker: string; fieldNumber: number; typeArgNode: ts.TypeNode } | null { ): { marker: string; fieldNumber: number; typeArgNode: ts.TypeNode } | null {
const t = member.type!; const t = member.type!;
if (!ts.isTypeReferenceNode(t) || !ts.isIdentifier(t.typeName)) return null; if (!ts.isTypeReferenceNode(t) || !ts.isIdentifier(t.typeName)) return null;
// Resolve the marker name through aliased imports so `import { pb as P }` // Resolve the marker name through aliased imports so `import { pb as P }`
// / `import { pb_repeated as PR }` still match the marker constants. // / `import { pb_repeated as PR }` still match the marker constants.
const marker = resolveImportedTypeName(t.typeName.text); const marker = resolveImportedTypeName(t.typeName.text);
if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER) return null; if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER) return null;
const ta = t.typeArguments; const ta = t.typeArguments;
if (!ta || ta.length !== 2) return null; if (!ta || ta.length !== 2) return null;
const fnNode = ta[0]; const fnNode = ta[0];
if (!ts.isLiteralTypeNode(fnNode) || !ts.isNumericLiteral(fnNode.literal)) return null; if (!ts.isLiteralTypeNode(fnNode) || !ts.isNumericLiteral(fnNode.literal)) return null;
return { marker, fieldNumber: Number(fnNode.literal.text), typeArgNode: ta[1] }; return { marker, fieldNumber: Number(fnNode.literal.text), typeArgNode: ta[1] };
} }
function resolveTypeName( function resolveTypeName(
node: ts.TypeNode, node: ts.TypeNode,
sf: ts.SourceFile, sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver, resolveImportedTypeName: ImportedTypeNameResolver,
): string | null { ): string | null {
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) { if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) {
// Generic instantiations (e.g. `Wrapper<uint_32>`) must resolve to the // Generic instantiations (e.g. `Wrapper<uint_32>`) must resolve to the
// mangled name produced by monomorphization so wire-type resolution can // mangled name produced by monomorphization so wire-type resolution can
// find the message in the registry. Without this the field would carry // find the message in the registry. Without this the field would carry
// the bare identifier `"Wrapper"` and never link to `Wrapper__uint_32`. // the bare identifier `"Wrapper"` and never link to `Wrapper__uint_32`.
if (node.typeArguments && node.typeArguments.length > 0) { if (node.typeArguments && node.typeArguments.length > 0) {
return typeNodeToMangledName(node, sf, resolveImportedTypeName); return typeNodeToMangledName(node, sf, resolveImportedTypeName);
}
return resolveImportedTypeName(node.typeName.text);
} }
if (isKeywordTypeNode(node)) return node.getText(sf); return resolveImportedTypeName(node.typeName.text);
return null; }
if (isKeywordTypeNode(node)) return node.getText(sf);
return null;
} }
function extractField( function extractField(
member: ts.PropertySignature, member: ts.PropertySignature,
sf: ts.SourceFile, sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver, resolveImportedTypeName: ImportedTypeNameResolver,
): ProtobufField | null { ): ProtobufField | null {
const parsed = parsePbTypeRef(member, resolveImportedTypeName); const parsed = parsePbTypeRef(member, resolveImportedTypeName);
if (!parsed) return null; if (!parsed) return null;
const typeName = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName); const typeName = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName);
if (!typeName || !ts.isIdentifier(member.name)) return null; if (!typeName || !ts.isIdentifier(member.name)) return null;
return { return {
name: (member.name as ts.Identifier).text, name: (member.name as ts.Identifier).text,
fieldNumber: parsed.fieldNumber, fieldNumber: parsed.fieldNumber,
typeName, typeName,
wireType: WireType.Varint, // placeholder wireType: WireType.Varint, // placeholder
isMessage: false, // placeholder isMessage: false, // placeholder
isOptional: member.questionToken != null, isOptional: member.questionToken != null,
isRepeated: parsed.marker === PB_REPEATED_MARKER, isRepeated: parsed.marker === PB_REPEATED_MARKER,
}; };
} }
function extractGenericField( function extractGenericField(
member: ts.PropertySignature, member: ts.PropertySignature,
sf: ts.SourceFile, sf: ts.SourceFile,
tpSet: Set<string>, tpSet: Set<string>,
resolveImportedTypeName: ImportedTypeNameResolver, resolveImportedTypeName: ImportedTypeNameResolver,
): GenericFieldTemplate | null { ): GenericFieldTemplate | null {
const parsed = parsePbTypeRef(member, resolveImportedTypeName); const parsed = parsePbTypeRef(member, resolveImportedTypeName);
if (!parsed) return null; if (!parsed) return null;
const raw = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName); const raw = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName);
if (!raw || !ts.isIdentifier(member.name)) return null; if (!raw || !ts.isIdentifier(member.name)) return null;
const result: GenericFieldTemplate = { const result: GenericFieldTemplate = {
name: (member.name as ts.Identifier).text, name: (member.name as ts.Identifier).text,
fieldNumber: parsed.fieldNumber, fieldNumber: parsed.fieldNumber,
rawTypeName: tpSet.has(raw) ? raw : resolveImportedTypeName(raw), rawTypeName: tpSet.has(raw) ? raw : resolveImportedTypeName(raw),
isTypeParam: tpSet.has(raw), isTypeParam: tpSet.has(raw),
isOptional: member.questionToken != null, isOptional: member.questionToken != null,
isRepeated: parsed.marker === PB_REPEATED_MARKER, isRepeated: parsed.marker === PB_REPEATED_MARKER,
}; };
// If the field's type-arg is itself a generic instantiation (`Wrapper<U>`, // If the field's type-arg is itself a generic instantiation (`Wrapper<U>`,
// where U is a type param of the enclosing template), capture the original // where U is a type param of the enclosing template), capture the original
// source text so monomorphization can substitute U and re-instantiate the // source text so monomorphization can substitute U and re-instantiate the
// inner generic. Without this the field's `rawTypeName` would stay at the // inner generic. Without this the field's `rawTypeName` would stay at the
// unsubstituted `'Wrapper__U'` form and the substituted instantiation // unsubstituted `'Wrapper__U'` form and the substituted instantiation
// would never reach the registry. // would never reach the registry.
const ta = parsed.typeArgNode; const ta = parsed.typeArgNode;
if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) { if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) {
result.genericTypeArgText = ta.getText(sf); result.genericTypeArgText = ta.getText(sf);
result.genericTypeArgSourceFilePath = sf.fileName; result.genericTypeArgSourceFilePath = sf.fileName;
} }
return result; return result;
} }
File diff suppressed because it is too large. Load diff
+95 -95
View File
@@ -1,15 +1,15 @@
import ts from 'typescript'; import ts from 'typescript';
import { WireType, type ProtobufField, type ProtobufMessage, type GenericProtobufTemplate } from './types.js'; import { WireType, type ProtobufField, type ProtobufMessage, type GenericProtobufTemplate } from './types.js';
import { import {
isKeywordTypeNode, isKeywordTypeNode,
createImportedTypeNameResolver, createImportedTypeNameResolver,
resolveSourceFileForTypeNode, resolveSourceFileForTypeNode,
type ImportedTypeNameResolver, type ImportedTypeNameResolver,
typeNodeToMangledName, typeNodeToMangledName,
} from './utils.js'; } from './utils.js';
function identityImportedTypeName(name: string): string { function identityImportedTypeName(name: string): string {
return name; return name;
} }
/** Resolved value for a single template type parameter. */ /** Resolved value for a single template type parameter. */
@@ -28,104 +28,104 @@ interface ResolvedTypeArg {
* Returns the mangled name of the concrete type, or null if it cannot be resolved. * Returns the mangled name of the concrete type, or null if it cannot be resolved.
*/ */
export function monomorphizeTypeNode( export function monomorphizeTypeNode(
typeNode: ts.TypeNode, typeNode: ts.TypeNode,
sf: ts.SourceFile, sf: ts.SourceFile,
templates: Map<string, GenericProtobufTemplate>, templates: Map<string, GenericProtobufTemplate>,
out: Map<string, ProtobufMessage>, out: Map<string, ProtobufMessage>,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): string | null { ): string | null {
if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return null; if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return null;
const baseName = resolveImportedTypeName(typeNode.typeName.text); const baseName = resolveImportedTypeName(typeNode.typeName.text);
const typeArgs = typeNode.typeArguments; const typeArgs = typeNode.typeArguments;
if (!typeArgs || typeArgs.length === 0) return baseName; // already concrete if (!typeArgs || typeArgs.length === 0) return baseName; // already concrete
const tpl = templates.get(baseName); const tpl = templates.get(baseName);
if (!tpl || typeArgs.length !== tpl.typeParams.length) return null; if (!tpl || typeArgs.length !== tpl.typeParams.length) return null;
const mangledName = typeNodeToMangledName(typeNode, sf, resolveImportedTypeName); const mangledName = typeNodeToMangledName(typeNode, sf, resolveImportedTypeName);
if (out.has(mangledName)) return mangledName; // already done if (out.has(mangledName)) return mangledName; // already done
// Resolve each type parameter → both mangled name AND source text. // Resolve each type parameter → both mangled name AND source text.
const paramMap = new Map<string, ResolvedTypeArg>(); const paramMap = new Map<string, ResolvedTypeArg>();
for (let i = 0; i < tpl.typeParams.length; i++) { for (let i = 0; i < tpl.typeParams.length; i++) {
const resolved = resolveTypeArg(typeArgs[i], sf, templates, out, resolveImportedTypeName); const resolved = resolveTypeArg(typeArgs[i], sf, templates, out, resolveImportedTypeName);
if (!resolved) return null; if (!resolved) return null;
paramMap.set(tpl.typeParams[i], resolved); paramMap.set(tpl.typeParams[i], resolved);
}
// Substitute type params in template fields.
const fields: ProtobufField[] = tpl.fields.map(f => {
if (f.genericTypeArgText) {
// Field type is an inner generic instantiation referencing template
// type params (e.g. `pb<N, Wrapper<U>>`). Substitute the params into
// the captured text, re-parse, and re-monomorphize so the resulting
// concrete instantiation (`Wrapper<uint_32>`) lands in `out`.
let substituted = f.genericTypeArgText;
for (const [paramName, value] of paramMap) {
substituted = substituted.replace(
new RegExp(`\\b${paramName}\\b`, 'g'),
value.text,
);
}
const innerSfPath = f.genericTypeArgSourceFilePath ?? sf.fileName;
const innerSf = ts.createSourceFile(
innerSfPath,
`type __X = ${substituted};`,
ts.ScriptTarget.Latest,
true,
);
const stmt = innerSf.statements[0];
let resolvedTypeName: string | null = null;
if (ts.isTypeAliasDeclaration(stmt)) {
const innerResolver = createImportedTypeNameResolver(innerSf);
resolvedTypeName = monomorphizeTypeNode(stmt.type, innerSf, templates, out, innerResolver);
}
return {
name: f.name,
fieldNumber: f.fieldNumber,
typeName: resolvedTypeName ?? f.rawTypeName,
wireType: WireType.Varint,
isMessage: false,
isOptional: f.isOptional,
isRepeated: f.isRepeated,
};
} }
return {
name: f.name,
fieldNumber: f.fieldNumber,
typeName: f.isTypeParam ? (paramMap.get(f.rawTypeName)?.mangled ?? f.rawTypeName) : f.rawTypeName,
wireType: WireType.Varint,
isMessage: false,
isOptional: f.isOptional,
isRepeated: f.isRepeated,
};
});
// Substitute type params in template fields. out.set(mangledName, { name: mangledName, fields });
const fields: ProtobufField[] = tpl.fields.map(f => { return mangledName;
if (f.genericTypeArgText) {
// Field type is an inner generic instantiation referencing template
// type params (e.g. `pb<N, Wrapper<U>>`). Substitute the params into
// the captured text, re-parse, and re-monomorphize so the resulting
// concrete instantiation (`Wrapper<uint_32>`) lands in `out`.
let substituted = f.genericTypeArgText;
for (const [paramName, value] of paramMap) {
substituted = substituted.replace(
new RegExp(`\\b${paramName}\\b`, 'g'),
value.text,
);
}
const innerSfPath = f.genericTypeArgSourceFilePath ?? sf.fileName;
const innerSf = ts.createSourceFile(
innerSfPath,
`type __X = ${substituted};`,
ts.ScriptTarget.Latest,
true,
);
const stmt = innerSf.statements[0];
let resolvedTypeName: string | null = null;
if (ts.isTypeAliasDeclaration(stmt)) {
const innerResolver = createImportedTypeNameResolver(innerSf);
resolvedTypeName = monomorphizeTypeNode(stmt.type, innerSf, templates, out, innerResolver);
}
return {
name: f.name,
fieldNumber: f.fieldNumber,
typeName: resolvedTypeName ?? f.rawTypeName,
wireType: WireType.Varint,
isMessage: false,
isOptional: f.isOptional,
isRepeated: f.isRepeated,
};
}
return {
name: f.name,
fieldNumber: f.fieldNumber,
typeName: f.isTypeParam ? (paramMap.get(f.rawTypeName)?.mangled ?? f.rawTypeName) : f.rawTypeName,
wireType: WireType.Varint,
isMessage: false,
isOptional: f.isOptional,
isRepeated: f.isRepeated,
};
});
out.set(mangledName, { name: mangledName, fields });
return mangledName;
} }
function resolveTypeArg( function resolveTypeArg(
node: ts.TypeNode, node: ts.TypeNode,
sf: ts.SourceFile, sf: ts.SourceFile,
templates: Map<string, GenericProtobufTemplate>, templates: Map<string, GenericProtobufTemplate>,
out: Map<string, ProtobufMessage>, out: Map<string, ProtobufMessage>,
resolveImportedTypeName: ImportedTypeNameResolver, resolveImportedTypeName: ImportedTypeNameResolver,
): ResolvedTypeArg | null { ): ResolvedTypeArg | null {
const effectiveSf = resolveSourceFileForTypeNode(node, sf); const effectiveSf = resolveSourceFileForTypeNode(node, sf);
// Try recursive monomorphization first (handles nested generics). // Try recursive monomorphization first (handles nested generics).
const mono = monomorphizeTypeNode(node, effectiveSf, templates, out, resolveImportedTypeName); const mono = monomorphizeTypeNode(node, effectiveSf, templates, out, resolveImportedTypeName);
if (mono) return { mangled: mono, text: node.getText(effectiveSf) }; if (mono) return { mangled: mono, text: node.getText(effectiveSf) };
// Keyword type (string, number, …) // Keyword type (string, number, …)
if (isKeywordTypeNode(node)) { if (isKeywordTypeNode(node)) {
const text = node.getText(effectiveSf); const text = node.getText(effectiveSf);
return { mangled: text, text }; return { mangled: text, text };
} }
// Simple identifier (uint_32, SomeMsg, …) // Simple identifier (uint_32, SomeMsg, …)
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !node.typeArguments) { if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !node.typeArguments) {
const name = resolveImportedTypeName(node.typeName.text); const name = resolveImportedTypeName(node.typeName.text);
return { mangled: name, text: name }; return { mangled: name, text: name };
} }
return null; return null;
} }
+38 -38
View File
@@ -3,7 +3,7 @@ import ts from 'typescript';
export type ImportedTypeNameResolver = (name: string) => string; export type ImportedTypeNameResolver = (name: string) => string;
function identityImportedTypeName(name: string): string { function identityImportedTypeName(name: string): string {
return name; return name;
} }
// Synthetic type-arg nodes (produced by wrapper-binding instantiation) live in // Synthetic type-arg nodes (produced by wrapper-binding instantiation) live in
@@ -13,47 +13,47 @@ function identityImportedTypeName(name: string): string {
const syntheticTypeSourceFiles = new WeakMap<ts.TypeNode, ts.SourceFile>(); const syntheticTypeSourceFiles = new WeakMap<ts.TypeNode, ts.SourceFile>();
export function registerSyntheticTypeSourceFile(node: ts.TypeNode, sf: ts.SourceFile): void { export function registerSyntheticTypeSourceFile(node: ts.TypeNode, sf: ts.SourceFile): void {
syntheticTypeSourceFiles.set(node, sf); syntheticTypeSourceFiles.set(node, sf);
} }
export function resolveSourceFileForTypeNode(node: ts.TypeNode, fallback: ts.SourceFile): ts.SourceFile { export function resolveSourceFileForTypeNode(node: ts.TypeNode, fallback: ts.SourceFile): ts.SourceFile {
return syntheticTypeSourceFiles.get(node) ?? fallback; return syntheticTypeSourceFiles.get(node) ?? fallback;
} }
// TS 5.9+ removed ts.isKeywordTypeNode — manual kind-based check // TS 5.9+ removed ts.isKeywordTypeNode — manual kind-based check
const KEYWORD_TYPE_KINDS = new Set([ const KEYWORD_TYPE_KINDS = new Set([
ts.SyntaxKind.StringKeyword, ts.SyntaxKind.StringKeyword,
ts.SyntaxKind.NumberKeyword, ts.SyntaxKind.NumberKeyword,
ts.SyntaxKind.BooleanKeyword, ts.SyntaxKind.BooleanKeyword,
ts.SyntaxKind.AnyKeyword, ts.SyntaxKind.AnyKeyword,
ts.SyntaxKind.VoidKeyword, ts.SyntaxKind.VoidKeyword,
ts.SyntaxKind.UndefinedKeyword, ts.SyntaxKind.UndefinedKeyword,
ts.SyntaxKind.NullKeyword, ts.SyntaxKind.NullKeyword,
ts.SyntaxKind.NeverKeyword, ts.SyntaxKind.NeverKeyword,
ts.SyntaxKind.UnknownKeyword, ts.SyntaxKind.UnknownKeyword,
ts.SyntaxKind.BigIntKeyword, ts.SyntaxKind.BigIntKeyword,
ts.SyntaxKind.SymbolKeyword, ts.SyntaxKind.SymbolKeyword,
ts.SyntaxKind.ObjectKeyword, ts.SyntaxKind.ObjectKeyword,
]); ]);
export function isKeywordTypeNode(node: ts.Node): boolean { export function isKeywordTypeNode(node: ts.Node): boolean {
return KEYWORD_TYPE_KINDS.has(node.kind); return KEYWORD_TYPE_KINDS.has(node.kind);
} }
export function createImportedTypeNameResolver(sf: ts.SourceFile): ImportedTypeNameResolver { export function createImportedTypeNameResolver(sf: ts.SourceFile): ImportedTypeNameResolver {
const localToImported = new Map<string, string>(); const localToImported = new Map<string, string>();
for (const stmt of sf.statements) { for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue; if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue;
const bindings = stmt.importClause.namedBindings; const bindings = stmt.importClause.namedBindings;
if (!bindings || !ts.isNamedImports(bindings)) continue; if (!bindings || !ts.isNamedImports(bindings)) continue;
for (const el of bindings.elements) { for (const el of bindings.elements) {
localToImported.set(el.name.text, (el.propertyName ?? el.name).text); localToImported.set(el.name.text, (el.propertyName ?? el.name).text);
}
} }
}
return (name: string) => localToImported.get(name) ?? name; return (name: string) => localToImported.get(name) ?? name;
} }
/** /**
@@ -67,19 +67,19 @@ export function createImportedTypeNameResolver(sf: ts.SourceFile): ImportedTypeN
* the substituted type text rather than garbage from `sf`. * the substituted type text rather than garbage from `sf`.
*/ */
export function typeNodeToMangledName( export function typeNodeToMangledName(
typeNode: ts.TypeNode, typeNode: ts.TypeNode,
sf: ts.SourceFile, sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): string { ): string {
const effectiveSf = resolveSourceFileForTypeNode(typeNode, sf); const effectiveSf = resolveSourceFileForTypeNode(typeNode, sf);
if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) { if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {
const base = resolveImportedTypeName(typeNode.typeName.text); const base = resolveImportedTypeName(typeNode.typeName.text);
if (typeNode.typeArguments && typeNode.typeArguments.length > 0) { if (typeNode.typeArguments && typeNode.typeArguments.length > 0) {
const args = typeNode.typeArguments.map(a => typeNodeToMangledName(a, effectiveSf, resolveImportedTypeName)); const args = typeNode.typeArguments.map(a => typeNodeToMangledName(a, effectiveSf, resolveImportedTypeName));
return base + '__' + args.join('__'); return base + '__' + args.join('__');
}
return base;
} }
if (isKeywordTypeNode(typeNode)) return typeNode.getText(effectiveSf); return base;
return typeNode.getText(effectiveSf); }
if (isKeywordTypeNode(typeNode)) return typeNode.getText(effectiveSf);
return typeNode.getText(effectiveSf);
} }
+118 -118
View File
@@ -1,154 +1,154 @@
import { WireType, PRIMITIVE_TYPE_MAP, type ProtobufField, type ProtobufMessage, type MessageRegistry } from '../ast/types.js'; import { WireType, PRIMITIVE_TYPE_MAP, type ProtobufField, type ProtobufMessage, type MessageRegistry } from '../ast/types.js';
function tagValue(field: ProtobufField): number { function tagValue(field: ProtobufField): number {
const wireType = field.isMessage || field.typeName === 'string' || field.typeName === 'bytes' const wireType = field.isMessage || field.typeName === 'string' || field.typeName === 'bytes'
? WireType.LengthDelim ? WireType.LengthDelim
: field.wireType; : field.wireType;
return ((field.fieldNumber << 3) | wireType) >>> 0; return ((field.fieldNumber << 3) | wireType) >>> 0;
} }
/** Emit inline varint decode, storing result in `varName`. */ /** Emit inline varint decode, storing result in `varName`. */
function varintDec(varName: string, ind: string): string { function varintDec(varName: string, ind: string): string {
return [ return [
`${ind}let ${varName} = data[offset++];`, `${ind}let ${varName} = data[offset++];`,
`${ind}if (${varName} & 0x80) {`, `${ind}if (${varName} & 0x80) {`,
`${ind} let _s = 7, _b;`, `${ind} let _s = 7, _b;`,
`${ind} ${varName} &= 0x7f;`, `${ind} ${varName} &= 0x7f;`,
`${ind} do { _b = data[offset++]; ${varName} |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80);`, `${ind} do { _b = data[offset++]; ${varName} |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80);`,
`${ind}}`, `${ind}}`,
].join('\n'); ].join('\n');
} }
function varintDec64(varName: string, ind: string): string { function varintDec64(varName: string, ind: string): string {
return [ return [
`${ind}let ${varName} = 0n, _s = 0n, _b;`, `${ind}let ${varName} = 0n, _s = 0n, _b;`,
`${ind}do { _b = data[offset++]; ${varName} |= BigInt(_b & 0x7f) << _s; _s += 7n; } while (_b & 0x80);`, `${ind}do { _b = data[offset++]; ${varName} |= BigInt(_b & 0x7f) << _s; _s += 7n; } while (_b & 0x80);`,
].join('\n'); ].join('\n');
} }
function isVarint64(typeName: string): boolean { function isVarint64(typeName: string): boolean {
return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64'; return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64';
} }
function isFixed64BigInt(typeName: string): boolean { function isFixed64BigInt(typeName: string): boolean {
return typeName === 'fixed_64' || typeName === 'sfixed_64'; return typeName === 'fixed_64' || typeName === 'sfixed_64';
} }
const INLINE_SKIP = [ const INLINE_SKIP = [
` const wireType = _tag & 0x7;`, ` const wireType = _tag & 0x7;`,
` if (wireType === 0) { while (data[offset] & 0x80) offset++; offset++; }`, ` if (wireType === 0) { while (data[offset] & 0x80) offset++; offset++; }`,
` else if (wireType === 1) offset += 8;`, ` else if (wireType === 1) offset += 8;`,
` else if (wireType === 2) { let _l = data[offset++]; if (_l & 0x80) { let _s = 7, _b; _l &= 0x7f; do { _b = data[offset++]; _l |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80); } offset += _l; }`, ` else if (wireType === 2) { let _l = data[offset++]; if (_l & 0x80) { let _s = 7, _b; _l &= 0x7f; do { _b = data[offset++]; _l |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80); } offset += _l; }`,
` else if (wireType === 5) offset += 4;`, ` else if (wireType === 5) offset += 4;`,
].join('\n'); ].join('\n');
export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry): string { export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry): string {
const locals = msg.fields.map((field, index) => { const locals = msg.fields.map((field, index) => {
const keyword = field.isRepeated ? 'const' : 'let'; const keyword = field.isRepeated ? 'const' : 'let';
return ` ${keyword} _f${index} = ${getDefault(field)};`; return ` ${keyword} _f${index} = ${getDefault(field)};`;
}); });
const result = msg.fields.map((field, index) => `${field.name}: _f${index}`).join(', '); const result = msg.fields.map((field, index) => `${field.name}: _f${index}`).join(', ');
const L = [ const L = [
`function protobuf_decode_${msg.name}(data, offset = 0, end = data.length) {`, `function protobuf_decode_${msg.name}(data, offset = 0, end = data.length) {`,
...locals, ...locals,
` while (offset < end) {`, ` while (offset < end) {`,
` let _tag = data[offset++];`, ` let _tag = data[offset++];`,
` if (_tag & 0x80) {`, ` if (_tag & 0x80) {`,
` let _ts = 7, _tb;`, ` let _ts = 7, _tb;`,
` _tag &= 0x7f;`, ` _tag &= 0x7f;`,
` do { _tb = data[offset++]; _tag |= (_tb & 0x7f) << _ts; _ts += 7; } while (_tb & 0x80);`, ` do { _tb = data[offset++]; _tag |= (_tb & 0x7f) << _ts; _ts += 7; } while (_tb & 0x80);`,
` }`, ` }`,
` switch (_tag) {`, ` switch (_tag) {`,
]; ];
msg.fields.forEach((field, index) => { msg.fields.forEach((field, index) => {
L.push(decodeField(field, index)); L.push(decodeField(field, index));
}); });
L.push( L.push(
` default: {`, ` default: {`,
INLINE_SKIP, INLINE_SKIP,
` break;`, ` break;`,
` }`, ` }`,
` }`, ` }`,
` }`, ` }`,
` return { ${result} };`, ` return { ${result} };`,
`}`, `}`,
); );
return L.join('\n'); return L.join('\n');
} }
function decodeField(field: ProtobufField, index: number): string { function decodeField(field: ProtobufField, index: number): string {
const { typeName, wireType, isMessage, isRepeated } = field; const { typeName, wireType, isMessage, isRepeated } = field;
const I = ' '; const I = ' ';
const local = `_f${index}`; const local = `_f${index}`;
const assign = (expr: string) => isRepeated const assign = (expr: string) => isRepeated
? `${I}${local}.push(${expr});` ? `${I}${local}.push(${expr});`
: `${I}${local} = ${expr};`; : `${I}${local} = ${expr};`;
const L: string[] = [` case ${tagValue(field)}: {`]; const L: string[] = [` case ${tagValue(field)}: {`];
if (isMessage) { if (isMessage) {
L.push(varintDec('_len', I)); L.push(varintDec('_len', I));
L.push(assign(`protobuf_decode_${typeName}(data, offset, offset + _len)`)); L.push(assign(`protobuf_decode_${typeName}(data, offset, offset + _len)`));
L.push(`${I}offset += _len;`); L.push(`${I}offset += _len;`);
} else if (typeName === 'string') { } else if (typeName === 'string') {
L.push(varintDec('_len', I)); L.push(varintDec('_len', I));
L.push(`${I}const _end = offset + _len;`); L.push(`${I}const _end = offset + _len;`);
L.push(assign(`__td.decode(data.subarray(offset, _end))`)); L.push(assign(`__td.decode(data.subarray(offset, _end))`));
L.push(`${I}offset = _end;`); L.push(`${I}offset = _end;`);
} else if (typeName === 'bytes') { } else if (typeName === 'bytes') {
L.push(varintDec('_len', I)); L.push(varintDec('_len', I));
L.push(`${I}const _end = offset + _len;`); L.push(`${I}const _end = offset + _len;`);
L.push(assign(`data.slice(offset, _end)`)); L.push(assign(`data.slice(offset, _end)`));
L.push(`${I}offset = _end;`); L.push(`${I}offset = _end;`);
} else if (typeName === 'bool') { } else if (typeName === 'bool') {
L.push(varintDec('_val', I)); L.push(varintDec('_val', I));
L.push(assign(`_val !== 0`)); L.push(assign(`_val !== 0`));
} else if (isVarint64(typeName)) { } else if (isVarint64(typeName)) {
L.push(varintDec64('_val', I)); L.push(varintDec64('_val', I));
if (typeName === 'uint_64') { if (typeName === 'uint_64') {
L.push(assign(`_val`)); L.push(assign(`_val`));
} else if (typeName === 'int_64') { } else if (typeName === 'int_64') {
L.push(assign(`BigInt.asIntN(64, _val)`)); L.push(assign(`BigInt.asIntN(64, _val)`));
} else { } else {
L.push(assign(`__zigZagDecode64(_val)`)); L.push(assign(`__zigZagDecode64(_val)`));
}
} else if (typeName === 'sint_32') {
L.push(varintDec('_val', I));
L.push(assign(`(_val >>> 1) ^ -(_val & 1)`));
} else if (wireType === WireType.Varint) {
L.push(varintDec('_val', I));
L.push(assign(`_val >>> 0`));
} else if (typeName === 'float') {
L.push(assign(`__readFloat32(data, offset)`));
L.push(`${I}offset += 4;`);
} else if (wireType === WireType.Bit32) {
L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`));
L.push(`${I}offset += 4;`);
} else if (typeName === 'double') {
L.push(assign(`__readFloat64(data, offset)`));
L.push(`${I}offset += 8;`);
} else if (isFixed64BigInt(typeName)) {
if (typeName === 'fixed_64') {
L.push(assign(`__readFixed64(data, offset)`));
} else {
L.push(assign(`BigInt.asIntN(64, __readFixed64(data, offset))`));
}
L.push(`${I}offset += 8;`);
} else if (wireType === WireType.Bit64) {
L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`));
L.push(`${I}offset += 8;`);
} }
} else if (typeName === 'sint_32') {
L.push(varintDec('_val', I));
L.push(assign(`(_val >>> 1) ^ -(_val & 1)`));
} else if (wireType === WireType.Varint) {
L.push(varintDec('_val', I));
L.push(assign(`_val >>> 0`));
} else if (typeName === 'float') {
L.push(assign(`__readFloat32(data, offset)`));
L.push(`${I}offset += 4;`);
} else if (wireType === WireType.Bit32) {
L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`));
L.push(`${I}offset += 4;`);
} else if (typeName === 'double') {
L.push(assign(`__readFloat64(data, offset)`));
L.push(`${I}offset += 8;`);
} else if (isFixed64BigInt(typeName)) {
if (typeName === 'fixed_64') {
L.push(assign(`__readFixed64(data, offset)`));
} else {
L.push(assign(`BigInt.asIntN(64, __readFixed64(data, offset))`));
}
L.push(`${I}offset += 8;`);
} else if (wireType === WireType.Bit64) {
L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`));
L.push(`${I}offset += 8;`);
}
L.push(`${I}break;`, ` }`); L.push(`${I}break;`, ` }`);
return L.join('\n'); return L.join('\n');
} }
function getDefault(field: ProtobufField): string { function getDefault(field: ProtobufField): string {
if (field.isRepeated) return '[]'; if (field.isRepeated) return '[]';
if (field.isOptional || field.isMessage) return 'null'; if (field.isOptional || field.isMessage) return 'null';
const primitive = PRIMITIVE_TYPE_MAP[field.typeName]; const primitive = PRIMITIVE_TYPE_MAP[field.typeName];
return primitive ? primitive.defaultValue : 'null'; return primitive ? primitive.defaultValue : 'null';
} }
File diff suppressed because it is too large. Load diff
+115 -115
View File
@@ -8,11 +8,11 @@ import type { MessageRegistry } from './ast/types.js';
import { buildDependencyRegistry } from './ast/dependency-graph.js'; import { buildDependencyRegistry } from './ast/dependency-graph.js';
import { generateCode } from './codegen/generator.js'; import { generateCode } from './codegen/generator.js';
import { import {
normalizeRuntimeMapPath, normalizeRuntimeMapPath,
runtimeMapToRegistry, runtimeMapToRegistry,
type ProtobufRuntimeMap, type ProtobufRuntimeMap,
type RuntimeMapCallSite, type RuntimeMapCallSite,
type RuntimeMapFnName, type RuntimeMapFnName,
} from './runtime-map.js'; } from './runtime-map.js';
type DynamicEncode = (params: unknown) => Uint8Array; type DynamicEncode = (params: unknown) => Uint8Array;
@@ -41,180 +41,180 @@ const dynamicTypeCache = new Map<string, DynamicTypeFns>();
* This is disabled by default. * This is disabled by default.
*/ */
export function protobuf_enableRuntimeMapFallback(map: ProtobufRuntimeMap): void { export function protobuf_enableRuntimeMapFallback(map: ProtobufRuntimeMap): void {
runtimeMapFallback = map; runtimeMapFallback = map;
runtimeMapRegistry = runtimeMapToRegistry(map); runtimeMapRegistry = runtimeMapToRegistry(map);
runtimeMapCallSites = map.callSites.map(cs => ({ runtimeMapCallSites = map.callSites.map(cs => ({
...cs, ...cs,
file: normalizeRuntimeMapPath(cs.file), file: normalizeRuntimeMapPath(cs.file),
})); }));
dynamicTypeCache.clear(); dynamicTypeCache.clear();
} }
/** Disable dynamic runtime fallback and clear all generated function caches. */ /** Disable dynamic runtime fallback and clear all generated function caches. */
export function protobuf_disableRuntimeMapFallback(): void { export function protobuf_disableRuntimeMapFallback(): void {
runtimeMapFallback = null; runtimeMapFallback = null;
runtimeMapRegistry = null; runtimeMapRegistry = null;
runtimeMapCallSites = []; runtimeMapCallSites = [];
dynamicTypeCache.clear(); dynamicTypeCache.clear();
} }
export function protobuf_encode<T>(_params: T): Uint8Array { export function protobuf_encode<T>(_params: T): Uint8Array {
const dynamic = tryDynamicInvoke('protobuf_encode', _params); const dynamic = tryDynamicInvoke('protobuf_encode', _params);
if (dynamic !== DYNAMIC_MISS) return dynamic as Uint8Array; if (dynamic !== DYNAMIC_MISS) return dynamic as Uint8Array;
throw new Error( throw new Error(
'protobuf_encode<T>() was not transformed by the @snowluma/proton Vite plugin. ' + 'protobuf_encode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.', 'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.',
); );
} }
export function protobuf_decode<T>(_data: Uint8Array): T { export function protobuf_decode<T>(_data: Uint8Array): T {
const dynamic = tryDynamicInvoke('protobuf_decode', _data); const dynamic = tryDynamicInvoke('protobuf_decode', _data);
if (dynamic !== DYNAMIC_MISS) return dynamic as T; if (dynamic !== DYNAMIC_MISS) return dynamic as T;
throw new Error( throw new Error(
'protobuf_decode<T>() was not transformed by the @snowluma/proton Vite plugin. ' + 'protobuf_decode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.', 'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.',
); );
} }
function tryDynamicInvoke(fnName: RuntimeMapFnName, payload: unknown): unknown { function tryDynamicInvoke(fnName: RuntimeMapFnName, payload: unknown): unknown {
if (!runtimeMapFallback || runtimeMapFallback.version !== 1 || !runtimeMapRegistry) { if (!runtimeMapFallback || runtimeMapFallback.version !== 1 || !runtimeMapRegistry) {
return DYNAMIC_MISS; return DYNAMIC_MISS;
} }
const caller = getFirstUserFrame(); const caller = getFirstUserFrame();
if (!caller) return DYNAMIC_MISS; if (!caller) return DYNAMIC_MISS;
const callSite = resolveCallSite(fnName, caller); const callSite = resolveCallSite(fnName, caller);
if (!callSite) return DYNAMIC_MISS; if (!callSite) return DYNAMIC_MISS;
const typeFns = ensureTypeFunctions(callSite.typeName); const typeFns = ensureTypeFunctions(callSite.typeName);
if (!typeFns) return DYNAMIC_MISS; if (!typeFns) return DYNAMIC_MISS;
const fn = fnName === 'protobuf_encode' ? typeFns.encode : typeFns.decode; const fn = fnName === 'protobuf_encode' ? typeFns.encode : typeFns.decode;
if (typeof fn !== 'function') return DYNAMIC_MISS; if (typeof fn !== 'function') return DYNAMIC_MISS;
return fn(payload as never); return fn(payload as never);
} }
function ensureTypeFunctions(typeName: string): DynamicTypeFns | null { function ensureTypeFunctions(typeName: string): DynamicTypeFns | null {
const cached = dynamicTypeCache.get(typeName); const cached = dynamicTypeCache.get(typeName);
if (cached) return cached; if (cached) return cached;
if (!runtimeMapRegistry || !runtimeMapRegistry.has(typeName)) return null; if (!runtimeMapRegistry || !runtimeMapRegistry.has(typeName)) return null;
const subset = buildDependencyRegistry(runtimeMapRegistry, [typeName]); const subset = buildDependencyRegistry(runtimeMapRegistry, [typeName]);
if (subset.size === 0) return null; if (subset.size === 0) return null;
const generated = generateCode(subset); const generated = generateCode(subset);
if (!generated) return null; if (!generated) return null;
const factory = new Function( const factory = new Function(
`${generated}\nreturn {\n` + `${generated}\nreturn {\n` +
` encode: typeof protobuf_encode_${typeName} === 'function' ? protobuf_encode_${typeName} : undefined,\n` + ` encode: typeof protobuf_encode_${typeName} === 'function' ? protobuf_encode_${typeName} : undefined,\n` +
` decode: typeof protobuf_decode_${typeName} === 'function' ? protobuf_decode_${typeName} : undefined,\n` + ` decode: typeof protobuf_decode_${typeName} === 'function' ? protobuf_decode_${typeName} : undefined,\n` +
`};`, `};`,
) as () => DynamicTypeFns; ) as () => DynamicTypeFns;
const compiled = factory(); const compiled = factory();
dynamicTypeCache.set(typeName, compiled); dynamicTypeCache.set(typeName, compiled);
return compiled; return compiled;
} }
function resolveCallSite(fnName: RuntimeMapFnName, caller: StackFrame): RuntimeMapCallSite | null { function resolveCallSite(fnName: RuntimeMapFnName, caller: StackFrame): RuntimeMapCallSite | null {
const callerFile = normalizeRuntimeMapPath(caller.file); const callerFile = normalizeRuntimeMapPath(caller.file);
const candidates = runtimeMapCallSites.filter(cs => const candidates = runtimeMapCallSites.filter(cs =>
cs.fnName === fnName && cs.fnName === fnName &&
cs.line === caller.line && cs.line === caller.line &&
pathsLikelySame(callerFile, cs.file), pathsLikelySame(callerFile, cs.file),
); );
if (candidates.length === 0) return null; if (candidates.length === 0) return null;
if (candidates.length === 1) return candidates[0]; if (candidates.length === 1) return candidates[0];
let best = candidates[0]; let best = candidates[0];
let bestDistance = Math.abs(best.column - caller.column); let bestDistance = Math.abs(best.column - caller.column);
for (let i = 1; i < candidates.length; i++) { for (let i = 1; i < candidates.length; i++) {
const dist = Math.abs(candidates[i].column - caller.column); const dist = Math.abs(candidates[i].column - caller.column);
if (dist < bestDistance) { if (dist < bestDistance) {
best = candidates[i]; best = candidates[i];
bestDistance = dist; bestDistance = dist;
}
} }
return best; }
return best;
} }
function getFirstUserFrame(): StackFrame | null { function getFirstUserFrame(): StackFrame | null {
const err = new Error(); const err = new Error();
if (!err.stack) return null; if (!err.stack) return null;
const lines = err.stack.split('\n').slice(1); const lines = err.stack.split('\n').slice(1);
for (const raw of lines) { for (const raw of lines) {
const frame = parseStackLine(raw); const frame = parseStackLine(raw);
if (!frame) continue; if (!frame) continue;
const file = normalizeRuntimeMapPath(frame.file); const file = normalizeRuntimeMapPath(frame.file);
if (isRuntimeInternalFile(file)) continue; if (isRuntimeInternalFile(file)) continue;
return { return {
file, file,
line: frame.line, line: frame.line,
column: frame.column, column: frame.column,
}; };
} }
return null; return null;
} }
function parseStackLine(line: string): StackFrame | null { function parseStackLine(line: string): StackFrame | null {
const trimmed = line.trim(); const trimmed = line.trim();
if (!trimmed) return null; if (!trimmed) return null;
let location = trimmed; let location = trimmed;
const atPrefix = 'at '; const atPrefix = 'at ';
if (location.startsWith(atPrefix)) { if (location.startsWith(atPrefix)) {
location = location.slice(atPrefix.length).trim(); location = location.slice(atPrefix.length).trim();
} }
const openParen = location.lastIndexOf('('); const openParen = location.lastIndexOf('(');
if (openParen >= 0 && location.endsWith(')')) { if (openParen >= 0 && location.endsWith(')')) {
location = location.slice(openParen + 1, -1); location = location.slice(openParen + 1, -1);
} }
const lastColon = location.lastIndexOf(':'); const lastColon = location.lastIndexOf(':');
if (lastColon < 0) return null; if (lastColon < 0) return null;
const secondLastColon = location.lastIndexOf(':', lastColon - 1); const secondLastColon = location.lastIndexOf(':', lastColon - 1);
if (secondLastColon < 0) return null; if (secondLastColon < 0) return null;
const file = location.slice(0, secondLastColon); const file = location.slice(0, secondLastColon);
const linePart = location.slice(secondLastColon + 1, lastColon); const linePart = location.slice(secondLastColon + 1, lastColon);
const colPart = location.slice(lastColon + 1); const colPart = location.slice(lastColon + 1);
const parsedLine = Number(linePart); const parsedLine = Number(linePart);
const parsedCol = Number(colPart); const parsedCol = Number(colPart);
if (!Number.isFinite(parsedLine) || !Number.isFinite(parsedCol)) return null; if (!Number.isFinite(parsedLine) || !Number.isFinite(parsedCol)) return null;
return { return {
file, file,
line: parsedLine, line: parsedLine,
column: parsedCol, column: parsedCol,
}; };
} }
function isRuntimeInternalFile(file: string): boolean { function isRuntimeInternalFile(file: string): boolean {
return file.endsWith('/runtime.ts') || file.endsWith('/runtime.js') || file.includes('/dist/runtime.js'); return file.endsWith('/runtime.ts') || file.endsWith('/runtime.js') || file.includes('/dist/runtime.js');
} }
function pathsLikelySame(a: string, b: string): boolean { function pathsLikelySame(a: string, b: string): boolean {
if (a === b) return true; if (a === b) return true;
const aBase = basename(a); const aBase = basename(a);
const bBase = basename(b); const bBase = basename(b);
return aBase !== '' && aBase === bBase; return aBase !== '' && aBase === bBase;
} }
function basename(file: string): string { function basename(file: string): string {
const normalized = normalizeRuntimeMapPath(file); const normalized = normalizeRuntimeMapPath(file);
const idx = normalized.lastIndexOf('/'); const idx = normalized.lastIndexOf('/');
return idx >= 0 ? normalized.slice(idx + 1) : normalized; return idx >= 0 ? normalized.slice(idx + 1) : normalized;
} }
+236 -236
View File
@@ -11,332 +11,332 @@ import { execAndGet } from '../helpers';
const crossDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fixtures', 'cross-file'); const crossDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fixtures', 'cross-file');
function loadCross(name: string): { code: string; path: string } { function loadCross(name: string): { code: string; path: string } {
const path = resolve(crossDir, name); const path = resolve(crossDir, name);
return { code: readFileSync(path, 'utf-8'), path }; return { code: readFileSync(path, 'utf-8'), path };
} }
describe('cross-file import resolution', () => { describe('cross-file import resolution', () => {
// ── Scenario A: imported type in encode/decode call site ────────── // ── Scenario A: imported type in encode/decode call site ──────────
it('resolves imported type for protobuf_encode/decode call site', () => { it('resolves imported type for protobuf_encode/decode call site', () => {
const { code, path } = loadCross('consumer.ts'); const { code, path } = loadCross('consumer.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
expect(imported.concrete.some(m => m.name === 'UserMsg')).toBe(true); expect(imported.concrete.some(m => m.name === 'UserMsg')).toBe(true);
const { registry, callSites, sourceFile } = analyze(code, path, imported); const { registry, callSites, sourceFile } = analyze(code, path, imported);
expect(registry.has('UserMsg')).toBe(true); expect(registry.has('UserMsg')).toBe(true);
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry); const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry);
expect(hasReplacements).toBe(true); expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_UserMsg'); expect(transformedCode).toContain('protobuf_encode_UserMsg');
expect(transformedCode).toContain('protobuf_decode_UserMsg'); expect(transformedCode).toContain('protobuf_decode_UserMsg');
}); });
it('Scenario A round-trip', () => { it('Scenario A round-trip', () => {
const { code, path } = loadCross('consumer.ts'); const { code, path } = loadCross('consumer.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
const registry = analyzeSource(code, path, imported); const registry = analyzeSource(code, path, imported);
const gen = generateCode(registry); const gen = generateCode(registry);
const result = execAndGet<any>(gen + `\n const result = execAndGet<any>(gen + `\n
const enc = protobuf_encode_UserMsg({ id: 42, name: 'alice' }); const enc = protobuf_encode_UserMsg({ id: 42, name: 'alice' });
globalThis.__r = protobuf_decode_UserMsg(enc); globalThis.__r = protobuf_decode_UserMsg(enc);
`, '__r'); `, '__r');
expect(result.id).toBe(42); expect(result.id).toBe(42);
expect(result.name).toBe('alice'); expect(result.name).toBe('alice');
}); });
// ── Scenario B: imported type as pb<> field ────────────────────── // ── Scenario B: imported type as pb<> field ──────────────────────
it('resolves imported nested message type', () => { it('resolves imported nested message type', () => {
const { code, path } = loadCross('outer.ts'); const { code, path } = loadCross('outer.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
expect(imported.concrete.some(m => m.name === 'Inner')).toBe(true); expect(imported.concrete.some(m => m.name === 'Inner')).toBe(true);
const registry = analyzeSource(code, path, imported); const registry = analyzeSource(code, path, imported);
expect(registry.has('Inner')).toBe(true); expect(registry.has('Inner')).toBe(true);
expect(registry.has('Outer')).toBe(true); expect(registry.has('Outer')).toBe(true);
const outer = registry.get('Outer')!; const outer = registry.get('Outer')!;
const innerField = outer.fields.find(f => f.name === 'inner')!; const innerField = outer.fields.find(f => f.name === 'inner')!;
expect(innerField.isMessage).toBe(true); expect(innerField.isMessage).toBe(true);
}); });
it('Scenario B round-trip', () => { it('Scenario B round-trip', () => {
const { code, path } = loadCross('outer.ts'); const { code, path } = loadCross('outer.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
const registry = analyzeSource(code, path, imported); const registry = analyzeSource(code, path, imported);
const gen = generateCode(registry); const gen = generateCode(registry);
const result = execAndGet<any>(gen + `\n const result = execAndGet<any>(gen + `\n
const enc = protobuf_encode_Outer({ inner: { value: 42 } }); const enc = protobuf_encode_Outer({ inner: { value: 42 } });
globalThis.__r = protobuf_decode_Outer(enc); globalThis.__r = protobuf_decode_Outer(enc);
`, '__r'); `, '__r');
expect(result.inner.value).toBe(42); expect(result.inner.value).toBe(42);
}); });
// ── Generic template import ────────────────────────────────────── // ── Generic template import ──────────────────────────────────────
it('resolves imported generic template', () => { it('resolves imported generic template', () => {
const { code, path } = loadCross('generic-consumer.ts'); const { code, path } = loadCross('generic-consumer.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
expect(imported.templates.has('Wrapper')).toBe(true); expect(imported.templates.has('Wrapper')).toBe(true);
const registry = analyzeSource(code, path, imported); const registry = analyzeSource(code, path, imported);
expect(registry.has('Wrapper__string')).toBe(true); expect(registry.has('Wrapper__string')).toBe(true);
}); });
it('generic import round-trip', () => { it('generic import round-trip', () => {
const { code, path } = loadCross('generic-consumer.ts'); const { code, path } = loadCross('generic-consumer.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
const registry = analyzeSource(code, path, imported); const registry = analyzeSource(code, path, imported);
const gen = generateCode(registry); const gen = generateCode(registry);
const result = execAndGet<any>(gen + `\n const result = execAndGet<any>(gen + `\n
const enc = protobuf_encode_Wrapper__string({ value: 'hello' }); const enc = protobuf_encode_Wrapper__string({ value: 'hello' });
globalThis.__r = protobuf_decode_Wrapper__string(enc); globalThis.__r = protobuf_decode_Wrapper__string(enc);
`, '__r'); `, '__r');
expect(result.value).toBe('hello'); expect(result.value).toBe('hello');
}); });
it('resolves generic type passed through imported wrapper functions', () => { it('resolves generic type passed through imported wrapper functions', () => {
const { code, path } = loadCross('wrapper-consumer.ts'); const { code, path } = loadCross('wrapper-consumer.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
expect(imported.templates.has('Wrapper')).toBe(true); expect(imported.templates.has('Wrapper')).toBe(true);
const { registry, callSites, sourceFile } = analyze(code, path, imported); const { registry, callSites, sourceFile } = analyze(code, path, imported);
const used = selectUsedRegistry(registry, callSites, sourceFile); const used = selectUsedRegistry(registry, callSites, sourceFile);
expect(used.registry.has('Wrapper__string')).toBe(true); expect(used.registry.has('Wrapper__string')).toBe(true);
expect(used.callSites).toHaveLength(2); expect(used.callSites).toHaveLength(2);
expect(used.callSites[0].fnName).toBe('protobuf_encode'); expect(used.callSites[0].fnName).toBe('protobuf_encode');
expect(used.callSites[1].fnName).toBe('protobuf_decode'); expect(used.callSites[1].fnName).toBe('protobuf_decode');
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
expect(hasReplacements).toBe(true); expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
}); });
it('handles wrapper aliases, arrows, nested generics, and non-first generic forwarding', () => { it('handles wrapper aliases, arrows, nested generics, and non-first generic forwarding', () => {
const { code, path } = loadCross('wrapper-edge-consumer.ts'); const { code, path } = loadCross('wrapper-edge-consumer.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
const { registry, callSites, sourceFile } = analyze(code, path, imported); const { registry, callSites, sourceFile } = analyze(code, path, imported);
const used = selectUsedRegistry(registry, callSites, sourceFile); const used = selectUsedRegistry(registry, callSites, sourceFile);
expect(used.registry.has('Wrapper__string')).toBe(true); expect(used.registry.has('Wrapper__string')).toBe(true);
expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true); expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true);
expect(used.callSites).toHaveLength(5); expect(used.callSites).toHaveLength(5);
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
expect(hasReplacements).toBe(true); expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string('); expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string(');
expect(transformedCode).toContain('protobuf_decode_Wrapper__Wrapper__string('); expect(transformedCode).toContain('protobuf_decode_Wrapper__Wrapper__string(');
expect(transformedCode).toContain('passthroughOnly<Wrapper<string>>'); expect(transformedCode).toContain('passthroughOnly<Wrapper<string>>');
}); });
it('handles local wrapper functions in the entry file', () => { it('handles local wrapper functions in the entry file', () => {
const { code, path } = loadCross('local-wrapper-consumer.ts'); const { code, path } = loadCross('local-wrapper-consumer.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
const { registry, callSites, sourceFile } = analyze(code, path, imported); const { registry, callSites, sourceFile } = analyze(code, path, imported);
const used = selectUsedRegistry(registry, callSites, sourceFile); const used = selectUsedRegistry(registry, callSites, sourceFile);
expect(used.registry.has('Wrapper__string')).toBe(true); expect(used.registry.has('Wrapper__string')).toBe(true);
expect(used.callSites).toHaveLength(2); expect(used.callSites).toHaveLength(2);
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
expect(hasReplacements).toBe(true); expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
}); });
it('handles complex wrapper objects, branches, nested helpers, and chains', () => { it('handles complex wrapper objects, branches, nested helpers, and chains', () => {
const { code, path } = loadCross('wrapper-complex-consumer.ts'); const { code, path } = loadCross('wrapper-complex-consumer.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
const { registry, callSites, sourceFile } = analyze(code, path, imported); const { registry, callSites, sourceFile } = analyze(code, path, imported);
const used = selectUsedRegistry(registry, callSites, sourceFile); const used = selectUsedRegistry(registry, callSites, sourceFile);
expect(used.registry.has('Wrapper__string')).toBe(true); expect(used.registry.has('Wrapper__string')).toBe(true);
expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true); expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true);
expect(used.callSites).toHaveLength(7); expect(used.callSites).toHaveLength(7);
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
expect(hasReplacements).toBe(true); expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string('); expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string(');
expect(transformedCode).not.toContain('encodeChained<Wrapper<string>>'); expect(transformedCode).not.toContain('encodeChained<Wrapper<string>>');
}); });
it('handles wrapper protobuf type derived from another generic type', () => { it('handles wrapper protobuf type derived from another generic type', () => {
const { code, path } = loadCross('wrapper-type-source-consumer.ts'); const { code, path } = loadCross('wrapper-type-source-consumer.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
const { registry, callSites, sourceFile } = analyze(code, path, imported); const { registry, callSites, sourceFile } = analyze(code, path, imported);
const used = selectUsedRegistry(registry, callSites, sourceFile); const used = selectUsedRegistry(registry, callSites, sourceFile);
expect(used.registry.has('Wrapper__string')).toBe(true); expect(used.registry.has('Wrapper__string')).toBe(true);
expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true); expect(used.registry.has('Wrapper__Wrapper__string')).toBe(true);
expect(used.callSites).toHaveLength(5); expect(used.callSites).toHaveLength(5);
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
expect(hasReplacements).toBe(true); expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_Wrapper__string('); expect(transformedCode).toContain('protobuf_encode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_decode_Wrapper__string('); expect(transformedCode).toContain('protobuf_decode_Wrapper__string(');
expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string('); expect(transformedCode).toContain('protobuf_encode_Wrapper__Wrapper__string(');
expect(transformedCode).not.toContain('encodeBoxed<string>'); expect(transformedCode).not.toContain('encodeBoxed<string>');
}); });
// ── Transitive imports ─────────────────────────────────────────── // ── Transitive imports ───────────────────────────────────────────
it('resolves transitive imports (A → B → C)', () => { it('resolves transitive imports (A → B → C)', () => {
const { code, path } = loadCross('top.ts'); const { code, path } = loadCross('top.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
expect(imported.concrete.some(m => m.name === 'Mid')).toBe(true); expect(imported.concrete.some(m => m.name === 'Mid')).toBe(true);
expect(imported.concrete.some(m => m.name === 'Deep')).toBe(true); expect(imported.concrete.some(m => m.name === 'Deep')).toBe(true);
const registry = analyzeSource(code, path, imported); const registry = analyzeSource(code, path, imported);
expect(registry.has('Top')).toBe(true); expect(registry.has('Top')).toBe(true);
expect(registry.has('Mid')).toBe(true); expect(registry.has('Mid')).toBe(true);
expect(registry.has('Deep')).toBe(true); expect(registry.has('Deep')).toBe(true);
}); });
it('transitive import round-trip', () => { it('transitive import round-trip', () => {
const { code, path } = loadCross('top.ts'); const { code, path } = loadCross('top.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
const registry = analyzeSource(code, path, imported); const registry = analyzeSource(code, path, imported);
const gen = generateCode(registry); const gen = generateCode(registry);
const result = execAndGet<any>(gen + `\n const result = execAndGet<any>(gen + `\n
const enc = protobuf_encode_Top({ nested: { inner: { val: 99 } } }); const enc = protobuf_encode_Top({ nested: { inner: { val: 99 } } });
globalThis.__r = protobuf_decode_Top(enc); globalThis.__r = protobuf_decode_Top(enc);
`, '__r'); `, '__r');
expect(result.nested.inner.val).toBe(99); expect(result.nested.inner.val).toBe(99);
}); });
// ── Cache behavior ─────────────────────────────────────────────── // ── Cache behavior ───────────────────────────────────────────────
it('uses cache on repeated resolves', () => { it('uses cache on repeated resolves', () => {
const { code, path } = loadCross('consumer.ts'); const { code, path } = loadCross('consumer.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
resolveImports(code, path, cache); resolveImports(code, path, cache);
expect(cache.size).toBeGreaterThan(0); expect(cache.size).toBeGreaterThan(0);
const cached = new Map(cache); const cached = new Map(cache);
resolveImports(code, path, cache); resolveImports(code, path, cache);
// Same entries, not re-created // Same entries, not re-created
for (const [key, val] of cache) { for (const [key, val] of cache) {
expect(val).toBe(cached.get(key)); expect(val).toBe(cached.get(key));
} }
}); });
// ── Graceful fallback ──────────────────────────────────────────── // ── Graceful fallback ────────────────────────────────────────────
it('handles missing import file gracefully', () => { it('handles missing import file gracefully', () => {
const code = `import type { Ghost } from './nonexistent';\nconst x = 1;`; const code = `import type { Ghost } from './nonexistent';\nconst x = 1;`;
const fakePath = resolve(crossDir, 'fake.ts'); const fakePath = resolve(crossDir, 'fake.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, fakePath, cache); const imported = resolveImports(code, fakePath, cache);
expect(imported.concrete).toEqual([]); expect(imported.concrete).toEqual([]);
expect(imported.templates.size).toBe(0); expect(imported.templates.size).toBe(0);
}); });
it('only resolves imports reachable from protobuf call roots', () => { it('only resolves imports reachable from protobuf call roots', () => {
const code = ` const code = `
import { protobuf_encode } from '@snowluma/proton'; import { protobuf_encode } from '@snowluma/proton';
import type { UserMsg } from './types'; import type { UserMsg } from './types';
import type { Inner } from './inner'; import type { Inner } from './inner';
const buf = protobuf_encode<UserMsg>({ id: 42, name: 'alice' }); const buf = protobuf_encode<UserMsg>({ id: 42, name: 'alice' });
`; `;
const fakePath = resolve(crossDir, 'on-demand.ts'); const fakePath = resolve(crossDir, 'on-demand.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, fakePath, cache); const imported = resolveImports(code, fakePath, cache);
expect(imported.concrete.map(m => m.name)).toEqual(['UserMsg']); expect(imported.concrete.map(m => m.name)).toEqual(['UserMsg']);
expect(cache.has(resolve(crossDir, 'types.ts'))).toBe(true); expect(cache.has(resolve(crossDir, 'types.ts'))).toBe(true);
expect(cache.has(resolve(crossDir, 'inner.ts'))).toBe(false); expect(cache.has(resolve(crossDir, 'inner.ts'))).toBe(false);
}); });
// ── Value import (non-type import) ─────────────────────────────── // ── Value import (non-type import) ───────────────────────────────
it('resolves value import { SimpleMessage } (not import type)', () => { it('resolves value import { SimpleMessage } (not import type)', () => {
const { code, path } = loadCross('value-import-consumer.ts'); const { code, path } = loadCross('value-import-consumer.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
expect(imported.concrete.some(m => m.name === 'SimpleMessage')).toBe(true); expect(imported.concrete.some(m => m.name === 'SimpleMessage')).toBe(true);
const { registry, callSites, sourceFile } = analyze(code, path, imported); const { registry, callSites, sourceFile } = analyze(code, path, imported);
expect(registry.has('SimpleMessage')).toBe(true); expect(registry.has('SimpleMessage')).toBe(true);
expect(callSites.length).toBe(2); expect(callSites.length).toBe(2);
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry); const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, registry);
expect(hasReplacements).toBe(true); expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_SimpleMessage('); expect(transformedCode).toContain('protobuf_encode_SimpleMessage(');
expect(transformedCode).toContain('protobuf_decode_SimpleMessage('); expect(transformedCode).toContain('protobuf_decode_SimpleMessage(');
}); });
it('value import round-trip', () => { it('value import round-trip', () => {
const { code, path } = loadCross('value-import-consumer.ts'); const { code, path } = loadCross('value-import-consumer.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
const registry = analyzeSource(code, path, imported); const registry = analyzeSource(code, path, imported);
const gen = generateCode(registry); const gen = generateCode(registry);
const result = execAndGet<any>(gen + `\n const result = execAndGet<any>(gen + `\n
const enc = protobuf_encode_SimpleMessage({ id: 42 }); const enc = protobuf_encode_SimpleMessage({ id: 42 });
globalThis.__r = protobuf_decode_SimpleMessage(enc); globalThis.__r = protobuf_decode_SimpleMessage(enc);
`, '__r'); `, '__r');
expect(result.id).toBe(42); expect(result.id).toBe(42);
}); });
it('canonicalizes imported type aliases to the original message name', () => { it('canonicalizes imported type aliases to the original message name', () => {
const { code, path } = loadCross('aliased-consumer.ts'); const { code, path } = loadCross('aliased-consumer.ts');
const cache = new Map<string, ParsedFileEntry>(); const cache = new Map<string, ParsedFileEntry>();
const imported = resolveImports(code, path, cache); const imported = resolveImports(code, path, cache);
const { registry, callSites, sourceFile } = analyze(code, path, imported); const { registry, callSites, sourceFile } = analyze(code, path, imported);
const used = selectUsedRegistry(registry, callSites, sourceFile); const used = selectUsedRegistry(registry, callSites, sourceFile);
expect(used.registry.has('UserMsg')).toBe(true); expect(used.registry.has('UserMsg')).toBe(true);
expect(used.registry.has('AliasMsg')).toBe(false); expect(used.registry.has('AliasMsg')).toBe(false);
expect(used.callSites).toHaveLength(2); expect(used.callSites).toHaveLength(2);
expect(used.callSites[0].typeName).toBe('UserMsg'); expect(used.callSites[0].typeName).toBe('UserMsg');
expect(used.callSites[1].typeName).toBe('UserMsg'); expect(used.callSites[1].typeName).toBe('UserMsg');
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry); const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
expect(hasReplacements).toBe(true); expect(hasReplacements).toBe(true);
expect(transformedCode).toContain('protobuf_encode_UserMsg('); expect(transformedCode).toContain('protobuf_encode_UserMsg(');
expect(transformedCode).toContain('protobuf_decode_UserMsg('); expect(transformedCode).toContain('protobuf_decode_UserMsg(');
expect(transformedCode).not.toContain('protobuf_encode_AliasMsg('); expect(transformedCode).not.toContain('protobuf_encode_AliasMsg(');
expect(transformedCode).not.toContain('protobuf_decode_AliasMsg('); expect(transformedCode).not.toContain('protobuf_decode_AliasMsg(');
}); });
}); });
+5 -5
View File
@@ -6,7 +6,7 @@ const fixturesDir = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'fixt
/** Load a fixture file as a string. */ /** Load a fixture file as a string. */
export function loadFixture(name: string): string { export function loadFixture(name: string): string {
return readFileSync(resolve(fixturesDir, name), 'utf-8'); return readFileSync(resolve(fixturesDir, name), 'utf-8');
} }
/** /**
@@ -14,8 +14,8 @@ export function loadFixture(name: string): string {
* Cleans up the global after retrieval. * Cleans up the global after retrieval.
*/ */
export function execAndGet<T>(code: string, globalKey: string): T { export function execAndGet<T>(code: string, globalKey: string): T {
new Function(code)(); new Function(code)();
const val = (globalThis as any)[globalKey] as T; const val = (globalThis as any)[globalKey] as T;
delete (globalThis as any)[globalKey]; delete (globalThis as any)[globalKey];
return val; return val;
} }
+1 -1
View File
@@ -24,7 +24,7 @@ function abortUpgrade(socket: Duplex, status: number, message?: string): void {
'Connection: close\r\n' + 'Connection: close\r\n' +
`Content-Length: ${Buffer.byteLength(body)}\r\n` + `Content-Length: ${Buffer.byteLength(body)}\r\n` +
'Content-Type: text/plain\r\n\r\n'; 'Content-Type: text/plain\r\n\r\n';
socket.write(head + body); socket.write(head + body);
} catch { /* noop */ } } catch { /* noop */ }
try { socket.destroy(); } catch { /* noop */ } try { socket.destroy(); } catch { /* noop */ }
} }
+1
View File
@@ -25,6 +25,7 @@ export default defineConfig([
}, },
}, },
rules: { rules: {
'indent': ['error', 2, { SwitchCase: 1 }],
'react-refresh/only-export-components': 'off', 'react-refresh/only-export-components': 'off',
'react-hooks/set-state-in-effect': 'off', 'react-hooks/set-state-in-effect': 'off',
}, },