diff --git a/eslint.config.ts b/eslint.config.ts index 1505d8b5..3318e517 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -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', diff --git a/packages/core/src/bridge/actions/group-album.ts b/packages/core/src/bridge/actions/group-album.ts index 27bf922d..1cce1e72 100644 --- a/packages/core/src/bridge/actions/group-album.ts +++ b/packages/core/src/bridge/actions/group-album.ts @@ -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 { 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 { 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 { 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 { 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) { diff --git a/packages/core/src/bridge/web-actions/cookies.ts b/packages/core/src/bridge/web-actions/cookies.ts index 8ecb5bab..00686979 100644 --- a/packages/core/src/bridge/web-actions/cookies.ts +++ b/packages/core/src/bridge/web-actions/cookies.ts @@ -120,8 +120,8 @@ export function getBknFromSKey(skey: string): number { export async function getCookiesStr(bridge: Bridge, domain: string): Promise { 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 { 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; diff --git a/packages/core/src/bridge/web/group-album.ts b/packages/core/src/bridge/web/group-album.ts index 5d8d87f4..830ec25e 100644 --- a/packages/core/src/bridge/web/group-album.ts +++ b/packages/core/src/bridge/web/group-album.ts @@ -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 { const img_size = statSync(filePath).size; const slice_size = 16384; // 严格使用 16KB diff --git a/packages/core/src/bridge/web/group-essence.ts b/packages/core/src/bridge/web/group-essence.ts index bf1710ce..5d8a7347 100644 --- a/packages/core/src/bridge/web/group-essence.ts +++ b/packages/core/src/bridge/web/group-essence.ts @@ -19,53 +19,53 @@ export interface GroupEssenceMsgRet { * 分页获取群精华消息 */ export async function getGroupEssenceMsg( - cookieObject: Record, - groupCode: string, - pageStart: number = 0, - pageLimit: number = 50 + cookieObject: Record, + groupCode: string, + pageStart: number = 0, + pageLimit: number = 50 ): Promise { - 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( - 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( + 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, - groupCode: string + cookieObject: Record, + groupCode: string ): Promise { - 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; } \ No newline at end of file diff --git a/packages/core/src/bridge/web/group-honor.ts b/packages/core/src/bridge/web/group-honor.ts index c9162b09..55a98546 100644 --- a/packages/core/src/bridge/web/group-honor.ts +++ b/packages/core/src/bridge/web/group-honor.ts @@ -13,41 +13,41 @@ export enum WebHonorType { async function fetchHonorData(cookieObject: Record, 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, 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 []; + } } \ No newline at end of file diff --git a/packages/core/src/bridge/web/group-notice.ts b/packages/core/src/bridge/web/group-notice.ts index 5d330b52..824fc5b3 100644 --- a/packages/core/src/bridge/web/group-notice.ts +++ b/packages/core/src/bridge/web/group-notice.ts @@ -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, - 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, + 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 { - 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 = { - qid: groupCode, - bkn: bodyBkn, - text: content, - pinned: pinned.toString(), - type: type.toString(), - settings, - }; + const bodyParams: Record = { + 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( - 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( + 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, - groupCode: string, - start: number = -1, // -1 表示第一页 - count: number = 20 // 抓包中是 10,你可以根据需要调整 + cookieObject: Record, + groupCode: string, + start: number = -1, // -1 表示第一页 + count: number = 20 // 抓包中是 10,你可以根据需要调整 ): Promise { - 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( - 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( + 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, - imageBuffer: Buffer + cookieObject: Record, + 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(/"/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(/"/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, - groupCode: string, - fid: string + cookieObject: Record, + groupCode: string, + fid: string ): Promise { - 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( - 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( + 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; + } } \ No newline at end of file diff --git a/packages/core/src/bridge/web/request-util.ts b/packages/core/src/bridge/web/request-util.ts index 0c880a48..60f28d8f 100644 --- a/packages/core/src/bridge/web/request-util.ts +++ b/packages/core/src/bridge/web/request-util.ts @@ -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(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(url: string, method: string = 'GET', data?: any, headers: { [key: string]: string; } = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5): Promise { - 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(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(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(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(url, method, data, headers, false, false); + } } export function cookieToString(cookieObject: Record): 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 { - 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(); } diff --git a/packages/core/src/onebot/actions/extended.ts b/packages/core/src/onebot/actions/extended.ts index 3935872d..aca89cef 100644 --- a/packages/core/src/onebot/actions/extended.ts +++ b/packages/core/src/onebot/actions/extended.ts @@ -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) { diff --git a/packages/core/src/onebot/config.ts b/packages/core/src/onebot/config.ts index 5e1605df..64aa8241 100644 --- a/packages/core/src/onebot/config.ts +++ b/packages/core/src/onebot/config.ts @@ -243,9 +243,9 @@ function collectByName( function pickAutoName(kind: keyof OneBotNetworks, used: Map, 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; diff --git a/packages/core/src/onebot/message-store.ts b/packages/core/src/onebot/message-store.ts index d17d4395..f2b29a24 100644 --- a/packages/core/src/onebot/message-store.ts +++ b/packages/core/src/onebot/message-store.ts @@ -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; diff --git a/packages/proton/src/ast/collector.ts b/packages/proton/src/ast/collector.ts index f05deda6..6955b308 100644 --- a/packages/proton/src/ast/collector.ts +++ b/packages/proton/src/ast/collector.ts @@ -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 { - 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`) 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`) 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, - resolveImportedTypeName: ImportedTypeNameResolver, + member: ts.PropertySignature, + sf: ts.SourceFile, + tpSet: Set, + 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`, // 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; } diff --git a/packages/proton/src/ast/import-resolver.ts b/packages/proton/src/ast/import-resolver.ts index c662818c..70207a77 100644 --- a/packages/proton/src/ast/import-resolver.ts +++ b/packages/proton/src/ast/import-resolver.ts @@ -37,359 +37,359 @@ interface ImportClause { } function getCallableName(expr: ts.Expression): string | null { - if (ts.isIdentifier(expr)) return expr.text; - if (ts.isPropertyAccessExpression(expr)) return expr.name.text; - return null; + if (ts.isIdentifier(expr)) return expr.text; + if (ts.isPropertyAccessExpression(expr)) return expr.name.text; + return null; } /** Extract all named imports from the source file (both type and value imports). */ function extractImports(sf: ts.SourceFile): ImportClause[] { - const result: ImportClause[] = []; - for (const stmt of sf.statements) { - if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue; - const spec = stmt.moduleSpecifier; - if (!ts.isStringLiteral(spec)) continue; - const specifier = spec.text; + const result: ImportClause[] = []; + for (const stmt of sf.statements) { + if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue; + const spec = stmt.moduleSpecifier; + if (!ts.isStringLiteral(spec)) continue; + const specifier = spec.text; - const clause = stmt.importClause; - if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) { - for (const el of clause.namedBindings.elements) { - result.push({ - importedName: (el.propertyName ?? el.name).text, - localName: el.name.text, - specifier, - }); - } - } + const clause = stmt.importClause; + if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) { + for (const el of clause.namedBindings.elements) { + result.push({ + importedName: (el.propertyName ?? el.name).text, + localName: el.name.text, + specifier, + }); + } } - return result; + } + return result; } /** Like `extractImports`, but skips `import type { ... }` and `import { type X }` * entries. Wrapper functions are values, so type-only imports can't introduce * one and we shouldn't eagerly parse their source files just to look for wrappers. */ function extractValueImports(sf: ts.SourceFile): ImportClause[] { - const result: ImportClause[] = []; - for (const stmt of sf.statements) { - if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue; - if (stmt.importClause.isTypeOnly) continue; - const spec = stmt.moduleSpecifier; - if (!ts.isStringLiteral(spec)) continue; - const specifier = spec.text; + const result: ImportClause[] = []; + for (const stmt of sf.statements) { + if (!ts.isImportDeclaration(stmt) || !stmt.importClause) continue; + if (stmt.importClause.isTypeOnly) continue; + const spec = stmt.moduleSpecifier; + if (!ts.isStringLiteral(spec)) continue; + const specifier = spec.text; - const clause = stmt.importClause; - if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) { - for (const el of clause.namedBindings.elements) { - if (el.isTypeOnly) continue; - result.push({ - importedName: (el.propertyName ?? el.name).text, - localName: el.name.text, - specifier, - }); - } - } + const clause = stmt.importClause; + if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) { + for (const el of clause.namedBindings.elements) { + if (el.isTypeOnly) continue; + result.push({ + importedName: (el.propertyName ?? el.name).text, + localName: el.name.text, + specifier, + }); + } } - return result; + } + return result; } function extractExportAllSpecifiers(sf: ts.SourceFile): string[] { - const result: string[] = []; - for (const stmt of sf.statements) { - if (!ts.isExportDeclaration(stmt) || stmt.exportClause) continue; - const spec = stmt.moduleSpecifier; - if (spec && ts.isStringLiteral(spec)) result.push(spec.text); - } - return result; + const result: string[] = []; + for (const stmt of sf.statements) { + if (!ts.isExportDeclaration(stmt) || stmt.exportClause) continue; + const spec = stmt.moduleSpecifier; + if (spec && ts.isStringLiteral(spec)) result.push(spec.text); + } + return result; } /** Resolve a relative module specifier to an absolute file path. Returns null if not found. */ function resolveModulePath(specifier: string, importerPath: string): string | null { - if (!specifier.startsWith('.')) return null; // skip bare/alias specifiers + if (!specifier.startsWith('.')) return null; // skip bare/alias specifiers - const base = resolve(dirname(importerPath), specifier); + const base = resolve(dirname(importerPath), specifier); - // Try exact path (e.g., './types.ts') - if (existsSync(base) && !base.endsWith('.ts') === false) return base; - if (base.endsWith('.ts') && existsSync(base)) return base; + // Try exact path (e.g., './types.ts') + if (existsSync(base) && !base.endsWith('.ts') === false) return base; + if (base.endsWith('.ts') && existsSync(base)) return base; - // Try appending .ts - const withTs = base + '.ts'; - if (existsSync(withTs)) return withTs; + // Try appending .ts + const withTs = base + '.ts'; + if (existsSync(withTs)) return withTs; - // Try as directory with index.ts - const indexTs = resolve(base, 'index.ts'); - if (existsSync(indexTs)) return indexTs; + // Try as directory with index.ts + const indexTs = resolve(base, 'index.ts'); + if (existsSync(indexTs)) return indexTs; - return null; + return null; } function hasExportModifier(node: ts.Node): boolean { - return ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword); + return ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword); } function matchForwardedProtobufFn( - body: ts.ConciseBody | ts.Block | undefined, - sf: ts.SourceFile, - typeParams: readonly ts.TypeParameterDeclaration[] | undefined, + body: ts.ConciseBody | ts.Block | undefined, + sf: ts.SourceFile, + typeParams: readonly ts.TypeParameterDeclaration[] | undefined, ): WrapperBinding | null { - if (!body || !typeParams?.length) return null; - const typeParamIndexes = new Map(typeParams.map((p, index) => [p.name.text, index])); - const typeParamNames = typeParams.map(p => p.name.text); - const bindings = collectProtobufImportBindings(sf); - let found: WrapperBinding | null = null; + if (!body || !typeParams?.length) return null; + const typeParamIndexes = new Map(typeParams.map((p, index) => [p.name.text, index])); + const typeParamNames = typeParams.map(p => p.name.text); + const bindings = collectProtobufImportBindings(sf); + let found: WrapperBinding | null = null; - function visit(node: ts.Node): void { - if (found) return; - if (ts.isCallExpression(node)) { - const cs = matchProtobufCallSite(node, sf, bindings, { - allowLegacyUnboundCanonical: true, - }); - if ( - cs && + function visit(node: ts.Node): void { + if (found) return; + if (ts.isCallExpression(node)) { + const cs = matchProtobufCallSite(node, sf, bindings, { + allowLegacyUnboundCanonical: true, + }); + if ( + cs && ts.isTypeReferenceNode(cs.firstTypeArg) && ts.isIdentifier(cs.firstTypeArg.typeName) && typeParamIndexes.has(cs.firstTypeArg.typeName.text) - ) { - found = { - fnName: cs.fnName, - typeArgIndex: typeParamIndexes.get(cs.firstTypeArg.typeName.text)!, - sourceFilePath: sf.fileName, - }; - return; - } + ) { + found = { + fnName: cs.fnName, + typeArgIndex: typeParamIndexes.get(cs.firstTypeArg.typeName.text)!, + sourceFilePath: sf.fileName, + }; + return; + } - if (cs && containsTypeParameter(cs.firstTypeArg, typeParamIndexes)) { - found = { - fnName: cs.fnName, - typeArgIndex: firstTypeParameterIndex(cs.firstTypeArg, typeParamIndexes) ?? 0, - typePattern: cs.firstTypeArg.getText(sf), - typeParamNames, - sourceFilePath: sf.fileName, - }; - return; - } - } - ts.forEachChild(node, visit); + if (cs && containsTypeParameter(cs.firstTypeArg, typeParamIndexes)) { + found = { + fnName: cs.fnName, + typeArgIndex: firstTypeParameterIndex(cs.firstTypeArg, typeParamIndexes) ?? 0, + typePattern: cs.firstTypeArg.getText(sf), + typeParamNames, + sourceFilePath: sf.fileName, + }; + return; + } } + ts.forEachChild(node, visit); + } - visit(body); - return found; + visit(body); + return found; } function containsTypeParameter(typeNode: ts.TypeNode, typeParamIndexes: Map): boolean { - let found = false; - function visit(node: ts.Node): void { - if (found) return; - if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && typeParamIndexes.has(node.typeName.text)) { - found = true; - return; - } - ts.forEachChild(node, visit); + let found = false; + function visit(node: ts.Node): void { + if (found) return; + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && typeParamIndexes.has(node.typeName.text)) { + found = true; + return; } - visit(typeNode); - return found; + ts.forEachChild(node, visit); + } + visit(typeNode); + return found; } function firstTypeParameterIndex(typeNode: ts.TypeNode, typeParamIndexes: Map): number | null { - let index: number | null = null; - function visit(node: ts.Node): void { - if (index !== null) return; - if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && typeParamIndexes.has(node.typeName.text)) { - index = typeParamIndexes.get(node.typeName.text)!; - return; - } - ts.forEachChild(node, visit); + let index: number | null = null; + function visit(node: ts.Node): void { + if (index !== null) return; + if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && typeParamIndexes.has(node.typeName.text)) { + index = typeParamIndexes.get(node.typeName.text)!; + return; } - visit(typeNode); - return index; + ts.forEachChild(node, visit); + } + visit(typeNode); + return index; } function instantiateWrapperTypePattern( - binding: WrapperBinding, - callerTypeArgs: ts.NodeArray, - sf: ts.SourceFile, + binding: WrapperBinding, + callerTypeArgs: ts.NodeArray, + sf: ts.SourceFile, ): ts.TypeNode | null { - if (!binding.typePattern || !binding.typeParamNames?.length) return callerTypeArgs[binding.typeArgIndex] ?? null; + if (!binding.typePattern || !binding.typeParamNames?.length) return callerTypeArgs[binding.typeArgIndex] ?? null; - let text = binding.typePattern; - for (let i = 0; i < binding.typeParamNames.length; i++) { - const arg = callerTypeArgs[i]; - if (!arg) return null; - text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf)); - } + let text = binding.typePattern; + for (let i = 0; i < binding.typeParamNames.length; i++) { + const arg = callerTypeArgs[i]; + if (!arg) return null; + text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf)); + } - const parsed = ts.createSourceFile('wrapper-type.ts', `type __T = ${text};`, ts.ScriptTarget.Latest, true); - const stmt = parsed.statements[0]; - if (!ts.isTypeAliasDeclaration(stmt)) return null; - return stmt.type; + const parsed = ts.createSourceFile('wrapper-type.ts', `type __T = ${text};`, ts.ScriptTarget.Latest, true); + const stmt = parsed.statements[0]; + if (!ts.isTypeAliasDeclaration(stmt)) return null; + return stmt.type; } function matchForwardedKnownWrapper( - body: ts.ConciseBody | ts.Block | undefined, - typeParams: readonly ts.TypeParameterDeclaration[] | undefined, - knownWrappers: Map, + body: ts.ConciseBody | ts.Block | undefined, + typeParams: readonly ts.TypeParameterDeclaration[] | undefined, + knownWrappers: Map, ): WrapperBinding | null { - if (!body || !typeParams?.length) return null; - const tps = typeParams; // narrowed copy for closure scope - const typeParamIndexes = new Map(tps.map((p, index) => [p.name.text, index])); - let found: WrapperBinding | null = null; + if (!body || !typeParams?.length) return null; + const tps = typeParams; // narrowed copy for closure scope + const typeParamIndexes = new Map(tps.map((p, index) => [p.name.text, index])); + let found: WrapperBinding | null = null; - function visit(node: ts.Node): void { - if (found) return; - if (ts.isCallExpression(node) && node.typeArguments?.length) { - const callableName = getCallableName(node.expression); - const wrapper = callableName ? knownWrappers.get(callableName) : undefined; - const forwardedTypeArg = wrapper ? node.typeArguments[wrapper.typeArgIndex] : undefined; - if ( - wrapper && + function visit(node: ts.Node): void { + if (found) return; + if (ts.isCallExpression(node) && node.typeArguments?.length) { + const callableName = getCallableName(node.expression); + const wrapper = callableName ? knownWrappers.get(callableName) : undefined; + const forwardedTypeArg = wrapper ? node.typeArguments[wrapper.typeArgIndex] : undefined; + if ( + wrapper && forwardedTypeArg && ts.isTypeReferenceNode(forwardedTypeArg) && ts.isIdentifier(forwardedTypeArg.typeName) && !forwardedTypeArg.typeArguments?.length && typeParamIndexes.has(forwardedTypeArg.typeName.text) - ) { - const chainTypeArgIndex = typeParamIndexes.get(forwardedTypeArg.typeName.text)!; - const binding: WrapperBinding = { - fnName: wrapper.fnName, - typeArgIndex: chainTypeArgIndex, - }; - // Propagate the typePattern from the inner wrapper, substituting - // its type-param names with the chain's own. Otherwise the chain - // would treat its own `` as the encoded type rather than the - // wrapped form (e.g. `Wrapper`). - if (wrapper.typePattern && wrapper.typeParamNames?.length === 1) { - const chainParamName = tps[chainTypeArgIndex].name.text; - const wrapperParamName = wrapper.typeParamNames[0]; - binding.typePattern = wrapperParamName === chainParamName - ? wrapper.typePattern - : wrapper.typePattern.replace(new RegExp(`\\b${wrapperParamName}\\b`, 'g'), chainParamName); - binding.typeParamNames = [chainParamName]; - binding.sourceFilePath = wrapper.sourceFilePath; - } - found = binding; - return; - } + ) { + const chainTypeArgIndex = typeParamIndexes.get(forwardedTypeArg.typeName.text)!; + const binding: WrapperBinding = { + fnName: wrapper.fnName, + typeArgIndex: chainTypeArgIndex, + }; + // Propagate the typePattern from the inner wrapper, substituting + // its type-param names with the chain's own. Otherwise the chain + // would treat its own `` as the encoded type rather than the + // wrapped form (e.g. `Wrapper`). + if (wrapper.typePattern && wrapper.typeParamNames?.length === 1) { + const chainParamName = tps[chainTypeArgIndex].name.text; + const wrapperParamName = wrapper.typeParamNames[0]; + binding.typePattern = wrapperParamName === chainParamName + ? wrapper.typePattern + : wrapper.typePattern.replace(new RegExp(`\\b${wrapperParamName}\\b`, 'g'), chainParamName); + binding.typeParamNames = [chainParamName]; + binding.sourceFilePath = wrapper.sourceFilePath; } - - ts.forEachChild(node, visit); + found = binding; + return; + } } - visit(body); - return found; + ts.forEachChild(node, visit); + } + + visit(body); + return found; } function collectWrapperCandidates( - sf: ts.SourceFile, - exportedOnly: boolean, + sf: ts.SourceFile, + exportedOnly: boolean, ): Array<{ name: string; body: ts.ConciseBody | ts.Block | undefined; typeParameters: readonly ts.TypeParameterDeclaration[] | undefined }> { - const candidates: Array<{ name: string; body: ts.ConciseBody | ts.Block | undefined; typeParameters: readonly ts.TypeParameterDeclaration[] | undefined }> = []; + const candidates: Array<{ name: string; body: ts.ConciseBody | ts.Block | undefined; typeParameters: readonly ts.TypeParameterDeclaration[] | undefined }> = []; - for (const stmt of sf.statements) { - if (ts.isFunctionDeclaration(stmt) && stmt.name && (!exportedOnly || hasExportModifier(stmt))) { - candidates.push({ name: stmt.name.text, body: stmt.body, typeParameters: stmt.typeParameters }); - continue; - } - - if (!ts.isVariableStatement(stmt) || (exportedOnly && !hasExportModifier(stmt))) continue; - for (const decl of stmt.declarationList.declarations) { - if (!ts.isIdentifier(decl.name) || !decl.initializer) continue; - const init = decl.initializer; - if (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) { - candidates.push({ name: decl.name.text, body: init.body, typeParameters: init.typeParameters }); - continue; - } - - if (ts.isObjectLiteralExpression(init)) { - for (const prop of init.properties) { - if (ts.isPropertyAssignment(prop)) { - const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; - const propInit = prop.initializer; - if (propName && (ts.isArrowFunction(propInit) || ts.isFunctionExpression(propInit))) { - candidates.push({ name: propName, body: propInit.body, typeParameters: propInit.typeParameters }); - } - continue; - } - - if (ts.isMethodDeclaration(prop)) { - const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; - if (propName) candidates.push({ name: propName, body: prop.body, typeParameters: prop.typeParameters }); - } - } - } - } + for (const stmt of sf.statements) { + if (ts.isFunctionDeclaration(stmt) && stmt.name && (!exportedOnly || hasExportModifier(stmt))) { + candidates.push({ name: stmt.name.text, body: stmt.body, typeParameters: stmt.typeParameters }); + continue; } - return candidates; + if (!ts.isVariableStatement(stmt) || (exportedOnly && !hasExportModifier(stmt))) continue; + for (const decl of stmt.declarationList.declarations) { + if (!ts.isIdentifier(decl.name) || !decl.initializer) continue; + const init = decl.initializer; + if (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) { + candidates.push({ name: decl.name.text, body: init.body, typeParameters: init.typeParameters }); + continue; + } + + if (ts.isObjectLiteralExpression(init)) { + for (const prop of init.properties) { + if (ts.isPropertyAssignment(prop)) { + const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; + const propInit = prop.initializer; + if (propName && (ts.isArrowFunction(propInit) || ts.isFunctionExpression(propInit))) { + candidates.push({ name: propName, body: propInit.body, typeParameters: propInit.typeParameters }); + } + continue; + } + + if (ts.isMethodDeclaration(prop)) { + const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; + if (propName) candidates.push({ name: propName, body: prop.body, typeParameters: prop.typeParameters }); + } + } + } + } + } + + return candidates; } function collectWrappers( - sf: ts.SourceFile, - exportedOnly: boolean, - externalKnownWrappers: Map = new Map(), + sf: ts.SourceFile, + exportedOnly: boolean, + externalKnownWrappers: Map = new Map(), ): Map { - const wrappers = new Map(); - const localWrapperMembers = new Map>(); - const candidates = collectWrapperCandidates(sf, exportedOnly); + const wrappers = new Map(); + const localWrapperMembers = new Map>(); + const candidates = collectWrapperCandidates(sf, exportedOnly); - for (const candidate of candidates) { - const fn = matchForwardedProtobufFn(candidate.body, sf, candidate.typeParameters); - if (fn) wrappers.set(candidate.name, fn); - } + for (const candidate of candidates) { + const fn = matchForwardedProtobufFn(candidate.body, sf, candidate.typeParameters); + if (fn) wrappers.set(candidate.name, fn); + } - // Detect both intra-file forwarders (`encodeFoo(v) { return encodeBar(v); }` - // where `encodeBar` is local) AND cross-file forwarders to wrappers imported - // from already-parsed modules. Externally known wrappers are seeded by the - // caller (`parseFileForDefinitions`) after it resolves imports. - const knownForForwarding = new Map(); - for (const [k, v] of externalKnownWrappers) knownForForwarding.set(k, v); - for (const [k, v] of wrappers) knownForForwarding.set(k, v); + // Detect both intra-file forwarders (`encodeFoo(v) { return encodeBar(v); }` + // where `encodeBar` is local) AND cross-file forwarders to wrappers imported + // from already-parsed modules. Externally known wrappers are seeded by the + // caller (`parseFileForDefinitions`) after it resolves imports. + const knownForForwarding = new Map(); + for (const [k, v] of externalKnownWrappers) knownForForwarding.set(k, v); + for (const [k, v] of wrappers) knownForForwarding.set(k, v); - for (const candidate of candidates) { - if (wrappers.has(candidate.name)) continue; - const fn = matchForwardedKnownWrapper(candidate.body, candidate.typeParameters, knownForForwarding); - if (fn) wrappers.set(candidate.name, fn); - } + for (const candidate of candidates) { + if (wrappers.has(candidate.name)) continue; + const fn = matchForwardedKnownWrapper(candidate.body, candidate.typeParameters, knownForForwarding); + if (fn) wrappers.set(candidate.name, fn); + } - for (const stmt of sf.statements) { - if (!ts.isVariableStatement(stmt) || (exportedOnly && !hasExportModifier(stmt))) continue; - for (const decl of stmt.declarationList.declarations) { - if (!ts.isIdentifier(decl.name) || !decl.initializer) continue; - const init = decl.initializer; - if (ts.isObjectLiteralExpression(init)) { - const memberWrappers = new Map(); - for (const prop of init.properties) { - if (!('name' in prop) || !prop.name) continue; - const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; - if (!propName) continue; - const fn = wrappers.get(propName); - if (fn) { - memberWrappers.set(propName, fn); - } - } - if (memberWrappers.size) localWrapperMembers.set(decl.name.text, memberWrappers); - } + for (const stmt of sf.statements) { + if (!ts.isVariableStatement(stmt) || (exportedOnly && !hasExportModifier(stmt))) continue; + for (const decl of stmt.declarationList.declarations) { + if (!ts.isIdentifier(decl.name) || !decl.initializer) continue; + const init = decl.initializer; + if (ts.isObjectLiteralExpression(init)) { + const memberWrappers = new Map(); + for (const prop of init.properties) { + if (!('name' in prop) || !prop.name) continue; + const propName = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : null; + if (!propName) continue; + const fn = wrappers.get(propName); + if (fn) { + memberWrappers.set(propName, fn); + } } + if (memberWrappers.size) localWrapperMembers.set(decl.name.text, memberWrappers); + } } + } - for (const stmt of sf.statements) { - if (exportedOnly || !ts.isVariableStatement(stmt)) continue; - for (const decl of stmt.declarationList.declarations) { - if (!ts.isIdentifier(decl.name) || !decl.initializer || !ts.isPropertyAccessExpression(decl.initializer)) continue; - if (!ts.isIdentifier(decl.initializer.expression)) continue; - const memberWrappers = localWrapperMembers.get(decl.initializer.expression.text); - const fn = memberWrappers?.get(decl.initializer.name.text); - if (fn) wrappers.set(decl.name.text, fn); - } + for (const stmt of sf.statements) { + if (exportedOnly || !ts.isVariableStatement(stmt)) continue; + for (const decl of stmt.declarationList.declarations) { + if (!ts.isIdentifier(decl.name) || !decl.initializer || !ts.isPropertyAccessExpression(decl.initializer)) continue; + if (!ts.isIdentifier(decl.initializer.expression)) continue; + const memberWrappers = localWrapperMembers.get(decl.initializer.expression.text); + const fn = memberWrappers?.get(decl.initializer.name.text); + if (fn) wrappers.set(decl.name.text, fn); } + } - return wrappers; + return wrappers; } function collectExportedWrappers( - sf: ts.SourceFile, - externalKnownWrappers: Map = new Map(), + sf: ts.SourceFile, + externalKnownWrappers: Map = new Map(), ): Map { - return collectWrappers(sf, true, externalKnownWrappers); + return collectWrappers(sf, true, externalKnownWrappers); } /** @@ -401,110 +401,110 @@ function collectExportedWrappers( * where `encodeBase` is imported from another module — can be detected. */ function parseFileForDefinitions( - absolutePath: string, - code?: string, - cache?: Map, - parsing?: Set, + absolutePath: string, + code?: string, + cache?: Map, + parsing?: Set, ): ParsedFileEntry { - const sourceText = code ?? readFileSync(absolutePath, 'utf-8'); - const sf = ts.createSourceFile(absolutePath, sourceText, ts.ScriptTarget.Latest, true); - const concrete: ProtobufMessage[] = []; - const templates = new Map(); - const resolveImportedTypeName = createImportedTypeNameResolver(sf); - const importedTypeSources = new Map(); - const exportAllTypeSources = new Map(); + const sourceText = code ?? readFileSync(absolutePath, 'utf-8'); + const sf = ts.createSourceFile(absolutePath, sourceText, ts.ScriptTarget.Latest, true); + const concrete: ProtobufMessage[] = []; + const templates = new Map(); + const resolveImportedTypeName = createImportedTypeNameResolver(sf); + const importedTypeSources = new Map(); + const exportAllTypeSources = new Map(); - // Collect imported wrapper bindings under their LOCAL names so this file's - // forwarders can match against them. Skip work entirely if there's no cache - // (legacy callers that don't care about cross-file forwarding). - // - // Only descends into value imports (not `import type { ... }`), since - // type-only imports can never introduce a wrapper function. This avoids - // pulling unrelated type-only modules into the cache. - const importedKnownWrappers = new Map(); - if (cache) { - const inProgress = parsing ?? new Set(); - inProgress.add(absolutePath); - for (const imp of extractValueImports(sf)) { - const resolved = resolveModulePath(imp.specifier, absolutePath); - if (!resolved) continue; - if (inProgress.has(resolved)) continue; // cycle guard - let entry = cache.get(resolved); - if (!entry) { - entry = parseFileForDefinitions(resolved, undefined, cache, inProgress); - cache.set(resolved, entry); - } - const wrapperFn = entry.exportedWrappers.get(imp.importedName); - if (wrapperFn) importedKnownWrappers.set(imp.localName, wrapperFn); - } - inProgress.delete(absolutePath); + // Collect imported wrapper bindings under their LOCAL names so this file's + // forwarders can match against them. Skip work entirely if there's no cache + // (legacy callers that don't care about cross-file forwarding). + // + // Only descends into value imports (not `import type { ... }`), since + // type-only imports can never introduce a wrapper function. This avoids + // pulling unrelated type-only modules into the cache. + const importedKnownWrappers = new Map(); + if (cache) { + const inProgress = parsing ?? new Set(); + inProgress.add(absolutePath); + for (const imp of extractValueImports(sf)) { + const resolved = resolveModulePath(imp.specifier, absolutePath); + if (!resolved) continue; + if (inProgress.has(resolved)) continue; // cycle guard + let entry = cache.get(resolved); + if (!entry) { + entry = parseFileForDefinitions(resolved, undefined, cache, inProgress); + cache.set(resolved, entry); + } + const wrapperFn = entry.exportedWrappers.get(imp.importedName); + if (wrapperFn) importedKnownWrappers.set(imp.localName, wrapperFn); } + inProgress.delete(absolutePath); + } - const exportedWrappers = collectExportedWrappers(sf, importedKnownWrappers); + const exportedWrappers = collectExportedWrappers(sf, importedKnownWrappers); - for (const imp of extractImports(sf)) { - const resolved = resolveModulePath(imp.specifier, absolutePath); - if (!resolved) continue; - importedTypeSources.set(imp.importedName, resolved); - importedTypeSources.set(imp.localName, resolved); + for (const imp of extractImports(sf)) { + const resolved = resolveModulePath(imp.specifier, absolutePath); + if (!resolved) continue; + importedTypeSources.set(imp.importedName, resolved); + importedTypeSources.set(imp.localName, resolved); + } + + if (cache) { + const inProgress = parsing ?? new Set(); + inProgress.add(absolutePath); + for (const specifier of extractExportAllSpecifiers(sf)) { + const resolved = resolveModulePath(specifier, absolutePath); + if (!resolved || inProgress.has(resolved)) continue; + let entry = cache.get(resolved); + if (!entry) { + entry = parseFileForDefinitions(resolved, undefined, cache, inProgress); + cache.set(resolved, entry); + } + for (const msg of entry.concrete) exportAllTypeSources.set(msg.name, resolved); + for (const name of entry.templates.keys()) exportAllTypeSources.set(name, resolved); + for (const [name, source] of entry.exportAllTypeSources) exportAllTypeSources.set(name, source); } + inProgress.delete(absolutePath); + } - if (cache) { - const inProgress = parsing ?? new Set(); - inProgress.add(absolutePath); - for (const specifier of extractExportAllSpecifiers(sf)) { - const resolved = resolveModulePath(specifier, absolutePath); - if (!resolved || inProgress.has(resolved)) continue; - let entry = cache.get(resolved); - if (!entry) { - entry = parseFileForDefinitions(resolved, undefined, cache, inProgress); - cache.set(resolved, entry); - } - for (const msg of entry.concrete) exportAllTypeSources.set(msg.name, resolved); - for (const name of entry.templates.keys()) exportAllTypeSources.set(name, resolved); - for (const [name, source] of entry.exportAllTypeSources) exportAllTypeSources.set(name, source); - } - inProgress.delete(absolutePath); + for (const stmt of sf.statements) { + if (!ts.isInterfaceDeclaration(stmt)) continue; + if (stmt.typeParameters?.length) { + const tpl = collectGenericInterface(stmt, sf, resolveImportedTypeName); + if (tpl) templates.set(tpl.name, tpl); + } else { + const msg = collectInterface(stmt, sf, resolveImportedTypeName); + if (msg) concrete.push(msg); } + } - for (const stmt of sf.statements) { - if (!ts.isInterfaceDeclaration(stmt)) continue; - if (stmt.typeParameters?.length) { - const tpl = collectGenericInterface(stmt, sf, resolveImportedTypeName); - if (tpl) templates.set(tpl.name, tpl); - } else { - const msg = collectInterface(stmt, sf, resolveImportedTypeName); - if (msg) concrete.push(msg); - } - } - - return { - filePath: absolutePath, - concrete, - templates, - importedTypeSources, - exportAllTypeSources, - resolveImportedTypeName, - exportedWrappers, - }; + return { + filePath: absolutePath, + concrete, + templates, + importedTypeSources, + exportAllTypeSources, + resolveImportedTypeName, + exportedWrappers, + }; } function collectCallRootTypeNodes(sf: ts.SourceFile): ts.TypeNode[] { - const roots: ts.TypeNode[] = []; - const importBindings = collectProtobufImportBindings(sf); + const roots: ts.TypeNode[] = []; + const importBindings = collectProtobufImportBindings(sf); - ts.forEachChild(sf, function visit(node) { - if (ts.isCallExpression(node)) { - const cs = matchProtobufCallSite(node, sf, importBindings, { - allowLegacyUnboundCanonical: true, - }); - if (cs) roots.push(cs.firstTypeArg); - } + ts.forEachChild(sf, function visit(node) { + if (ts.isCallExpression(node)) { + const cs = matchProtobufCallSite(node, sf, importBindings, { + allowLegacyUnboundCanonical: true, + }); + if (cs) roots.push(cs.firstTypeArg); + } - ts.forEachChild(node, visit); - }); + ts.forEachChild(node, visit); + }); - return roots; + return roots; } interface RootTypeNode { @@ -516,175 +516,175 @@ interface RootTypeNode { * Resolve only the import definitions reachable from protobuf call-site roots. */ export function resolveImports( - code: string, - importerPath: string, - cache: Map, + code: string, + importerPath: string, + cache: Map, ): ImportedDefinitions { - const entryPath = resolve(importerPath); - const entry = parseFileForDefinitions(entryPath, code, cache); - const concrete = new Map(); - const templates = new Map(); - const fileEntries = new Map([[entryPath, entry]]); - const visitedConcrete = new Set(); - const visitedTemplates = new Set(); - const importedObjectWrapperMembers = new Map>(); + const entryPath = resolve(importerPath); + const entry = parseFileForDefinitions(entryPath, code, cache); + const concrete = new Map(); + const templates = new Map(); + const fileEntries = new Map([[entryPath, entry]]); + const visitedConcrete = new Set(); + const visitedTemplates = new Set(); + const importedObjectWrapperMembers = new Map>(); - function getEntry(filePath: string): ParsedFileEntry { - const abs = resolve(filePath); - const known = fileEntries.get(abs); - if (known) return known; + function getEntry(filePath: string): ParsedFileEntry { + const abs = resolve(filePath); + const known = fileEntries.get(abs); + if (known) return known; - let parsed = cache.get(abs); - if (!parsed) { - parsed = parseFileForDefinitions(abs, undefined, cache); - cache.set(abs, parsed); - } - - fileEntries.set(abs, parsed); - return parsed; + let parsed = cache.get(abs); + if (!parsed) { + parsed = parseFileForDefinitions(abs, undefined, cache); + cache.set(abs, parsed); } - function collectCalledGenericIdentifiers(sf: ts.SourceFile): Set { - const names = new Set(); + fileEntries.set(abs, parsed); + return parsed; + } - ts.forEachChild(sf, function visit(node) { - if (ts.isCallExpression(node) && node.typeArguments?.length) { - const callableName = getCallableName(node.expression); - if (callableName) names.add(callableName); - } + function collectCalledGenericIdentifiers(sf: ts.SourceFile): Set { + const names = new Set(); - ts.forEachChild(node, visit); - }); + ts.forEachChild(sf, function visit(node) { + if (ts.isCallExpression(node) && node.typeArguments?.length) { + const callableName = getCallableName(node.expression); + if (callableName) names.add(callableName); + } - return names; + ts.forEachChild(node, visit); + }); + + return names; + } + + function collectWrapperBindings(from: ParsedFileEntry, sf: ts.SourceFile): Map { + const bindings = new Map(); + const localWrappers = from.filePath === entryPath ? collectWrappers(sf, false) : from.exportedWrappers; + for (const [name, fn] of localWrappers) bindings.set(name, fn); + + const calledGenericIdentifiers = collectCalledGenericIdentifiers(sf); + for (const imp of extractImports(sf)) { + if (!calledGenericIdentifiers.has(imp.localName)) continue; + const resolved = resolveModulePath(imp.specifier, from.filePath); + if (!resolved) continue; + const wrapperFn = getEntry(resolved).exportedWrappers.get(imp.importedName); + if (wrapperFn) bindings.set(imp.localName, wrapperFn); + + const importedEntry = getEntry(resolved); + const memberNames = [...importedEntry.exportedWrappers.keys()].filter(name => calledGenericIdentifiers.has(name)); + if (memberNames.length) { + const members = new Map(); + for (const name of memberNames) { + const memberBinding = importedEntry.exportedWrappers.get(name)!; + members.set(name, memberBinding); + bindings.set(name, memberBinding); + } + importedObjectWrapperMembers.set(imp.localName, members); + } } - function collectWrapperBindings(from: ParsedFileEntry, sf: ts.SourceFile): Map { - const bindings = new Map(); - const localWrappers = from.filePath === entryPath ? collectWrappers(sf, false) : from.exportedWrappers; - for (const [name, fn] of localWrappers) bindings.set(name, fn); + return bindings; + } - const calledGenericIdentifiers = collectCalledGenericIdentifiers(sf); - for (const imp of extractImports(sf)) { - if (!calledGenericIdentifiers.has(imp.localName)) continue; - const resolved = resolveModulePath(imp.specifier, from.filePath); - if (!resolved) continue; - const wrapperFn = getEntry(resolved).exportedWrappers.get(imp.importedName); - if (wrapperFn) bindings.set(imp.localName, wrapperFn); + function resolveTypeName(typeName: string, from: ParsedFileEntry): void { + if (typeName in PRIMITIVE_TYPE_MAP) return; - const importedEntry = getEntry(resolved); - const memberNames = [...importedEntry.exportedWrappers.keys()].filter(name => calledGenericIdentifiers.has(name)); - if (memberNames.length) { - const members = new Map(); - for (const name of memberNames) { - const memberBinding = importedEntry.exportedWrappers.get(name)!; - members.set(name, memberBinding); - bindings.set(name, memberBinding); - } - importedObjectWrapperMembers.set(imp.localName, members); - } - } + const concreteMsg = from.concrete.find(msg => msg.name === typeName); + if (concreteMsg) { + const visitKey = `${from.filePath}:message:${typeName}`; + if (visitedConcrete.has(visitKey)) return; + visitedConcrete.add(visitKey); - return bindings; + if (from.filePath !== entryPath && !concrete.has(concreteMsg.name)) { + concrete.set(concreteMsg.name, concreteMsg); + } + + for (const field of concreteMsg.fields) { + resolveTypeName(field.typeName, from); + } + return; } - function resolveTypeName(typeName: string, from: ParsedFileEntry): void { - if (typeName in PRIMITIVE_TYPE_MAP) return; + const template = from.templates.get(typeName); + if (template) { + const visitKey = `${from.filePath}:template:${typeName}`; + if (visitedTemplates.has(visitKey)) return; + visitedTemplates.add(visitKey); - const concreteMsg = from.concrete.find(msg => msg.name === typeName); - if (concreteMsg) { - const visitKey = `${from.filePath}:message:${typeName}`; - if (visitedConcrete.has(visitKey)) return; - visitedConcrete.add(visitKey); + if (from.filePath !== entryPath && !templates.has(template.name)) { + templates.set(template.name, template); + } - if (from.filePath !== entryPath && !concrete.has(concreteMsg.name)) { - concrete.set(concreteMsg.name, concreteMsg); - } - - for (const field of concreteMsg.fields) { - resolveTypeName(field.typeName, from); - } - return; - } - - const template = from.templates.get(typeName); - if (template) { - const visitKey = `${from.filePath}:template:${typeName}`; - if (visitedTemplates.has(visitKey)) return; - visitedTemplates.add(visitKey); - - if (from.filePath !== entryPath && !templates.has(template.name)) { - templates.set(template.name, template); - } - - for (const field of template.fields) { - if (!field.isTypeParam) resolveTypeName(field.rawTypeName, from); - } - return; - } - - const importedPath = from.importedTypeSources.get(typeName) ?? from.exportAllTypeSources.get(typeName); - if (!importedPath) return; - - resolveTypeName(typeName, getEntry(importedPath)); + for (const field of template.fields) { + if (!field.isTypeParam) resolveTypeName(field.rawTypeName, from); + } + return; } - function resolveTypeNode(typeNode: ts.TypeNode, from: ParsedFileEntry): void { - if (isKeywordTypeNode(typeNode)) return; - if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return; + const importedPath = from.importedTypeSources.get(typeName) ?? from.exportAllTypeSources.get(typeName); + if (!importedPath) return; - const typeName = from.resolveImportedTypeName(typeNode.typeName.text); - resolveTypeName(typeName, from); + resolveTypeName(typeName, getEntry(importedPath)); + } - if (!typeNode.typeArguments?.length) return; - for (const typeArg of typeNode.typeArguments) { - resolveTypeNode(typeArg, from); - } + function resolveTypeNode(typeNode: ts.TypeNode, from: ParsedFileEntry): void { + if (isKeywordTypeNode(typeNode)) return; + if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return; + + const typeName = from.resolveImportedTypeName(typeNode.typeName.text); + resolveTypeName(typeName, from); + + if (!typeNode.typeArguments?.length) return; + for (const typeArg of typeNode.typeArguments) { + resolveTypeNode(typeArg, from); } + } - const rootTypeNodes: RootTypeNode[] = collectCallRootTypeNodes(ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true)) - .map(typeNode => ({ typeNode, from: entry })); - const entrySourceFile = ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true); - const wrapperBindings = collectWrapperBindings(entry, entrySourceFile); + const rootTypeNodes: RootTypeNode[] = collectCallRootTypeNodes(ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true)) + .map(typeNode => ({ typeNode, from: entry })); + const entrySourceFile = ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true); + const wrapperBindings = collectWrapperBindings(entry, entrySourceFile); - ts.forEachChild(entrySourceFile, function visit(node) { - if ( - ts.isCallExpression(node) && + ts.forEachChild(entrySourceFile, function visit(node) { + if ( + ts.isCallExpression(node) && node.typeArguments?.length && getCallableName(node.expression) && ( - wrapperBindings.has(getCallableName(node.expression)!) || + wrapperBindings.has(getCallableName(node.expression)!) || ( - ts.isPropertyAccessExpression(node.expression) && + ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && importedObjectWrapperMembers.get(node.expression.expression.text)?.has(node.expression.name.text) ) ) - ) { - const binding = wrapperBindings.get(getCallableName(node.expression)!) ?? ( - ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) - ? importedObjectWrapperMembers.get(node.expression.expression.text)?.get(node.expression.name.text) - : undefined - ); - if (!binding) return; - const typeArg = instantiateWrapperTypePattern(binding, node.typeArguments, entrySourceFile); - if (typeArg) rootTypeNodes.push({ - typeNode: typeArg, - from: binding.typePattern && binding.sourceFilePath ? getEntry(binding.sourceFilePath) : entry, - }); - if (binding.typePattern) { - for (const callerTypeArg of node.typeArguments) { - rootTypeNodes.push({ typeNode: callerTypeArg, from: entry }); - } - } + ) { + const binding = wrapperBindings.get(getCallableName(node.expression)!) ?? ( + ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) + ? importedObjectWrapperMembers.get(node.expression.expression.text)?.get(node.expression.name.text) + : undefined + ); + if (!binding) return; + const typeArg = instantiateWrapperTypePattern(binding, node.typeArguments, entrySourceFile); + if (typeArg) rootTypeNodes.push({ + typeNode: typeArg, + from: binding.typePattern && binding.sourceFilePath ? getEntry(binding.sourceFilePath) : entry, + }); + if (binding.typePattern) { + for (const callerTypeArg of node.typeArguments) { + rootTypeNodes.push({ typeNode: callerTypeArg, from: entry }); } - - ts.forEachChild(node, visit); - }); - - for (const root of rootTypeNodes) { - resolveTypeNode(root.typeNode, root.from); + } } - return { concrete: [...concrete.values()], templates, wrapperBindings }; + ts.forEachChild(node, visit); + }); + + for (const root of rootTypeNodes) { + resolveTypeNode(root.typeNode, root.from); + } + + return { concrete: [...concrete.values()], templates, wrapperBindings }; } diff --git a/packages/proton/src/ast/monomorphizer.ts b/packages/proton/src/ast/monomorphizer.ts index 219c5d1a..29d9e47b 100644 --- a/packages/proton/src/ast/monomorphizer.ts +++ b/packages/proton/src/ast/monomorphizer.ts @@ -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, - out: Map, - resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName, + typeNode: ts.TypeNode, + sf: ts.SourceFile, + templates: Map, + out: Map, + 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(); - 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(); + 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>`). Substitute the params into + // the captured text, re-parse, and re-monomorphize so the resulting + // concrete instantiation (`Wrapper`) 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>`). Substitute the params into - // the captured text, re-parse, and re-monomorphize so the resulting - // concrete instantiation (`Wrapper`) 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, - out: Map, - resolveImportedTypeName: ImportedTypeNameResolver, + node: ts.TypeNode, + sf: ts.SourceFile, + templates: Map, + out: Map, + 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; } diff --git a/packages/proton/src/ast/utils.ts b/packages/proton/src/ast/utils.ts index 04a0590f..68370772 100644 --- a/packages/proton/src/ast/utils.ts +++ b/packages/proton/src/ast/utils.ts @@ -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(); 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(); + const localToImported = new Map(); - 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); } diff --git a/packages/proton/src/codegen/decoder.ts b/packages/proton/src/codegen/decoder.ts index 0d8b87d2..9b8477d2 100644 --- a/packages/proton/src/codegen/decoder.ts +++ b/packages/proton/src/codegen/decoder.ts @@ -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'; } diff --git a/packages/proton/src/codegen/encoder.ts b/packages/proton/src/codegen/encoder.ts index 372898e7..cc89efc4 100644 --- a/packages/proton/src/codegen/encoder.ts +++ b/packages/proton/src/codegen/encoder.ts @@ -5,65 +5,65 @@ import { WireType, type ProtobufField, type ProtobufMessage, type MessageRegistr * Field 1 + Varint(0) -> [0x08], Field 1 + LenDelim(2) -> [0x0a], etc. */ function computeTagBytes(fieldNumber: number, wireType: number): number[] { - let value = ((fieldNumber << 3) | wireType) >>> 0; - const bytes: number[] = []; - while (value > 0x7f) { - bytes.push((value & 0x7f) | 0x80); - value >>>= 7; - } - bytes.push(value & 0x7f); - return bytes; + let value = ((fieldNumber << 3) | wireType) >>> 0; + const bytes: number[] = []; + while (value > 0x7f) { + bytes.push((value & 0x7f) | 0x80); + value >>>= 7; + } + bytes.push(value & 0x7f); + return bytes; } function writeTag(fieldNumber: number, wireType: number, ind: string): string { - return computeTagBytes(fieldNumber, wireType) - .map(byte => `${ind}buf[offset++] = ${byte};`) - .join('\n'); + return computeTagBytes(fieldNumber, wireType) + .map(byte => `${ind}buf[offset++] = ${byte};`) + .join('\n'); } function varintSize(varName: string, ind: string): string { - return `${ind}size += ${varName} < 0x80 ? 1 : ${varName} < 0x4000 ? 2 : ${varName} < 0x200000 ? 3 : ${varName} < 0x10000000 ? 4 : 5;`; + return `${ind}size += ${varName} < 0x80 ? 1 : ${varName} < 0x4000 ? 2 : ${varName} < 0x200000 ? 3 : ${varName} < 0x10000000 ? 4 : 5;`; } function writeVarint(expr: string, ind: string): string { - return [ - `${ind}let _v = ${expr};`, - `${ind}if (_v < 0x80) {`, - `${ind} buf[offset++] = _v;`, - `${ind}} else if (_v < 0x4000) {`, - `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, - `${ind} buf[offset++] = _v >>> 7;`, - `${ind}} else if (_v < 0x200000) {`, - `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, - `${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`, - `${ind} buf[offset++] = _v >>> 14;`, - `${ind}} else if (_v < 0x10000000) {`, - `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, - `${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`, - `${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`, - `${ind} buf[offset++] = _v >>> 21;`, - `${ind}} else {`, - `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, - `${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`, - `${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`, - `${ind} buf[offset++] = ((_v >>> 21) & 0x7f) | 0x80;`, - `${ind} buf[offset++] = _v >>> 28;`, - `${ind}}`, - ].join('\n'); + return [ + `${ind}let _v = ${expr};`, + `${ind}if (_v < 0x80) {`, + `${ind} buf[offset++] = _v;`, + `${ind}} else if (_v < 0x4000) {`, + `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, + `${ind} buf[offset++] = _v >>> 7;`, + `${ind}} else if (_v < 0x200000) {`, + `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = _v >>> 14;`, + `${ind}} else if (_v < 0x10000000) {`, + `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = _v >>> 21;`, + `${ind}} else {`, + `${ind} buf[offset++] = (_v & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = ((_v >>> 21) & 0x7f) | 0x80;`, + `${ind} buf[offset++] = _v >>> 28;`, + `${ind}}`, + ].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'; } function bigintVarintExpr(typeName: string, expr: string): string { - if (typeName === 'uint_64') return `BigInt.asUintN(64, ${expr})`; - if (typeName === 'int_64') return `BigInt.asUintN(64, ${expr})`; - return `__zigZagEncode64(${expr})`; + if (typeName === 'uint_64') return `BigInt.asUintN(64, ${expr})`; + if (typeName === 'int_64') return `BigInt.asUintN(64, ${expr})`; + return `__zigZagEncode64(${expr})`; } interface EncoderBlock { @@ -73,518 +73,518 @@ interface EncoderBlock { } export function generateEncoder(msg: ProtobufMessage, _registry: MessageRegistry): string { - const blocks = msg.fields.map((field, index) => field.isRepeated ? buildRepeatedBlock(field, index) : buildSingularBlock(field, index)); + const blocks = msg.fields.map((field, index) => field.isRepeated ? buildRepeatedBlock(field, index) : buildSingularBlock(field, index)); - const L = [ - `function protobuf_encode_${msg.name}(obj) {`, - ` let size = 0;`, - ...blocks.flatMap(block => block.declare), - ...blocks.flatMap(block => block.size), - ` const buf = new Uint8Array(size);`, - ` let offset = 0;`, - ...blocks.flatMap(block => block.write), - ` return buf;`, - `}`, - ]; - return L.join('\n'); + const L = [ + `function protobuf_encode_${msg.name}(obj) {`, + ` let size = 0;`, + ...blocks.flatMap(block => block.declare), + ...blocks.flatMap(block => block.size), + ` const buf = new Uint8Array(size);`, + ` let offset = 0;`, + ...blocks.flatMap(block => block.write), + ` return buf;`, + `}`, + ]; + return L.join('\n'); } function buildSingularBlock(field: ProtobufField, index: number): EncoderBlock { - const { name, fieldNumber, typeName, wireType, isMessage } = field; - const valueVar = `_f${index}`; - const cacheVar = `_c${index}`; - const tagLength = computeTagBytes(fieldNumber, isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType).length; + const { name, fieldNumber, typeName, wireType, isMessage } = field; + const valueVar = `_f${index}`; + const cacheVar = `_c${index}`; + const tagLength = computeTagBytes(fieldNumber, isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType).length; - if (isMessage) { - return { - declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`], - size: [ - ` if (${valueVar} != null) {`, - ` ${cacheVar} = protobuf_encode_${typeName}(${valueVar});`, - ` const _len = ${cacheVar}.length;`, - ` size += ${tagLength};`, - varintSize('_len', ' '), - ` size += _len;`, - ` }`, - ], - write: [ - ` if (${valueVar} != null) {`, - ` const _data = ${cacheVar};`, - writeTag(fieldNumber, 2, ' '), - ` const _len = _data.length;`, - writeVarint('_len', ' '), - ` buf.set(_data, offset);`, - ` offset += _len;`, - ` }`, - ], - }; - } + if (isMessage) { + return { + declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`], + size: [ + ` if (${valueVar} != null) {`, + ` ${cacheVar} = protobuf_encode_${typeName}(${valueVar});`, + ` const _len = ${cacheVar}.length;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ], + write: [ + ` if (${valueVar} != null) {`, + ` const _data = ${cacheVar};`, + writeTag(fieldNumber, 2, ' '), + ` const _len = _data.length;`, + writeVarint('_len', ' '), + ` buf.set(_data, offset);`, + ` offset += _len;`, + ` }`, + ], + }; + } - if (typeName === 'string') { - return { - declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`], - size: [ - ` if (${valueVar} != null && ${valueVar} !== "") {`, - ` ${cacheVar} = __utf8Len(${valueVar});`, - ` const _len = ${cacheVar};`, - ` size += ${tagLength};`, - varintSize('_len', ' '), - ` size += _len;`, - ` }`, - ], - write: [ - ` if (${valueVar} != null && ${valueVar} !== "") {`, - writeTag(fieldNumber, 2, ' '), - ` const _len = ${cacheVar};`, - writeVarint('_len', ' '), - ` offset = __utf8Write(buf, offset, ${valueVar});`, - ` }`, - ], - }; - } + if (typeName === 'string') { + return { + declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`], + size: [ + ` if (${valueVar} != null && ${valueVar} !== "") {`, + ` ${cacheVar} = __utf8Len(${valueVar});`, + ` const _len = ${cacheVar};`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ], + write: [ + ` if (${valueVar} != null && ${valueVar} !== "") {`, + writeTag(fieldNumber, 2, ' '), + ` const _len = ${cacheVar};`, + writeVarint('_len', ' '), + ` offset = __utf8Write(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } - if (typeName === 'bytes') { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [ - ` if (${valueVar} != null && ${valueVar}.length > 0) {`, - ` const _len = ${valueVar}.length;`, - ` size += ${tagLength};`, - varintSize('_len', ' '), - ` size += _len;`, - ` }`, - ], - write: [ - ` if (${valueVar} != null && ${valueVar}.length > 0) {`, - writeTag(fieldNumber, 2, ' '), - ` const _len = ${valueVar}.length;`, - writeVarint('_len', ' '), - ` buf.set(${valueVar}, offset);`, - ` offset += _len;`, - ` }`, - ], - }; - } + if (typeName === 'bytes') { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [ + ` if (${valueVar} != null && ${valueVar}.length > 0) {`, + ` const _len = ${valueVar}.length;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ], + write: [ + ` if (${valueVar} != null && ${valueVar}.length > 0) {`, + writeTag(fieldNumber, 2, ' '), + ` const _len = ${valueVar}.length;`, + writeVarint('_len', ' '), + ` buf.set(${valueVar}, offset);`, + ` offset += _len;`, + ` }`, + ], + }; + } - if (typeName === 'bool') { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [` if (${valueVar} === true) size += ${tagLength + 1};`], - write: [ - ` if (${valueVar} === true) {`, - writeTag(fieldNumber, 0, ' '), - ` buf[offset++] = 1;`, - ` }`, - ], - }; - } + if (typeName === 'bool') { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} === true) size += ${tagLength + 1};`], + write: [ + ` if (${valueVar} === true) {`, + writeTag(fieldNumber, 0, ' '), + ` buf[offset++] = 1;`, + ` }`, + ], + }; + } - if (isVarint64(typeName)) { - const bigintExpr = bigintVarintExpr(typeName, valueVar); - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [ - ` if (${valueVar} != null && ${valueVar} !== 0n) {`, - ` const _val = ${bigintExpr};`, - ` size += ${tagLength};`, - ` size += __varint64Size(_val);`, - ` }`, - ], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0n) {`, - ` const _val = ${bigintExpr};`, - writeTag(fieldNumber, 0, ' '), - ` offset = __writeVarint64(buf, offset, _val);`, - ` }`, - ], - }; - } + if (isVarint64(typeName)) { + const bigintExpr = bigintVarintExpr(typeName, valueVar); + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [ + ` if (${valueVar} != null && ${valueVar} !== 0n) {`, + ` const _val = ${bigintExpr};`, + ` size += ${tagLength};`, + ` size += __varint64Size(_val);`, + ` }`, + ], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0n) {`, + ` const _val = ${bigintExpr};`, + writeTag(fieldNumber, 0, ' '), + ` offset = __writeVarint64(buf, offset, _val);`, + ` }`, + ], + }; + } - if (typeName === 'sint_32') { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - ` const _val = ((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0;`, - ` size += ${tagLength};`, - varintSize('_val', ' '), - ` }`, - ], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - writeTag(fieldNumber, 0, ' '), - writeVarint(`((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0`, ' '), - ` }`, - ], - }; - } + if (typeName === 'sint_32') { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + ` const _val = ((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0`, ' '), + ` }`, + ], + }; + } - if (wireType === WireType.Varint) { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - ` const _val = ${valueVar} >>> 0;`, - ` size += ${tagLength};`, - varintSize('_val', ' '), - ` }`, - ], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - writeTag(fieldNumber, 0, ' '), - writeVarint(`${valueVar} >>> 0`, ' '), - ` }`, - ], - }; - } + if (wireType === WireType.Varint) { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + ` const _val = ${valueVar} >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`${valueVar} >>> 0`, ' '), + ` }`, + ], + }; + } - if (typeName === 'float') { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - writeTag(fieldNumber, 5, ' '), - ` offset = __writeFloat32(buf, offset, ${valueVar});`, - ` }`, - ], - }; - } + if (typeName === 'float') { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 5, ' '), + ` offset = __writeFloat32(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } - if (wireType === WireType.Bit32) { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - writeTag(fieldNumber, 5, ' '), - ` const _val = ${valueVar};`, - ` buf[offset++] = _val & 0xff;`, - ` buf[offset++] = (_val >> 8) & 0xff;`, - ` buf[offset++] = (_val >> 16) & 0xff;`, - ` buf[offset++] = (_val >> 24) & 0xff;`, - ` }`, - ], - }; - } + if (wireType === WireType.Bit32) { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 5, ' '), + ` const _val = ${valueVar};`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` }`, + ], + }; + } - if (typeName === 'double') { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - writeTag(fieldNumber, 1, ' '), - ` offset = __writeFloat64(buf, offset, ${valueVar});`, - ` }`, - ], - }; - } + if (typeName === 'double') { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFloat64(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } - if (isFixed64BigInt(typeName)) { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [` if (${valueVar} != null && ${valueVar} !== 0n) size += ${tagLength + 8};`], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0n) {`, - writeTag(fieldNumber, 1, ' '), - ` offset = __writeFixed64(buf, offset, ${valueVar});`, - ` }`, - ], - }; - } + if (isFixed64BigInt(typeName)) { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} != null && ${valueVar} !== 0n) size += ${tagLength + 8};`], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0n) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFixed64(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } - if (wireType === WireType.Bit64) { - return { - declare: [` const ${valueVar} = obj.${name};`], - size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`], - write: [ - ` if (${valueVar} != null && ${valueVar} !== 0) {`, - writeTag(fieldNumber, 1, ' '), - ` const _val = ${valueVar};`, - ` buf[offset++] = _val & 0xff;`, - ` buf[offset++] = (_val >> 8) & 0xff;`, - ` buf[offset++] = (_val >> 16) & 0xff;`, - ` buf[offset++] = (_val >> 24) & 0xff;`, - ` buf[offset++] = 0;`, - ` buf[offset++] = 0;`, - ` buf[offset++] = 0;`, - ` buf[offset++] = 0;`, - ` }`, - ], - }; - } + if (wireType === WireType.Bit64) { + return { + declare: [` const ${valueVar} = obj.${name};`], + size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`], + write: [ + ` if (${valueVar} != null && ${valueVar} !== 0) {`, + writeTag(fieldNumber, 1, ' '), + ` const _val = ${valueVar};`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` }`, + ], + }; + } - return { declare: [], size: [], write: [] }; + return { declare: [], size: [], write: [] }; } function buildRepeatedBlock(field: ProtobufField, index: number): EncoderBlock { - const { name, fieldNumber, typeName, wireType, isMessage } = field; - const arrayVar = `_f${index}`; - const cacheVar = `_c${index}`; - const tagWireType = isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType; - const tagLength = computeTagBytes(fieldNumber, tagWireType).length; + const { name, fieldNumber, typeName, wireType, isMessage } = field; + const arrayVar = `_f${index}`; + const cacheVar = `_c${index}`; + const tagWireType = isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType; + const tagLength = computeTagBytes(fieldNumber, tagWireType).length; - if (isMessage) { - return { - declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`], - size: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` ${cacheVar} = new Array(${arrayVar}.length);`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _data = protobuf_encode_${typeName}(${arrayVar}[_i]);`, - ` ${cacheVar}[_i] = _data;`, - ` const _len = _data.length;`, - ` size += ${tagLength};`, - varintSize('_len', ' '), - ` size += _len;`, - ` }`, - ` }`, - ], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _data = ${cacheVar}[_i];`, - writeTag(fieldNumber, 2, ' '), - ` const _len = _data.length;`, - writeVarint('_len', ' '), - ` buf.set(_data, offset);`, - ` offset += _len;`, - ` }`, - ` }`, - ], - }; - } + if (isMessage) { + return { + declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` ${cacheVar} = new Array(${arrayVar}.length);`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _data = protobuf_encode_${typeName}(${arrayVar}[_i]);`, + ` ${cacheVar}[_i] = _data;`, + ` const _len = _data.length;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _data = ${cacheVar}[_i];`, + writeTag(fieldNumber, 2, ' '), + ` const _len = _data.length;`, + writeVarint('_len', ' '), + ` buf.set(_data, offset);`, + ` offset += _len;`, + ` }`, + ` }`, + ], + }; + } - if (typeName === 'string') { - return { - declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`], - size: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` ${cacheVar} = new Array(${arrayVar}.length);`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _len = __utf8Len(${arrayVar}[_i]);`, - ` ${cacheVar}[_i] = _len;`, - ` size += ${tagLength};`, - varintSize('_len', ' '), - ` size += _len;`, - ` }`, - ` }`, - ], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _len = ${cacheVar}[_i];`, - writeTag(fieldNumber, 2, ' '), - writeVarint('_len', ' '), - ` offset = __utf8Write(buf, offset, ${arrayVar}[_i]);`, - ` }`, - ` }`, - ], - }; - } + if (typeName === 'string') { + return { + declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` ${cacheVar} = new Array(${arrayVar}.length);`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _len = __utf8Len(${arrayVar}[_i]);`, + ` ${cacheVar}[_i] = _len;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _len = ${cacheVar}[_i];`, + writeTag(fieldNumber, 2, ' '), + writeVarint('_len', ' '), + ` offset = __utf8Write(buf, offset, ${arrayVar}[_i]);`, + ` }`, + ` }`, + ], + }; + } - if (typeName === 'bytes') { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _data = ${arrayVar}[_i];`, - ` const _len = _data.length;`, - ` size += ${tagLength};`, - varintSize('_len', ' '), - ` size += _len;`, - ` }`, - ` }`, - ], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _data = ${arrayVar}[_i];`, - writeTag(fieldNumber, 2, ' '), - ` const _len = _data.length;`, - writeVarint('_len', ' '), - ` buf.set(_data, offset);`, - ` offset += _len;`, - ` }`, - ` }`, - ], - }; - } + if (typeName === 'bytes') { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _data = ${arrayVar}[_i];`, + ` const _len = _data.length;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _data = ${arrayVar}[_i];`, + writeTag(fieldNumber, 2, ' '), + ` const _len = _data.length;`, + writeVarint('_len', ' '), + ` buf.set(_data, offset);`, + ` offset += _len;`, + ` }`, + ` }`, + ], + }; + } - if (typeName === 'bool') { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 1};`], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 0, ' '), - ` buf[offset++] = ${arrayVar}[_i] ? 1 : 0;`, - ` }`, - ` }`, - ], - }; - } + if (typeName === 'bool') { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 1};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 0, ' '), + ` buf[offset++] = ${arrayVar}[_i] ? 1 : 0;`, + ` }`, + ` }`, + ], + }; + } - if (isVarint64(typeName)) { - const bigintExpr = bigintVarintExpr(typeName, `${arrayVar}[_i]`); - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _val = ${bigintExpr};`, - ` size += ${tagLength};`, - ` size += __varint64Size(_val);`, - ` }`, - ` }`, - ], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _val = ${bigintExpr};`, - writeTag(fieldNumber, 0, ' '), - ` offset = __writeVarint64(buf, offset, _val);`, - ` }`, - ` }`, - ], - }; - } + if (isVarint64(typeName)) { + const bigintExpr = bigintVarintExpr(typeName, `${arrayVar}[_i]`); + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _val = ${bigintExpr};`, + ` size += ${tagLength};`, + ` size += __varint64Size(_val);`, + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _val = ${bigintExpr};`, + writeTag(fieldNumber, 0, ' '), + ` offset = __writeVarint64(buf, offset, _val);`, + ` }`, + ` }`, + ], + }; + } - if (typeName === 'sint_32') { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _val = ((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0;`, - ` size += ${tagLength};`, - varintSize('_val', ' '), - ` }`, - ` }`, - ], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 0, ' '), - writeVarint(`((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0`, ' '), - ` }`, - ` }`, - ], - }; - } + if (typeName === 'sint_32') { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _val = ((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0`, ' '), + ` }`, + ` }`, + ], + }; + } - if (wireType === WireType.Varint) { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - ` const _val = ${arrayVar}[_i] >>> 0;`, - ` size += ${tagLength};`, - varintSize('_val', ' '), - ` }`, - ` }`, - ], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 0, ' '), - writeVarint(`${arrayVar}[_i] >>> 0`, ' '), - ` }`, - ` }`, - ], - }; - } + if (wireType === WireType.Varint) { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + ` const _val = ${arrayVar}[_i] >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ` }`, + ], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`${arrayVar}[_i] >>> 0`, ' '), + ` }`, + ` }`, + ], + }; + } - if (typeName === 'float') { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 5, ' '), - ` offset = __writeFloat32(buf, offset, ${arrayVar}[_i]);`, - ` }`, - ` }`, - ], - }; - } + if (typeName === 'float') { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 5, ' '), + ` offset = __writeFloat32(buf, offset, ${arrayVar}[_i]);`, + ` }`, + ` }`, + ], + }; + } - if (wireType === WireType.Bit32) { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 5, ' '), - ` const _val = ${arrayVar}[_i];`, - ` buf[offset++] = _val & 0xff;`, - ` buf[offset++] = (_val >> 8) & 0xff;`, - ` buf[offset++] = (_val >> 16) & 0xff;`, - ` buf[offset++] = (_val >> 24) & 0xff;`, - ` }`, - ` }`, - ], - }; - } + if (wireType === WireType.Bit32) { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 5, ' '), + ` const _val = ${arrayVar}[_i];`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` }`, + ` }`, + ], + }; + } - if (typeName === 'double') { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 1, ' '), - ` offset = __writeFloat64(buf, offset, ${arrayVar}[_i]);`, - ` }`, - ` }`, - ], - }; - } + if (typeName === 'double') { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFloat64(buf, offset, ${arrayVar}[_i]);`, + ` }`, + ` }`, + ], + }; + } - if (isFixed64BigInt(typeName)) { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 1, ' '), - ` offset = __writeFixed64(buf, offset, ${arrayVar}[_i]);`, - ` }`, - ` }`, - ], - }; - } + if (isFixed64BigInt(typeName)) { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFixed64(buf, offset, ${arrayVar}[_i]);`, + ` }`, + ` }`, + ], + }; + } - if (wireType === WireType.Bit64) { - return { - declare: [` const ${arrayVar} = obj.${name};`], - size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`], - write: [ - ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, - ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, - writeTag(fieldNumber, 1, ' '), - ` const _val = ${arrayVar}[_i];`, - ` buf[offset++] = _val & 0xff;`, - ` buf[offset++] = (_val >> 8) & 0xff;`, - ` buf[offset++] = (_val >> 16) & 0xff;`, - ` buf[offset++] = (_val >> 24) & 0xff;`, - ` buf[offset++] = 0;`, - ` buf[offset++] = 0;`, - ` buf[offset++] = 0;`, - ` buf[offset++] = 0;`, - ` }`, - ` }`, - ], - }; - } + if (wireType === WireType.Bit64) { + return { + declare: [` const ${arrayVar} = obj.${name};`], + size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`], + write: [ + ` if (${arrayVar} != null && ${arrayVar}.length > 0) {`, + ` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`, + writeTag(fieldNumber, 1, ' '), + ` const _val = ${arrayVar}[_i];`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` }`, + ` }`, + ], + }; + } - return { declare: [], size: [], write: [] }; + return { declare: [], size: [], write: [] }; } diff --git a/packages/proton/src/runtime.ts b/packages/proton/src/runtime.ts index a4236fbc..b3b8b185 100644 --- a/packages/proton/src/runtime.ts +++ b/packages/proton/src/runtime.ts @@ -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(); * 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(_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() was not transformed by the @snowluma/proton Vite plugin. ' + + throw new Error( + 'protobuf_encode() 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(_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() was not transformed by the @snowluma/proton Vite plugin. ' + + throw new Error( + 'protobuf_decode() 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; } diff --git a/packages/proton/test/__tests__/cross-file.test.ts b/packages/proton/test/__tests__/cross-file.test.ts index 9f553cba..a088acbb 100644 --- a/packages/proton/test/__tests__/cross-file.test.ts +++ b/packages/proton/test/__tests__/cross-file.test.ts @@ -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(); - 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(); + 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(); - 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(); + const imported = resolveImports(code, path, cache); + const registry = analyzeSource(code, path, imported); + const gen = generateCode(registry); - const result = execAndGet(gen + `\n + const result = execAndGet(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(); - const imported = resolveImports(code, path, cache); + it('resolves imported nested message type', () => { + const { code, path } = loadCross('outer.ts'); + const cache = new Map(); + 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(); - 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(); + const imported = resolveImports(code, path, cache); + const registry = analyzeSource(code, path, imported); + const gen = generateCode(registry); - const result = execAndGet(gen + `\n + const result = execAndGet(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(); - const imported = resolveImports(code, path, cache); + it('resolves imported generic template', () => { + const { code, path } = loadCross('generic-consumer.ts'); + const cache = new Map(); + 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(); - 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(); + const imported = resolveImports(code, path, cache); + const registry = analyzeSource(code, path, imported); + const gen = generateCode(registry); - const result = execAndGet(gen + `\n + const result = execAndGet(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(); - 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(); + 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(); - 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(); + 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>'); - }); + 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>'); + }); - it('handles local wrapper functions in the entry file', () => { - const { code, path } = loadCross('local-wrapper-consumer.ts'); - const cache = new Map(); - 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(); + 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(); - 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(); + 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>'); - }); + 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>'); + }); - it('handles wrapper protobuf type derived from another generic type', () => { - const { code, path } = loadCross('wrapper-type-source-consumer.ts'); - const cache = new Map(); - 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(); + 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'); - }); + 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'); + }); - // ── Transitive imports ─────────────────────────────────────────── + // ── Transitive imports ─────────────────────────────────────────── - it('resolves transitive imports (A → B → C)', () => { - const { code, path } = loadCross('top.ts'); - const cache = new Map(); - const imported = resolveImports(code, path, cache); + it('resolves transitive imports (A → B → C)', () => { + const { code, path } = loadCross('top.ts'); + const cache = new Map(); + 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(); - 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(); + const imported = resolveImports(code, path, cache); + const registry = analyzeSource(code, path, imported); + const gen = generateCode(registry); - const result = execAndGet(gen + `\n + const result = execAndGet(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(); + it('uses cache on repeated resolves', () => { + const { code, path } = loadCross('consumer.ts'); + const cache = new Map(); - 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(); + 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(); - 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({ id: 42, name: 'alice' }); `; - const fakePath = resolve(crossDir, 'on-demand.ts'); - const cache = new Map(); + const fakePath = resolve(crossDir, 'on-demand.ts'); + const cache = new Map(); - 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(); - 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(); + 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(); - 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(); + const imported = resolveImports(code, path, cache); + const registry = analyzeSource(code, path, imported); + const gen = generateCode(registry); - const result = execAndGet(gen + `\n + const result = execAndGet(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(); - 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(); + 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('); + }); }); diff --git a/packages/proton/test/helpers/index.ts b/packages/proton/test/helpers/index.ts index 9ac63567..03ad4535 100644 --- a/packages/proton/test/helpers/index.ts +++ b/packages/proton/test/helpers/index.ts @@ -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(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; } diff --git a/packages/websocket/src/server.ts b/packages/websocket/src/server.ts index 99d9fd29..a6a0defa 100644 --- a/packages/websocket/src/server.ts +++ b/packages/websocket/src/server.ts @@ -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 */ } } diff --git a/packages/webui/eslint.config.ts b/packages/webui/eslint.config.ts index c26527fd..dcd2d053 100644 --- a/packages/webui/eslint.config.ts +++ b/packages/webui/eslint.config.ts @@ -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', },