fix: subsetCache 版本指纹改用构建期注入,修复 LLRT __filename 报错

createRequire(import.meta.url) 经 tsdown 打包为 CJS 后引入 __filename,
而 LLRT 运行时不提供 __filename,导致 ReferenceError: __filename is not defined。

改用 tsdown define 构建期把 PACKAGE_VERSION 替换为字面量字符串,
运行时无文件读取、无 __filename 依赖。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
崮生(子虚) 2026-06-13 21:14:01 +08:00
parent c04914e255
commit ef5514a008
2 changed files with 13 additions and 5 deletions

View File

@ -1,4 +1,3 @@
import { createRequire } from "node:module";
import { fontSubset } from "../font_util/font";
import type { FontEditor } from "../../vendor/fonteditor-core/lib/ttf/font.js";
import { parseUrl, jsonResponse, stats, subsetCache, findFontPath, readFontBuffer } from "../shared";
@ -7,13 +6,16 @@ import { parseUrl, jsonResponse, stats, subsetCache, findFontPath, readFontBuffe
*
*
* subsetCache key
* - bump package.json version
* - pnpm dev
* - bump package.json version tsdown define
* - pnpm dev process.uptime()
*
*
*
* createRequire(import.meta.url) package.json tsdown CJS
* __filename LLRT __filename ReferenceError
*/
const packageVersion: string = createRequire(import.meta.url)("../../package.json").version;
const SUBSET_CACHE_KEY = `${packageVersion}:${process.uptime()}`;
declare const PACKAGE_VERSION: string;
const SUBSET_CACHE_KEY = `${PACKAGE_VERSION}:${process.uptime()}`;
/** GET /api?font=...&text=... — 字体裁剪 */
export async function handleFontSubset(req: Request, res: Response) {

View File

@ -1,10 +1,16 @@
import { defineConfig } from "tsdown";
import { readFileSync } from "node:fs";
/** 构建期读取 package.json 版本号,注入为运行时常量(避免运行时读文件 + LLRT 无 __filename 问题) */
const packageVersion = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")).version;
const shared = {
format: ["cjs"],
clean: true,
sourcemap: true,
outDir: "dist_backend",
/** 构建期把 PACKAGE_VERSION 替换为字面量字符串,运行时无任何文件读取 */
define: { PACKAGE_VERSION: JSON.stringify(packageVersion) },
outputOptions: {
/** 禁用代码拆分确保单文件输出tsdown 默认会拆分大依赖为 chunk */
codeSplitting: false,