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