@xiaozhu2007/koishi-plugin-litematic-renderer 0.6.0 → 0.7.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +94 -6
- package/assets/standalone-renderer/litematic-standalone-renderer-0.2.8-patch.1.jar +0 -0
- package/dist/index.css +1 -0
- package/dist/index.js +13 -1
- package/lib/cache.d.ts +94 -0
- package/lib/cache.js +1 -0
- package/lib/concurrency.d.ts +13 -0
- package/lib/concurrency.js +1 -0
- package/lib/config.d.ts +205 -0
- package/lib/config.js +1 -0
- package/lib/diagnostics.d.ts +86 -0
- package/lib/diagnostics.js +1 -0
- package/lib/gpuAgentProtocol.d.ts +196 -0
- package/lib/gpuAgentProtocol.js +1 -0
- package/lib/index.d.ts +74 -435
- package/lib/index.js +1 -1
- package/lib/jsonFile.d.ts +8 -0
- package/lib/jsonFile.js +1 -0
- package/lib/litematic.d.ts +103 -0
- package/lib/litematic.js +1 -0
- package/lib/messageDelivery.d.ts +82 -0
- package/lib/messageDelivery.js +1 -0
- package/lib/messageFiles.d.ts +93 -0
- package/lib/messageFiles.js +1 -0
- package/lib/officialProxy.d.ts +12 -0
- package/lib/officialProxy.js +1 -0
- package/lib/onebotCompat.d.ts +29 -0
- package/lib/onebotCompat.js +1 -0
- package/lib/projectionCache.d.ts +83 -0
- package/lib/projectionCache.js +1 -0
- package/lib/projectionSearch.d.ts +3 -0
- package/lib/projectionSearch.js +1 -0
- package/lib/rateLimit.d.ts +18 -0
- package/lib/rateLimit.js +1 -0
- package/lib/render/cpu.d.ts +23 -0
- package/lib/render/cpu.js +1 -0
- package/lib/render/externalGpu.d.ts +12 -0
- package/lib/render/externalGpu.js +1 -0
- package/lib/render/gpuAgent.d.ts +7 -0
- package/lib/render/gpuAgent.js +1 -0
- package/lib/render/imageValidation.d.ts +18 -0
- package/lib/render/imageValidation.js +1 -0
- package/lib/render/javaBridge.d.ts +11 -0
- package/lib/render/javaBridge.js +1 -0
- package/lib/render/standalone.d.ts +76 -0
- package/lib/render/standalone.js +1 -0
- package/lib/render/types.d.ts +5 -0
- package/lib/render/types.js +1 -0
- package/lib/render/webgl.d.ts +21 -0
- package/lib/render/webgl.js +1 -0
- package/lib/resourcePacks.d.ts +15 -0
- package/lib/resourcePacks.js +1 -0
- package/lib/runtimePaths.d.ts +8 -0
- package/lib/runtimePaths.js +1 -0
- package/lib/schematicFormats.d.ts +8 -0
- package/lib/schematicFormats.js +1 -0
- package/package.json +18 -14
- package/client/index.ts +0 -136
- package/client/style.css +0 -18
- package/dist/style.css +0 -1
- package/lib/gpu-agent-protocol.d.ts +0 -102
- package/lib/gpu-agent-protocol.js +0 -257
package/lib/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Config=exports.inject=exports.name=void 0,exports.resolveOfficialProxyUrl=resolveOfficialProxyUrl,exports.buildSshProxyArguments=buildSshProxyArguments,exports.reloadOfficialQqAdapter=reloadOfficialQqAdapter,exports.apply=apply,exports.saveUploadedResourcePack=saveUploadedResourcePack,exports.hashRenderConfiguration=hashRenderConfiguration,exports.patchOneBotAdapterSource=patchOneBotAdapterSource,exports.cacheNameSegment=cacheNameSegment,exports.enforceCacheLimit=enforceCacheLimit,exports.canRenderInSession=canRenderInSession,exports.isGroupAllowed=isGroupAllowed,exports.findLitematicFile=findLitematicFile,exports.supportsStandaloneJavaVersion=supportsStandaloneJavaVersion,exports.standaloneJvmOptions=standaloneJvmOptions,exports.isJavaMemoryFailure=isJavaMemoryFailure,exports.createGpuRenderRequest=createGpuRenderRequest,exports.mergeRenderDiagnostics=mergeRenderDiagnostics,exports.formatRenderError=formatRenderError,exports.resolveSendOptions=resolveSendOptions,exports.sendImages=sendImages,exports.composeQqOverview=composeQqOverview,exports.replyElements=replyElements,exports.parseLitematicMetadata=parseLitematicMetadata,exports.validateProjectionLimits=validateProjectionLimits,exports.formatLitematicMetadata=formatLitematicMetadata,exports.parseLitematic=parseLitematic,exports.renderSchematic=renderSchematic,exports.renderSixFaceOverview=renderSixFaceOverview;const koishi_1=require("koishi"),node_crypto_1=require("node:crypto"),node_fs_1=require("node:fs"),node_path_1=require("node:path"),node_url_1=require("node:url"),node_child_process_1=require("node:child_process"),node_net_1=require("node:net"),node_zlib_1=require("node:zlib"),pngjs_1=require("pngjs"),ssh2_1=require("ssh2"),gpu_agent_protocol_1=require("./gpu-agent-protocol"),Sentry=require("@sentry/node-core/light");exports.name="litematic-renderer",exports.inject={optional:["puppeteer","server","console"]};const CACHE_FORMAT_VERSION=15,RESOURCE_PACK_UPLOAD_LIMIT=268435456,packageVersion=require("../package.json").version,PLUGIN_VERSION="string"==typeof packageVersion?packageVersion:"unknown";exports.Config=koishi_1.Schema.intersect([koishi_1.Schema.object({qqBotType:koishi_1.Schema.union([koishi_1.Schema.const("official").description("QQ 官方机器人"),koishi_1.Schema.const("selfHosted").description("自建 QQ(OneBot / NapCat)")]).role("radio").default("selfHosted").description("机器人接入类型;决定图片、合并转发、引用和 @ 的发送方式"),patchOneBotGroupUpload:koishi_1.Schema.boolean().default(!0).description("自建 QQ:启动时修复 OneBot 群文件上传事件;官方机器人不使用此项"),officialProxyMode:koishi_1.Schema.union([koishi_1.Schema.const("disabled").description("关闭中转"),koishi_1.Schema.const("proxy").description("使用已有代理"),koishi_1.Schema.const("ssh").description("自动建立 SSH 中转")]).role("radio").default("disabled").description("实验性:仅官方 QQ 使用固定公网出口;默认关闭,不改变现有网络行为").experimental(),officialProxyUrl:koishi_1.Schema.string().default("").description("实验性:已有 socks5h、socks5、http 或 https 代理地址").experimental(),sshProxyExecutable:koishi_1.Schema.string().default("ssh").description("实验性:密钥模式使用的 SSH 可执行文件").experimental(),sshProxyHost:koishi_1.Schema.string().default("").description("实验性:SSH 中转服务器的数字 IP,例如 203.0.113.10").experimental(),sshProxyPort:koishi_1.Schema.natural().min(1).max(65535).default(22).description("实验性:SSH 中转服务器端口").experimental(),sshProxyUser:koishi_1.Schema.string().default("root").description("实验性:SSH 登录用户名").experimental(),sshProxyPrivateKey:koishi_1.Schema.path({filters:["file"]}).default("").description("实验性:SSH 私钥路径;填写后优先使用密钥登录").experimental(),sshProxyPassword:koishi_1.Schema.string().role("secret").default("").description("实验性:SSH 登录密码;不会进入命令行或日志").experimental(),sshProxyLocalPort:koishi_1.Schema.natural().min(1).max(65535).default(1080).description("实验性:仅监听 127.0.0.1 的 SOCKS5 端口").experimental(),officialGatewayWatchdog:koishi_1.Schema.boolean().default(!1).description("实验性:8 分钟无入站消息时热重载 QQ 适配器;默认关闭").experimental()}).description("机器人接入"),koishi_1.Schema.object({renderEngine:koishi_1.Schema.union([koishi_1.Schema.const("standalone"),koishi_1.Schema.const("gpuAgent").description("独立 GPU Agent v2(主动连接)"),koishi_1.Schema.const("java"),koishi_1.Schema.const("webgl"),koishi_1.Schema.const("cpu")]).default("standalone").description("渲染引擎;保留本地全部引擎,并新增主动连接的 GPU Agent v2"),maxFileSize:koishi_1.Schema.natural().min(1).default(1024).description("群聊自动处理的最大文件大小(KB)"),privateMaxFileSize:koishi_1.Schema.natural().min(1).default(1024).description("私聊自动处理的独立文件大小(KB);不改变群聊上限"),maxBlocks:koishi_1.Schema.natural().min(1).max(2e9).default(5e6).description("投影区域体积及声明方块数上限;用于拒绝尺寸异常或资源消耗过大的投影"),outputSize:koishi_1.Schema.natural().min(128).max(4096).default(1024).description("六面图和 CPU 渲染最长边的最大像素数"),background:koishi_1.Schema.string().default("#000000").description("PNG 背景颜色"),transparentBackground:koishi_1.Schema.boolean().default(!1).description("输出透明背景"),isometricFill:koishi_1.Schema.percent().default(.78).description("正二轴测主体在画布中的最大占比"),isometricRotation:koishi_1.Schema.number().min(0).max(360).step(1).default(135).description("Isometric Renders 绕竖直轴的基准旋转角"),isometricSlant:koishi_1.Schema.number().min(-90).max(90).step(1).default(36).description("Isometric Renders 俯仰角;36° 为正二轴测预设")}).description("渲染设置"),koishi_1.Schema.object({allowPrivateRender:koishi_1.Schema.boolean().default(!1).description("允许私聊附件及私聊命令触发渲染;默认关闭以保持现有行为"),sendAsForward:koishi_1.Schema.boolean().default(!1).description("仅自建 QQ:开启为合并转发,关闭为联合发送;官方 QQ 忽略此项"),showViewTitles:koishi_1.Schema.boolean().default(!1).description("仅自建 QQ:发送图片时显示视图标题"),replyAndMention:koishi_1.Schema.boolean().default(!1).description("自建 QQ 会引用并 @ 发送者;官方 QQ 仅引用,避免显示 OpenID"),sixFaceOverview:koishi_1.Schema.boolean().default(!0).description("合并转发时生成并附加上、下、东、南、西、北六面正交合成图"),sixFaceLayout:koishi_1.Schema.union([koishi_1.Schema.const("horizontal").description("横向 3×2"),koishi_1.Schema.const("vertical").description("纵向 2×3")]).default("horizontal").description("六面正交合成图布局;最长边由 outputSize 控制"),groupSendOptions:koishi_1.Schema.array(koishi_1.Schema.object({groupId:koishi_1.Schema.string().description("QQ群号"),sendMode:koishi_1.Schema.union([koishi_1.Schema.const("forward").description("合并转发"),koishi_1.Schema.const("combined").description("联合发送(一条普通消息)")]).default("forward"),replyAndMention:koishi_1.Schema.union([koishi_1.Schema.const("inherit").description("继承全局设置"),koishi_1.Schema.const("enabled").description("开启回复 @"),koishi_1.Schema.const("disabled").description("关闭回复 @")]).default("inherit")})).default([]).description("按群覆盖发送方式和回复设置;官方 QQ 只使用引用开关,自建 QQ 同时使用发送模式和 @"),groupWhitelist:koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("群白名单:非空时只有列表内群可渲染;私聊不参与判定"),groupBlacklist:koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("群黑名单:列表内群始终不渲染,优先级高于白名单")}).description("发送设置"),koishi_1.Schema.object({standaloneJavaCommand:koishi_1.Schema.string().default("").description("独立渲染器使用的 Java 可执行文件;推荐 Java 21+,留空自动查找"),minecraftJarPath:koishi_1.Schema.string().default("").description("可选的 Minecraft 客户端 JAR 或基础资源包;留空使用内置 26.2 原版资源"),resourcePackPaths:koishi_1.Schema.array(koishi_1.Schema.string()).role("table").default([]).description("自定义材质包路径;控制台可上传 ZIP,越靠后优先级越高"),standaloneRendererJar:koishi_1.Schema.string().default("").description("独立渲染器 JAR;留空使用插件内置版本"),standaloneRenderTimeout:koishi_1.Schema.natural().min(1e4).default(18e4).description("独立 Java 渲染超时(毫秒)"),standaloneJavaMaxHeapMb:koishi_1.Schema.natural().min(128).max(32768).step(8).default(200).description("首次独立渲染的最大堆内存(MiB)"),standaloneJavaRetryMaxHeapMb:koishi_1.Schema.natural().min(256).max(32768).step(128).default(2048).description("内存不足时新进程重试的最大堆内存(MiB)"),standaloneJavaMemoryRestartLimit:koishi_1.Schema.natural().max(3).default(1).description("检测到内存不足后启动全新进程重试的次数"),javaResolution:koishi_1.Schema.natural().min(256).max(4096).default(1024).description("Java 渲染最终输出边长"),javaSupersampling:koishi_1.Schema.natural().min(1).max(4).default(2).description("离屏超采样倍数")}).description("独立渲染器"),koishi_1.Schema.object({renderTimeout:koishi_1.Schema.natural().min(1e3).default(3e4).description("文件下载超时(毫秒)"),cacheDirectory:koishi_1.Schema.string().default("data/litematic-renderer-cache").description("持久缓存目录;按插件版本和投影 SHA-256 分区"),cacheMaxSizeGb:koishi_1.Schema.number().min(1).max(1024).step(1).default(20).description("所有版本缓存总上限(GiB),超出后按最久未使用清理"),diagnosticsFilePath:koishi_1.Schema.string().default("data/litematic-renderer-diagnostics.json").description("渲染诊断持久化文件路径;导出地址固定为 /litematic-renderer/diagnostics"),sentryDsn:koishi_1.Schema.string().default("").description("Sentry DSN,用于上报渲染错误;留空时读取 SENTRY_DSN 环境变量").experimental()}).description("缓存与诊断"),koishi_1.Schema.object({isometricCellSize:koishi_1.Schema.natural().min(2).max(32).default(7).description("CPU 正二轴测方块菱形半宽"),javaRenderTimeout:koishi_1.Schema.natural().min(1e4).default(18e4).description("等待 Minecraft Java 渲染桥的超时(毫秒)"),webglQuality:koishi_1.Schema.union([koishi_1.Schema.const("standard"),koishi_1.Schema.const("high"),koishi_1.Schema.const("ultra")]).default("high").description("WebGL 渲染质量"),webglWidth:koishi_1.Schema.natural().min(256).max(2048).default(800).description("WebGL 单张图宽度"),webglHeight:koishi_1.Schema.natural().min(256).max(2048).default(600).description("WebGL 单张图高度"),isometricSquare:koishi_1.Schema.boolean().default(!0).description("将 WebGL 正二轴测图输出为正方形"),javaBridgeDirectory:koishi_1.Schema.string().default("").description("renderEngine=java 时使用的 Fabric Java 渲染桥任务目录"),gpuRendererCommand:koishi_1.Schema.string().default("").description("可选外部 GPU 渲染器命令;非空时优先尝试,失败后回退到 renderEngine")}).description("高级设置"),koishi_1.Schema.object({gpuAgentEnabled:koishi_1.Schema.boolean().default(!1).description("启动 GPU Agent v2 WebSocket 服务;默认关闭,不占用监听端口"),gpuAgentListenHost:koishi_1.Schema.string().default("0.0.0.0").description("GPU Agent v2 监听地址"),gpuAgentListenPort:koishi_1.Schema.natural().min(1).max(65535).default(39180).description("GPU Agent v2 监听端口"),gpuAgentPath:koishi_1.Schema.string().default("/litematic-renderer/agent/v2").description("GPU Agent v2 WebSocket 路径"),gpuAgentNodes:koishi_1.Schema.array(koishi_1.Schema.object({agentId:koishi_1.Schema.string().description("GPU 节点唯一 ID"),sharedSecret:koishi_1.Schema.string().role("secret").description("该节点的 HMAC 共享密钥"),enabled:koishi_1.Schema.boolean().default(!0).description("允许此节点连接")})).default([]).description("允许连接的 GPU 节点;每个节点使用独立密钥"),gpuAgentTimeout:koishi_1.Schema.natural().min(1e4).max(36e5).default(24e4).description("等待 GPU Agent 完成任务的超时(毫秒)"),gpuAgentFallback:koishi_1.Schema.boolean().default(!0).description("GPU Agent 不可用或失败时回退到本地 standalone")}).description("GPU Agent v2")]);const activeStandaloneJavaProcesses=new Set;let standaloneRenderQueue=Promise.resolve();async function acquireStandaloneRenderSlot(){const e=standaloneRenderQueue;let t;return standaloneRenderQueue=new Promise(e=>{t=e}),await e.catch(()=>{}),t}const SUPPORTED_PROXY_PROTOCOLS=new Set(["http:","https:","socks:","socks5:","socks5h:"]);function resolveOfficialProxyUrl(e){if("disabled"===e.officialProxyMode)return;const t="ssh"===e.officialProxyMode?`socks5h://127.0.0.1:${e.sshProxyLocalPort}`:e.officialProxyUrl.trim();if(!t)throw new Error("已开启官方 QQ 中转,但代理地址为空");let i;try{i=new URL(t)}catch{throw new Error(`代理地址格式无效:${t}`)}if(!SUPPORTED_PROXY_PROTOCOLS.has(i.protocol))throw new Error(`不支持的代理协议:${i.protocol}`);return i.href}function buildSshProxyArguments(e){const t=e.sshProxyHost.trim(),i=e.sshProxyUser.trim(),r=e.sshProxyPrivateKey.trim();if(!t)throw new Error("SSH 中转服务器 IP 不能为空");if(!i)throw new Error("SSH 登录用户名不能为空");if(!r&&!e.sshProxyPassword)throw new Error("SSH 私钥和密码至少填写一项");const n=["-NT","-D",`127.0.0.1:${e.sshProxyLocalPort}`,"-p",String(e.sshProxyPort),"-o","BatchMode=yes","-o","ExitOnForwardFailure=yes","-o","ServerAliveInterval=30","-o","ServerAliveCountMax=3","-o","StrictHostKeyChecking=accept-new"];return r&&n.push("-i",(0,node_path_1.resolve)(r)),n.push(`${i}@${t}`),n}function isTcpPortOpen(e,t,i=1e3){return new Promise(r=>{const n=new node_net_1.Socket;let a=!1;const o=e=>{a||(a=!0,n.destroy(),r(e))};n.setTimeout(i),n.once("connect",()=>o(!0)),n.once("timeout",()=>o(!1)),n.once("error",()=>o(!1)),n.connect(t,e)})}function startPasswordSshProxyTunnel(e,t){let i,r,n,a=!1;const o=new Set,s=()=>{a||(i=new ssh2_1.Client,i.once("ready",()=>{!a&&i&&(r=(0,node_net_1.createServer)(e=>{o.add(e),e.once("close",()=>o.delete(e)),handleSocks5Connection(e,i)}),r.once("error",e=>{t.warn(`本地 SOCKS5 监听失败:${e.message}`),i?.end()}),r.listen(e.sshProxyLocalPort,"127.0.0.1",()=>{t.info(`官方 QQ 中转已就绪:socks5h://127.0.0.1:${e.sshProxyLocalPort}`)}))}),i.once("error",e=>t.warn(`SSH 密码登录失败:${e.message}`)),i.once("close",()=>{i=void 0,r?.close(),r=void 0;for(const e of o)e.destroy();a||a||n||(n=setTimeout(()=>{n=void 0,s()},5e3))}),t.info(`正在使用密码建立官方 QQ SSH 中转:${e.sshProxyUser}@${e.sshProxyHost}`),i.connect({host:e.sshProxyHost.trim(),port:e.sshProxyPort,username:e.sshProxyUser.trim(),password:e.sshProxyPassword,keepaliveInterval:3e4,keepaliveCountMax:3,readyTimeout:15e3}))};return s(),()=>{a=!0,n&&clearTimeout(n),r?.close(),i?.end();for(const e of o)e.destroy()}}function handleSocks5Connection(e,t){let i=Buffer.alloc(0),r="greeting";const n=(t=1)=>{"request"===r&&e.write(Buffer.from([5,t,0,1,0,0,0,0,0,0])),e.destroy()};e.on("data",a=>{if(i=Buffer.concat([i,a]),"greeting"===r){if(i.length<2)return;const t=2+i[1];if(i.length<t)return;if(5!==i[0]||!i.subarray(2,t).includes(0))return n();i=i.subarray(t),r="request",e.write(Buffer.from([5,0]))}if("request"!==r||i.length<4)return;if(5!==i[0]||1!==i[1])return n(7);const o=i[3];let s,c;if(1===o){if(i.length<10)return;s=[...i.subarray(4,8)].join("."),c=8}else if(3===o){const e=i[4];if(i.length<7+e)return;s=i.subarray(5,5+e).toString("utf8"),c=5+e}else{if(4!==o)return n(8);{if(i.length<22)return;const e=[];for(let t=4;t<20;t+=2)e.push(i.readUInt16BE(t).toString(16));s=e.join(":"),c=20}}const d=i.readUInt16BE(c);e.pause(),e.removeAllListeners("data"),t.forwardOut("127.0.0.1",0,s,d,(t,i)=>{if(t)return n(5);e.write(Buffer.from([5,0,0,1,0,0,0,0,0,0])),e.pipe(i).pipe(e),e.resume()})}),e.once("error",()=>e.destroy())}function startSshProxyTunnel(e,t){if(buildSshProxyArguments(e),!e.sshProxyPrivateKey.trim())return startPasswordSshProxyTunnel(e,t);const i=e.sshProxyExecutable.trim()||"ssh",r=buildSshProxyArguments(e);let n,a,o=!1;const s=()=>{o||a||(a=setTimeout(()=>{a=void 0,c()},5e3))},c=async()=>{if(o)return;if(await isTcpPortOpen("127.0.0.1",e.sshProxyLocalPort))return void t.info(`官方 QQ 中转已就绪:socks5h://127.0.0.1:${e.sshProxyLocalPort}`);try{await node_fs_1.promises.access((0,node_path_1.resolve)(e.sshProxyPrivateKey),node_fs_1.constants.R_OK)}catch{return t.warn(`SSH 私钥不可读:${(0,node_path_1.resolve)(e.sshProxyPrivateKey)}`),void s()}n=(0,node_child_process_1.spawn)(i,r,{stdio:["ignore","ignore","pipe"],windowsHide:!0});let a="";n.stderr?.on("data",e=>{a=`${a}${e.toString()}`.slice(-2e3)}),n.once("spawn",()=>t.info(`正在建立官方 QQ SSH 中转:${e.sshProxyUser}@${e.sshProxyHost}`)),n.once("error",e=>{t.warn(`SSH 中转启动失败:${e.message}`),s()}),n.once("close",e=>{if(n=void 0,o)return;const i=a.trim().split(/\r?\n/).at(-1);t.warn(`SSH 中转已断开(退出码 ${e??"unknown"})${i?`:${i}`:""}`),s()});for(let i=0;i<20&&n&&!o;i++){if(await isTcpPortOpen("127.0.0.1",e.sshProxyLocalPort,300)){t.info(`官方 QQ 中转已就绪:socks5h://127.0.0.1:${e.sshProxyLocalPort}`);break}await new Promise(e=>setTimeout(e,250))}};return c(),()=>{o=!0,a&&clearTimeout(a),n?.kill()}}async function reloadOfficialQqAdapter(e,t){try{const i=e.loader;if(!i?.entries)return!1;for(const e of i.entries.values())if(e?.config&&"secret"in e.config&&"intents"in e.config&&String(e.name??"").includes("adapter-qq"))return t.warn("官方 QQ 网关看门狗:8 分钟无消息,正在热重载适配器"),await i.reload(e),!0}catch(e){t.warn(`官方 QQ 网关看门狗热重载失败:${e instanceof Error?e.message:String(e)}`)}return!1}function apply(e,t){const i=e.logger(exports.name),r=t.gpuAgentEnabled?new gpu_agent_protocol_1.GpuAgentHub({host:t.gpuAgentListenHost,port:t.gpuAgentListenPort,path:t.gpuAgentPath.startsWith("/")?t.gpuAgentPath:`/${t.gpuAgentPath}`,nodes:t.gpuAgentNodes,heartbeatTimeout:3e4,logger:i}):void 0;r?.start(),r&&e.on("dispose",()=>{r.close()});let n=Promise.resolve();if("official"===t.qqBotType){const r=resolveOfficialProxyUrl(t);if(r){const n=e.root.on("http/config",e=>{e.proxyAgent=r}),a="ssh"===t.officialProxyMode?startSshProxyTunnel(t,i):()=>{};i.info(`官方 QQ 实验性出站代理已启用:${r}`);const o=setInterval(async()=>{try{await e.http.get("https://api.sgroup.qq.com/gateway",{timeout:1e4,responseType:"json"})}catch{}},6e4);let s=Date.now();t.officialGatewayWatchdog&&e.on("message",()=>{s=Date.now()});const c=t.officialGatewayWatchdog?setInterval(()=>{Date.now()-s<=48e4||reloadOfficialQqAdapter(e,i).then(e=>{e&&(s=Date.now())})},6e4):void 0;e.on("dispose",()=>{clearInterval(o),c&&clearInterval(c),n(),a()})}}e.inject(["console"],e=>{const t=(0,node_path_1.resolve)(__dirname,"..");e.console.addEntry({dev:(0,node_path_1.join)(t,"client/index.ts"),prod:(0,node_path_1.join)(t,"dist")}),e.console.addListener("litematic/resource-pack-upload",async(t,i)=>saveUploadedResourcePack(t,i,(0,node_path_1.resolve)(e.baseDir,"data/litematic-resource-packs")),{authority:4})});const a=1024*t.maxFileSize,o=t.sentryDsn||process.env.SENTRY_DSN||"";o&&Sentry.init({dsn:o,tracesSampleRate:1});const s=(e,i)=>{o&&Sentry.withScope(r=>{r.setFingerprint([i]),r.setTag("entrypoint",i),r.setContext("render",{engine:t.renderEngine}),Sentry.captureException(e)})};e.on("dispose",()=>terminateActiveStandaloneJavaProcesses(i)),"selfHosted"===t.qqBotType&&ensureOneBotGroupUploadCompatibility(i,t.patchOneBotGroupUpload);const c=(0,node_path_1.resolve)(stringOrDefault(t.diagnosticsFilePath,"data/litematic-renderer-diagnostics.json")),d=(0,node_path_1.join)((0,node_path_1.dirname)(c),"litematic-renderer-diagnostics-archive"),l=(0,node_path_1.join)((0,node_path_1.dirname)(c),"litematic-renderer-diagnostics-disabled");rotateDiagnosticsFile(c,d,i);const u=(0,node_path_1.resolve)(stringOrDefault(t.cacheDirectory,"data/litematic-renderer-cache")),m=(0,node_path_1.join)(u,`v${cachePathSegment(PLUGIN_VERSION)}`),h=Math.floor(t.cacheMaxSizeGb*1024**3),p=new Map;node_fs_1.promises.mkdir(m,{recursive:!0}).then(()=>enforceCacheLimit(u,h)).catch(e=>i.warn(`缓存初始化失败:${e instanceof Error?e.message:String(e)}`));const f=async(o,s="schematic.litematic",d,l=!1,f,g=a)=>{const _=d??await download(e,o,g,t.renderTimeout),w=parseLitematicMetadata(_);validateProjectionLimits(_,w,t.maxBlocks);const S=formatLitematicMetadata(w,s),y=projectionNameFromFilename(s),v=(0,node_crypto_1.createHash)("sha256").update(_).digest("hex"),x="standalone"===t.renderEngine||"gpuAgent"===t.renderEngine&&t.gpuAgentFallback,b=x?await resolveMinecraftResources(t):"",k=x?await fingerprintFiles([b,...resourcePackPaths(t.resourcePackPaths)]):[],P=hashRenderConfiguration({version:CACHE_FORMAT_VERSION,outputSize:t.outputSize,isometricCellSize:t.isometricCellSize,background:t.background,transparentBackground:t.transparentBackground,gpuRendererCommand:t.gpuRendererCommand,renderEngine:t.renderEngine,standaloneRendererJar:t.standaloneRendererJar,resourceFingerprint:k,javaResolution:t.javaResolution,javaSupersampling:t.javaSupersampling,webglQuality:t.webglQuality,webglWidth:t.webglWidth,webglHeight:t.webglHeight,isometricSquare:t.isometricSquare,isometricFill:t.isometricFill,isometricRotation:t.isometricRotation,isometricSlant:t.isometricSlant,sixFaceLayout:t.sixFaceLayout,gpuAgentFingerprint:"gpuAgent"===t.renderEngine?r?.capabilityFingerprint()??"disabled":void 0}),M=cacheNameSegment(s),E=(0,node_path_1.join)(m,`${M}-${v}-${P}`),R=(0,node_path_1.join)(E,"projection.litematic");await node_fs_1.promises.mkdir(E,{recursive:!0}),await exists(R)||await node_fs_1.promises.writeFile(R,_),await ensureCacheMetadata(E,{pluginVersion:PLUGIN_VERSION,cacheFormatVersion:CACHE_FORMAT_VERSION,contentSha256:v,renderConfigSha256:P,sourceFilename:(0,node_path_1.basename)(s),createdAt:(new Date).toISOString()});const I=["isometric.png","isometric-reverse.png"].map(e=>(0,node_path_1.join)(E,e)),$=async()=>{const e=await Promise.all(I.map(exists));return e.every(Boolean)||"gpuAgent"===t.renderEngine&&e[0]};if(await $())i.debug(`命中投影缓存:${v}`);else{let a=p.get(E);a?i.debug(`等待相同投影的缓存任务:${v}`):(a=(async()=>{try{if(await $())return;if(!Boolean(t.gpuRendererCommand&&await renderWithGpu(t.gpuRendererCommand,R,E,t.renderTimeout,i))||!(await Promise.all(I.map(exists))).every(Boolean))if("standalone"===t.renderEngine)await renderWithStandalone(R,E,b,t,i),await mergeRenderDiagnostics(E,c,i);else if("gpuAgent"===t.renderEngine)try{if(!r)throw new Error("GPU Agent v2 服务未启用");const e=await(e=>{const t=n.then(e,e);return n=t.catch(()=>{}),t})(()=>r.render(createGpuRenderRequest(s,t,f),_,t.gpuAgentTimeout));for(const t of e.images){if("merged"===t.id||"merged.png"===t.name){await node_fs_1.promises.writeFile(I[0],t.png),await node_fs_1.promises.rm(I[1],{force:!0});break}"isometric"===t.id||"isometric.png"===t.name?await node_fs_1.promises.writeFile(I[0],t.png):"isometric-reverse"!==t.id&&"isometric-reverse.png"!==t.name||await node_fs_1.promises.writeFile(I[1],t.png)}}catch(e){if(!t.gpuAgentFallback)throw e;i.warn(`GPU Agent 渲染失败,回退独立 Java:${e instanceof Error?e.message:String(e)}`),await renderWithStandalone(R,E,b,t,i),await mergeRenderDiagnostics(E,c,i)}else if("java"===t.renderEngine)await renderWithJavaBridge(R,E,t);else{const r=parseLitematic(_);let n;if("webgl"===t.renderEngine&&e.puppeteer)try{n=await renderWithWebgl(e,_,t)}catch(e){i.warn(`WebGL 渲染失败,回退 CPU:${e instanceof Error?e.message:String(e)}`),n=renderSchematic(r,t)}else n=renderSchematic(r,t);await Promise.all(n.map(e=>node_fs_1.promises.writeFile((0,node_path_1.join)(E,e.title),e.png)))}if(!await $())throw new Error("渲染器没有生成两张正二轴测 PNG")}catch(e){throw await appendRenderError(E,c,t.renderEngine,e,i),e}})().finally(()=>p.delete(E)),p.set(E,a)),await a}const A=await exists(I[1])?I.map((e,t)=>({title:["正二轴测","反向正二轴测(旋转 180°)"][t],path:e})):[{title:"正二轴测",path:I[0]}];if(l){const e=(0,node_path_1.join)(E,"six-faces.png");if(!await exists(e)){const r=`${E}:six-face`;let n=p.get(r);n||(n=(async()=>{try{if("standalone"===t.renderEngine)try{await renderWithStandalone(R,E,b,t,i,"six-face")}catch(e){i.warn(`真实材质六面图生成失败,回退方块颜色投影:${e instanceof Error?e.message:String(e)}`)}if(!await exists(e)){const i=parseLitematic(_);await node_fs_1.promises.writeFile(e,renderSixFaceOverview(i,t,t.sixFaceLayout))}}catch(e){i.warn(`六面正交图生成失败,继续发送轴测图:${e instanceof Error?e.message:String(e)}`)}})().finally(()=>p.delete(r)),p.set(r,n)),await n}await exists(e)&&A.push({title:"六面正投影",path:e})}return await touchCacheEntry(E),await enforceCacheLimit(u,h,E),{images:A,metadata:S,projectionName:y}};e.middleware(async(e,r)=>{if(!canRenderInSession(e,t.allowPrivateRender))return r();const n=findLitematicFile(e);if(!n)return r();if(!isGroupAllowed(t,e.guildId))return i.info(`群 ${e.guildId} 不在渲染白名单内或已被拉黑,忽略其投影文件`),await e.send([...replyElements(e,t.qqBotType),(0,koishi_1.h)("text",{content:`本群未开启投影渲染。如需开启,请将群 ID ${e.guildId} 加入插件白名单`})]),r();const a=await resolveFileUrl(e,n);if(!a)return i.warn(`检测到 Litematic 文件但无法获取下载地址:${fileName(n)??"unknown.litematic"};请检查 OneBot/NapCat 的 get_group_file_url 接口`),await e.send([...replyElements(e,t.qqBotType),(0,koishi_1.h)("text",{content:"检测到投影文件,但无法获取群文件下载地址,请检查机器人文件接口"})]),r();const o=Boolean(e.isDirect),d=o?t.privateMaxFileSize:t.maxFileSize,l=1024*d;if(isOverLimit(n.size,l))return await appendGlobalRenderError(c,`input:${(0,node_path_1.basename)(fileName(n)??"unknown.litematic")}`,"input",`file size exceeds ${d} KB`,i),await e.send([...replyElements(e,t.qqBotType),(0,koishi_1.h)("text",{content:`文件大小超过 ${(d/1024).toFixed(2)} MB,无法渲染`})]),r();if(!isUnderLimit(n.size,l))return r();try{const i=resolveSendOptions(t,e.guildId),r=await f(a,fileName(n)??"schematic.litematic",void 0,i.sixFaceOverview,{group:e.guildId??void 0,user:e.userId??void 0},l);await sendImages(e,r.images,r.metadata,i,r.projectionName)}catch(n){return s(n,o?"private-file-upload":"group-file-upload"),i.warn(n),await e.send([...replyElements(e,t.qqBotType),(0,koishi_1.h)("text",{content:formatRenderError(n,{maxFileSize:d})})]),r()}return r()}),e.command("litematic.render <url:string>","渲染可直接下载的 .litematic 文件").action(async({session:e},i)=>{if(!i)return"请提供 .litematic 文件的直链";if(!e)return"此命令只能在消息会话中执行";if(!canRenderInSession(e,t.allowPrivateRender))return"单人对话渲染未开启,请在插件发送设置中启用";if(!isGroupAllowed(t,e.guildId))return`本群未开启投影渲染。如需开启,请将群 ID ${e.guildId} 加入插件白名单`;const r=e.isDirect?t.privateMaxFileSize:t.maxFileSize,n=1024*r;try{const r=resolveSendOptions(t,e.guildId),a=await f(i,"schematic.litematic",void 0,r.sixFaceOverview,{group:e.guildId??void 0,user:e.userId??void 0},n);await sendImages(e,a.images,a.metadata,r,a.projectionName)}catch(e){return s(e,"litematic.render"),formatRenderError(e,{maxFileSize:r})}}),e.command("litematic.cache.clear","清理投影渲染缓存",{authority:3}).action(async()=>(await node_fs_1.promises.rm(u,{recursive:!0,force:!0}),await node_fs_1.promises.mkdir(m,{recursive:!0}),"投影渲染缓存已清理")),e.command("litematic.errors.export","export render diagnostics",{authority:3}).action(async()=>`Diagnostics file: ${c}`),e.command("litematic.errors.disable","disable current render diagnostics snapshot",{authority:3}).action(async()=>disableDiagnosticsSnapshot(c,l)),e.command("litematic.proxy.check","检查 Koishi 当前公网出口 IP",{authority:3}).action(async()=>{try{const t=await e.http.get("https://ifconfig.me/ip",{responseType:"text",timeout:1e4,headers:{"User-Agent":"koishi-plugin-litematic-renderer"}});return`当前 Koishi 出口 IP:${String(t).trim()}`}catch(e){return`出口 IP 检查失败:${e instanceof Error?e.message:String(e)}`}});const g=e.server;g?.get&&g.get("/litematic-renderer/diagnostics",async e=>{e.type="application/json",e.set("Content-Disposition",'attachment; filename="litematic-renderer-diagnostics.json"'),e.body=await node_fs_1.promises.readFile(c,"utf8").catch(()=>'{"format":2,"blocks":[],"errors":[]}')})}async function saveUploadedResourcePack(e,t,i){if("string"!=typeof e||!/\.zip$/i.test(e))throw new Error("只允许上传 ZIP 材质包");if("string"!=typeof t||!t.length)throw new Error("材质包内容为空");const r=Buffer.from(t,"base64");if(!r.length)throw new Error("材质包内容为空");if(r.length>RESOURCE_PACK_UPLOAD_LIMIT)throw new Error("材质包超过 256 MB 上传上限");const n=r.readUInt32LE(0);if(![67324752,101010256,134695760].includes(n))throw new Error("文件不是有效的 ZIP 材质包");const a=(0,node_path_1.basename)(e).replace(/\.zip$/i,"").replace(/[<>:"/\\|?*\x00-\x1f]/g,"_").replace(/[. ]+$/g,"").trim()||"resource-pack",o=(0,node_crypto_1.createHash)("sha256").update(r).digest("hex").slice(0,12),s=(0,node_path_1.join)(i,`${a}-${o}.zip`);return await node_fs_1.promises.mkdir(i,{recursive:!0}),await node_fs_1.promises.writeFile(s,r),s.replace(/\\/g,"/")}function hashRenderConfiguration(e){return(0,node_crypto_1.createHash)("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16)}function patchOneBotAdapterSource(e){if(/^\s*case ["']group_upload["']:/m.test(e))return{source:e,changed:!1,alreadyCompatible:!0};const t=e.match(/\(0,\s*(import_[\w$]+)\.hyphenate\)\(data\.sub_type\)/)?.[1]??"import_koishi2",i=/ \/\/ https:\/\/github\.com\/koishijs\/koishi-plugin-adapter-onebot\/issues\/33\r?\n \/\/ case 'offline_file':\r?\n \/\/ session\.elements = \[h\('file', data\.file\)\]\r?\n \/\/ session\.type = 'message'\r?\n \/\/ session\.subtype = 'private'\r?\n \/\/ session\.isDirect = true\r?\n \/\/ session\.subsubtype = 'offline-file-added'\r?\n \/\/ break\r?\n \/\/ case 'group_upload':\r?\n \/\/ session\.elements = \[h\('file', data\.file\)\]\r?\n \/\/ session\.type = 'message'\r?\n \/\/ session\.subtype = 'group'\r?\n \/\/ session\.subsubtype = 'guild-file-added'\r?\n \/\/ break/;if(!i.test(e))return{source:e,changed:!1,alreadyCompatible:!1};const r=[" // Restored by koishi-plugin-litematic-renderer so NapCat group file uploads reach middleware",' case "offline_file":',` session.elements = [(0, ${t}.h)("file", data.file)];`,' session.type = "message";',' session.subtype = "private";'," session.isDirect = true;",' session.subsubtype = "offline-file-added";'," break;",' case "group_upload":',` session.elements = [(0, ${t}.h)("file", data.file)];`,' session.type = "message";',' session.subtype = "group";',' session.subsubtype = "guild-file-added";'," break;"].join("\n");return{source:e.replace(i,r),changed:!0,alreadyCompatible:!1}}async function ensureOneBotGroupUploadCompatibility(e,t){if(!t)return;let i;try{i=require.resolve("koishi-plugin-adapter-onebot/package.json",{paths:[process.cwd(),__dirname]})}catch{return void e.debug("未安装 koishi-plugin-adapter-onebot,跳过群文件上传事件兼容修复")}try{const t=(0,node_path_1.dirname)(i),r=JSON.parse(await node_fs_1.promises.readFile(i,"utf8")),n=(0,node_path_1.join)(t,"lib","index.js"),a=await node_fs_1.promises.readFile(n,"utf8"),o=patchOneBotAdapterSource(a);if(o.alreadyCompatible)return void e.debug(`koishi-plugin-adapter-onebot@${r.version??"unknown"} 已支持 group_upload`);if(!o.changed)return void e.warn(`koishi-plugin-adapter-onebot@${r.version??"unknown"} 未识别到可自动修复的 group_upload 代码段`);const s=`${n}.litematic-renderer.bak`;await exists(s)||await node_fs_1.promises.writeFile(s,a),await node_fs_1.promises.writeFile(n,o.source),e.warn(`已修复 koishi-plugin-adapter-onebot@${r.version??"unknown"} 的群文件上传事件映射;请重启 Koishi 让已加载的 OneBot 适配器生效`)}catch(t){e.warn(`修复 OneBot 群文件上传事件失败:${t instanceof Error?t.message:String(t)}`)}}function cachePathSegment(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")||"unknown"}function cacheNameSegment(e){return((0,node_path_1.basename)(e||"schematic.litematic",(0,node_path_1.extname)(e||"")).replace(/[<>:"/\\|?*\u0000-\u001f]/g,"_").replace(/[. ]+$/g,"").trim()||"schematic").slice(0,80)}function projectionNameFromFilename(e){return(0,node_path_1.basename)(e||"schematic.litematic").replace(/\.litematic$/i,"").trim()||"schematic"}async function ensureCacheMetadata(e,t){const i=(0,node_path_1.join)(e,"cache.json");await exists(i)||await node_fs_1.promises.writeFile(i,JSON.stringify(t,null,2)+"\n")}async function touchCacheEntry(e){const t=new Date;await node_fs_1.promises.utimes(e,t,t).catch(()=>{})}async function directorySize(e){let t=0;const i=await node_fs_1.promises.readdir(e,{withFileTypes:!0}).catch(e=>{if("ENOENT"===e?.code)return[];throw e});for(const r of i){const i=(0,node_path_1.join)(e,r.name);r.isDirectory()?t+=await directorySize(i):r.isFile()&&(t+=(await node_fs_1.promises.stat(i)).size)}return t}async function enforceCacheLimit(e,t,i){const r=[],n=await node_fs_1.promises.readdir(e,{withFileTypes:!0}).catch(e=>{if("ENOENT"===e?.code)return[];throw e});for(const t of n){if(!t.isDirectory())continue;const i=(0,node_path_1.join)(e,t.name),n=await node_fs_1.promises.readdir(i,{withFileTypes:!0});for(const e of n){if(!e.isDirectory())continue;const t=(0,node_path_1.join)(i,e.name),[n,a]=await Promise.all([directorySize(t),node_fs_1.promises.stat(t)]);r.push({path:t,size:n,lastUsed:a.mtimeMs})}}let a=r.reduce((e,t)=>e+t.size,0),o=0,s=0;const c=i&&(0,node_path_1.resolve)(i);r.sort((e,t)=>e.lastUsed-t.lastUsed);for(const e of r){if(a<=t)break;c&&(0,node_path_1.resolve)(e.path)===c||(await node_fs_1.promises.rm(e.path,{recursive:!0,force:!0}),a-=e.size,o+=e.size,s++)}return{totalBytes:a,removedBytes:o,removedEntries:s}}function fileElements(e){return[...e.elements??[],...koishi_1.h.parse(e.content??"")]}function canRenderInSession(e,t){return Boolean(e.guildId)||Boolean(e.isDirect)&&t}function isGroupAllowed(e,t){if(!t)return!0;const i=t.trim();return!i||!e.groupBlacklist.some(e=>e.trim()===i)&&!(e.groupWhitelist.length>0&&!e.groupWhitelist.some(e=>e.trim()===i))}function findLitematicFile(e){const t=fileElements(e).filter(e=>"file"===e.type),i=t.find(e=>".litematic"===(0,node_path_1.extname)(fileName(e.attrs)??"").toLowerCase());if(i?.attrs)return i.attrs;for(const t of[e.event,e._data,e.data,e.message]){const e=findLitematicInFilePayload(t);if(e)return e}const r=inferLitematicName(e.content);return r&&t[0]?.attrs?{...t[0].attrs,name:r}:void 0}function findLitematicInFilePayload(e,t=new Set,i=0){if(!e||"object"!=typeof e||i>6||t.has(e))return;t.add(e);const r=e,n=r,a=n.file&&"object"==typeof n.file?n.file:void 0;if(a&&fileName(a)&&".litematic"===(0,node_path_1.extname)(fileName(a)).toLowerCase())return{...a,id:a.id??n.id,file_id:a.file_id??n.file_id,fileId:a.fileId??n.fileId,busid:a.busid??n.busid};if(fileName(n)&&".litematic"===(0,node_path_1.extname)(fileName(n)).toLowerCase())return n;for(const[e,n]of Object.entries(r))if(n&&"object"==typeof n&&/file|upload|message|data|event/i.test(e)){const e=findLitematicInFilePayload(n,t,i+1);if(e)return e}}function inferLitematicName(e){if(!e)return;const t=e.match(/(?:file|文件)\s+(.+?\.litematic)(?=$|[\]】\r\n])/i);return t?.[1]?t[1].trim():e.match(/([^\s\]】<>"']+\.litematic)(?=$|[\s\]】])/i)?.[1]?.trim()}function fileName(e){const t=e.file&&"object"==typeof e.file?e.file:void 0,i=e.name??e.filename??e.file_name??e.fileName??t?.name??t?.filename??t?.file_name??t?.fileName;return"string"==typeof i&&i.trim()?i.trim():void 0}async function resolveFileUrl(e,t){const i=t.file&&"object"==typeof t.file?t.file:void 0,r=t.url??t.src??("string"==typeof t.file?t.file:void 0)??i?.url??i?.src;if("string"==typeof r&&r)return r;const n=t.id??t.file_id??t.fileId??i?.id??i?.file_id??i?.fileId,a=e.bot.internal;if(!e.guildId||!n||"function"!=typeof a?.getGroupFileUrl)return;const o=await a.getGroupFileUrl(e.guildId,n,Number(t.busid??i?.busid??0));return"string"==typeof o?o:o?.url}function isUnderLimit(e,t){if(null==e||""===e)return!0;const i=Number(e);return Number.isFinite(i)&&i>0&&i<=t}async function download(e,t,i,r){const n=await e.http.get(t,{responseType:"arraybuffer",timeout:r}),a=Buffer.from(n);if(a.byteLength>i)throw new Error(`文件超过 ${(i/1024/1024).toFixed(2)} MB 限制`);return a}async function exists(e){try{return await node_fs_1.promises.access(e,node_fs_1.constants.R_OK),!0}catch{return!1}}function stringOrDefault(e,t){return"string"==typeof e&&e.trim()?e:t}function resourcePackPaths(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e&&Boolean(e.trim())):[]}async function fingerprintFiles(e){return Promise.all(e.filter(e=>"string"==typeof e&&Boolean(e.trim())).map(async e=>{const t=(0,node_path_1.resolve)(e);try{const e=await node_fs_1.promises.stat(t);return{path:t,size:e.size,modified:e.mtimeMs}}catch{return{path:t,missing:!0}}}))}async function resolveStandaloneJavaCommand(e){const t=e.trim();if(t)return t;const i="win32"===process.platform?"java.exe":"java",r=new Set;if(process.env.JAVA_HOME&&r.add((0,node_path_1.join)(process.env.JAVA_HOME,"bin",i)),"win32"===process.platform){const e=new Set([(0,node_path_1.join)(process.env.ProgramFiles??"C:/Program Files","Java"),(0,node_path_1.join)(process.env.ProgramFiles??"C:/Program Files","Eclipse Adoptium"),(0,node_path_1.join)(process.env.ProgramFiles??"C:/Program Files","Microsoft","jdk")]);for(const t of e)try{const e=await node_fs_1.promises.readdir(t,{withFileTypes:!0});for(const n of e)n.isDirectory()&&/(?:^|[-_])21(?:[._-]|$)/.test(n.name)&&r.add((0,node_path_1.join)(t,n.name,"bin",i))}catch{}}r.add("java");for(const e of r)if(supportsStandaloneJavaVersion(await javaMajorVersion(e)))return e;throw new Error("未找到 Java 21+;请安装 Java 21 或更高版本,设置 JAVA_HOME,或填写 standaloneJavaCommand")}function isOverLimit(e,t){if(null==e||""===e)return!1;const i=Number(e);return Number.isFinite(i)&&i>t}async function javaMajorVersion(e){return new Promise(t=>{let i="",r=!1;const n=e=>{r||(r=!0,clearTimeout(s),t(e))},a=(0,node_child_process_1.spawn)(e,["-version"],{shell:!1,windowsHide:!0}),o=e=>{i=(i+String(e)).slice(-2e3)};a.stdout?.on("data",o),a.stderr?.on("data",o),a.once("error",()=>n()),a.once("close",()=>{const e=i.match(/(?:java|openjdk) version "(\d+)/i);n(e?Number(e[1]):void 0)});const s=setTimeout(()=>{a.kill(),n()},5e3)})}function supportsStandaloneJavaVersion(e){return void 0!==e&&e>=21}function standaloneJvmOptions(e){return["-Xms128m",`-Xmx${Math.max(128,Math.min(32768,Math.floor(e)))}m`,"-XX:+UseG1GC","-XX:+UseStringDeduplication","-XX:+ExitOnOutOfMemoryError"]}function isJavaMemoryFailure(e,t){return 137===t||/outofmemoryerror|java heap space|gc overhead limit|cannot reserve enough space|native memory allocation|insufficient memory|malloc failed|os::commit_memory/i.test(e)}async function resolveMinecraftResources(e){const t="string"==typeof e.minecraftJarPath?e.minecraftJarPath.trim():"";if(t&&await exists((0,node_path_1.resolve)(t)))return(0,node_path_1.resolve)(t);const i=(0,node_path_1.resolve)((0,node_path_1.join)(__dirname,"../assets/vanilla-resources/Minecraft-26.2-Vanilla-Resources.zip"));if(!await exists(i))throw new Error(`插件内置的 Minecraft 26.2 原版资源包不存在:${i}`);return i}async function renderWithStandalone(e,t,i,r,n,a="isometric"){const o=await acquireStandaloneRenderSlot();try{const o=(0,node_path_1.resolve)(r.standaloneRendererJar||(0,node_path_1.join)(__dirname,"../assets/standalone-renderer/litematic-standalone-renderer-0.2.8-patch.1.jar"));if(!await exists(o))throw new Error(`独立 Java 渲染器不存在:${o}`);if(!await exists(i))throw new Error(`Minecraft 资源 JAR 不存在:${i}`);for(const e of resourcePackPaths(r.resourcePackPaths))if(!await exists((0,node_path_1.resolve)(e)))throw new Error(`材质包不存在:${e}`);const s=["-Djava.awt.headless=true","-jar",o,"--input",(0,node_path_1.resolve)(e),"--output",(0,node_path_1.resolve)(t),"--minecraft-jar",i,"--resolution",String(r.javaResolution),"--supersampling",String(r.javaSupersampling),"--rotation",String(r.isometricRotation),"--slant",String(r.isometricSlant),"--fill",String(r.isometricFill),"--background",r.background];"six-face"===a&&s.push("--six-face-only","--six-face-resolution",String(r.outputSize),"--six-face-layout",r.sixFaceLayout),r.transparentBackground&&s.push("--transparent-background");for(const e of resourcePackPaths(r.resourcePackPaths))s.push("--resource-pack",(0,node_path_1.resolve)(e));const c=await resolveStandaloneJavaCommand(r.standaloneJavaCommand);for(let e=0;e<=r.standaloneJavaMemoryRestartLimit;e++){const i=0===e?r.standaloneJavaMaxHeapMb:r.standaloneJavaRetryMaxHeapMb,o=await runStandaloneJava(c,[...standaloneJvmOptions(i),...s],r.standaloneRenderTimeout);if(0===o.code)return;const d=isJavaMemoryFailure(o.stderr,o.code);if(d&&e<r.standaloneJavaMemoryRestartLimit){n.warn(`独立 Java 渲染超出 ${r.standaloneJavaMaxHeapMb} MiB 堆内存限制;正在启动全新进程重试(${e+1}/${r.standaloneJavaMemoryRestartLimit})`);const i="six-face"===a?["six-faces.png"]:["isometric.png","isometric-reverse.png"];await Promise.all(i.map(e=>node_fs_1.promises.rm((0,node_path_1.join)(t,e),{force:!0})));continue}const l=d?`;Java 内存不足(最大堆 ${r.standaloneJavaMaxHeapMb} MiB,已重启 ${e} 次)`:"";throw new Error(`独立 Java 渲染器退出码 ${o.code}${l}${o.stderr?`:${o.stderr.trim()}`:""}`)}}finally{o()}}async function runStandaloneJava(e,t,i){return new Promise((r,n)=>{const a=(0,node_child_process_1.spawn)(e,t,{shell:!1,windowsHide:!0});activeStandaloneJavaProcesses.add(a);let o="",s=!1;const c=()=>activeStandaloneJavaProcesses.delete(a);a.stderr?.on("data",e=>{o=(o+String(e)).slice(-6e3)});const d=setTimeout(()=>{s||(s=!0,(async()=>{await terminateStandaloneJavaProcess(a),c(),n(new Error("Standalone Java render timed out; process terminated and memory reclaimed"))})())},i);a.once("error",e=>{s||(s=!0,clearTimeout(d),terminateStandaloneJavaProcess(a),c(),n(e))}),a.once("close",e=>{s||(s=!0,clearTimeout(d),c(),r({code:e,stderr:o}))})})}async function terminateStandaloneJavaProcess(e){const t=e.pid;t&&("win32"===process.platform&&await new Promise(e=>{const i=(0,node_child_process_1.spawn)("taskkill.exe",["/PID",String(t),"/T","/F"],{windowsHide:!0});i.once("close",()=>e()),i.once("error",()=>e())}),null!=e.exitCode||e.killed||e.kill())}async function terminateActiveStandaloneJavaProcesses(e){const t=[...activeStandaloneJavaProcesses];t.length&&(await Promise.all(t.map(e=>terminateStandaloneJavaProcess(e))),e.info(`已终止 ${t.length} 个独立渲染 Java 进程并回收其子进程`))}function createGpuRenderRequest(e,t,i){const r=Math.max(128,Math.min(4096,Math.floor(t.outputSize))),n=(e,i,n)=>({id:e,name:i,yaw:n,pitch:t.isometricSlant,zoom:Math.max(.05,t.isometricFill/.95),autoFill:!0,width:r,height:r,background:t.background,transparentBackground:t.transparentBackground,supersampling:Math.max(1,Math.min(4,Math.floor(t.javaSupersampling)))});return{version:2,id:(0,node_crypto_1.randomUUID)(),filename:(0,node_path_1.basename)(e),views:[n("isometric","正二轴测",t.isometricRotation),n("isometric-reverse","反向正二轴测(旋转 180°)",t.isometricRotation+180)],sourceGroup:i?.group,sourceUser:i?.user}}async function renderWithJavaBridge(e,t,i){if(!i.javaBridgeDirectory.trim())throw new Error("Fabric Java 渲染桥任务目录未配置;使用 java 后端时请填写 javaBridgeDirectory");const r=(0,node_path_1.resolve)(i.javaBridgeDirectory),n=await readJson((0,node_path_1.join)(r,"status.json"));if(!n?.timestamp||Date.now()-n.timestamp>5e3)throw new Error("Minecraft Java 渲染桥未运行;请启动 1.21.1-Fabric 客户端并进入一个世界");if(!n.inWorld)throw new Error("Minecraft Java 渲染桥已启动,但客户端尚未进入世界");const a=n.resourcePacks??[];if(![["XeKr","3.6forMC1.20.2~1.21.5.zip"],["XKRDA","1.19.4~1.21snapshot.zip"]].every(e=>a.some(t=>e.every(e=>t.includes(e)))))throw new Error("Minecraft 客户端没有同时启用 XeKr 红显基础包和 XKRDA 附加包");const o=(0,node_crypto_1.randomUUID)(),s=(0,node_path_1.join)(r,"jobs"),c=(0,node_path_1.join)(r,"results",`${o}.result.json`),d=(0,node_path_1.join)(s,`${o}.job.json`),l=`${d}.tmp`;await node_fs_1.promises.mkdir(s,{recursive:!0}),await node_fs_1.promises.rm(c,{force:!0}),await node_fs_1.promises.writeFile(l,JSON.stringify({id:o,input:(0,node_path_1.resolve)(e),outputDirectory:(0,node_path_1.resolve)(t),resolution:i.javaResolution,supersampling:i.javaSupersampling,rotation:i.isometricRotation,slant:i.isometricSlant,fill:i.isometricFill,background:i.background,transparentBackground:i.transparentBackground})),await node_fs_1.promises.rename(l,d);const u=Date.now()+i.javaRenderTimeout;for(;Date.now()<u;){const e=await readJson(c);if(e){if(await node_fs_1.promises.rm(c,{force:!0}),!e.success)throw new Error(`Minecraft Java 渲染失败:${e.error??"未知错误"}`);return}await new Promise(e=>setTimeout(e,200))}throw new Error(`Minecraft Java 渲染超过 ${Math.round(i.javaRenderTimeout/1e3)} 秒`)}async function readJson(e){try{return JSON.parse(await node_fs_1.promises.readFile(e,"utf8"))}catch(e){if("ENOENT"===e?.code||e instanceof SyntaxError)return;throw e}}async function mergeRenderDiagnostics(e,t,i){const r=(0,node_path_1.join)(e,"render-diagnostics.json"),n=await readJson(r);if(!n)return;const a=Array.isArray(n.blocks)?n.blocks:[],o=Array.isArray(n.errors)?n.errors:[];if(!a.length&&!o.length)return;const s=(0,node_path_1.resolve)(t),c=await readJson(s)??{format:2,generatedAt:(new Date).toISOString(),blocks:[],errors:[]},d=new Map;for(const e of c.blocks??[])d.set(`${e.state}\0${e.reason}`,e);for(const e of a){const t=`${e.state}\0${e.reason}`,i=d.get(t);i?(i.count=Number(i.count??0)+Number(e.count??0),i.samples=[...i.samples??[],...e.samples??[]].slice(0,20)):d.set(t,{...e,samples:e.samples??[]})}const l=new Map;for(const e of c.errors??[])l.set(`${e.renderId}\0${e.engine}\0${e.message}`,e);for(const e of o){const t=`${e.renderId}\0${e.engine}\0${e.message}`,i=l.get(t);i?i.count=Number(i.count??0)+Number(e.count??0):l.set(t,{...e})}const u={format:2,pluginVersion:PLUGIN_VERSION,generatedAt:(new Date).toISOString(),blocks:[...d.values()],errors:[...l.values()]};await node_fs_1.promises.mkdir((0,node_path_1.resolve)(t,".."),{recursive:!0}).catch(()=>{}),await node_fs_1.promises.writeFile(s,JSON.stringify(u,null,2)+"\n"),a.length&&i.warn(`记录 ${a.length} 类无法正常渲染的方块;诊断已保存到 ${s}`),o.length&&i.warn(`记录 ${o.length} 类渲染错误;诊断已保存到 ${s}`)}async function rotateDiagnosticsFile(e,t,i){const r=await readJson(e);if(!r||r.pluginVersion===PLUGIN_VERSION)return;await node_fs_1.promises.mkdir(t,{recursive:!0});const n=cachePathSegment("string"==typeof r.pluginVersion?r.pluginVersion:"legacy"),a=formatDiagnosticsTimestamp(new Date),o=(0,node_path_1.join)(t,`litematic-renderer-diagnostics-v${n}-${a}.json`);await node_fs_1.promises.rename(e,o),i.info(`已将旧版诊断汇总归档到 ${o}`)}async function disableDiagnosticsSnapshot(e,t){if(!await readJson(e))return"当前没有可禁用的诊断汇总";await node_fs_1.promises.mkdir(t,{recursive:!0});const i=(0,node_path_1.join)(t,`litematic-renderer-diagnostics-disabled-${formatDiagnosticsTimestamp(new Date)}.json`);return await node_fs_1.promises.rename(e,i),await node_fs_1.promises.writeFile(e,JSON.stringify({format:2,pluginVersion:PLUGIN_VERSION,generatedAt:(new Date).toISOString(),blocks:[],errors:[]},null,2)+"\n"),`当前诊断已移入禁用文件夹:${i}`}async function appendGlobalRenderError(e,t,i,r,n){const a=(0,node_path_1.resolve)(e),o=await readJson(a)??{format:2,pluginVersion:PLUGIN_VERSION,generatedAt:(new Date).toISOString(),blocks:[],errors:[]};o.format=2,o.pluginVersion=PLUGIN_VERSION,o.errors??=[];const s=o.errors.find(e=>e.renderId===t&&e.engine===i&&e.message===r);s?s.count=Number(s.count??0)+1:o.errors.push({renderId:t,engine:i,message:r,count:1,generatedAt:(new Date).toISOString()}),await node_fs_1.promises.mkdir((0,node_path_1.dirname)(a),{recursive:!0}),await node_fs_1.promises.writeFile(a,JSON.stringify(o,null,2)+"\n"),n.warn(`渲染问题已记录到 ${a}`)}function formatDiagnosticsTimestamp(e){const t=e=>String(e).padStart(2,"0");return`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}`}async function appendRenderError(e,t,i,r,n){const a=(0,node_path_1.join)(e,"render-diagnostics.json"),o=await readJson(a)??{format:2,generatedAt:(new Date).toISOString(),blocks:[],errors:[]};o.format=2,o.errors??=[];const s=r instanceof Error?r.message:String(r),c=(0,node_path_1.basename)(e),d=o.errors.find(e=>e.renderId===c&&e.engine===i&&e.message===s);d?d.count=Number(d.count??0)+1:o.errors.push({renderId:c,engine:i,message:s,count:1,generatedAt:(new Date).toISOString()}),await node_fs_1.promises.writeFile(a,JSON.stringify(o,null,2)+"\n"),await mergeRenderDiagnostics(e,t,n)}function formatRenderError(e,t){const i=e instanceof Error?e.message:String(e);return/投影方块数或区域体积超过/i.test(i)?`${i},不渲染`:/文件超过|file size|file.*limit/i.test(i)?`文件大小超过 ${(t.maxFileSize/1024).toFixed(2)} MB,不渲染`:/java 21\+|未找到.*java|java.*not found/i.test(i)?"未找到 Java 21+,请在插件配置中检查 Java 可执行文件设置":/standalone renderer|独立.*渲染器.*不存在|渲染器.*not exist/i.test(i)?"独立渲染器不可用,请重装插件或检查 Java 渲染配置":/minecraft.*resource|resource pack|原版资源|材质包.*不存在/i.test(i)?"Minecraft 原版资源包不可用,请检查资源包配置":"投影渲染失败,请检查渲染器配置或导出诊断文件"}async function renderWithGpu(e,t,i,r,n){try{return await new Promise((n,a)=>{const o=(0,node_child_process_1.spawn)(e,["--input",t,"--output",i,"--views","isometric,isometric-reverse"],{shell:!1,windowsHide:!0}),s=setTimeout(()=>{o.kill(),a(new Error("GPU 渲染超时"))},r);o.once("error",a),o.once("exit",e=>0===e?n():a(new Error(`GPU 渲染器退出码:${e}`))),o.once("close",()=>clearTimeout(s))}),!0}catch(e){return n.warn(`GPU 渲染器不可用,回退 CPU:${e instanceof Error?e.message:String(e)}`),!1}}async function renderWithWebgl(e,t,i){const r=await e.puppeteer.page();try{const e=(0,node_url_1.pathToFileURL)((0,node_path_1.resolve)(__dirname,"../assets/threeviews/index.html")).href;await r.goto(e,{waitUntil:"networkidle0",timeout:i.renderTimeout}),await r.waitForFunction(()=>Boolean(window.litematicViewerAPI&&window.deepslateResources),{timeout:i.renderTimeout});const n=await r.evaluate(async({base64:e,width:t,height:i,quality:r,isometricSquare:n,isometricFill:a,isometricRotation:o,isometricSlant:s})=>{const c=atob(e),d=new Uint8Array(c.length);for(let e=0;e<c.length;e++)d[e]=c.charCodeAt(e);const l=new File([d],"schematic.litematic",{type:"application/octet-stream"});return await window.litematicViewerAPI.loadFromFile(l),window.litematicViewerAPI.renderIsometricViews({width:t,height:i,quality:r,isometricSquare:n,isometricFill:a,isometricRotation:o,isometricSlant:s})},{base64:t.toString("base64"),width:i.webglWidth,height:i.webglHeight,quality:i.webglQuality,isometricSquare:i.isometricSquare,isometricFill:i.isometricFill,isometricRotation:i.isometricRotation,isometricSlant:i.isometricSlant});return[{title:"isometric.png",png:decodeDataUrl(n.isometricView)},{title:"isometric-reverse.png",png:decodeDataUrl(n.reverseIsometricView)}]}finally{await r.close().catch(()=>{})}}function decodeDataUrl(e){if("string"!=typeof e||!e.startsWith("data:image/"))throw new Error("WebGL 渲染器没有返回 PNG 数据");const t=e.indexOf(",");if(t<0)throw new Error("WebGL 渲染器返回了无效图像数据");return Buffer.from(e.slice(t+1),"base64")}function resolveSendOptions(e,t){const i=t?[...e.groupSendOptions].reverse().find(e=>e.groupId.trim()===t):void 0,r="enabled"===i?.replyAndMention||"disabled"!==i?.replyAndMention&&e.replyAndMention,n=i?.sendMode??(e.sendAsForward?"forward":"combined"),a=e.qqBotType??"selfHosted";return{qqBotType:a,sendMode:n,replyAndMention:r,showViewTitles:e.showViewTitles??!1,sixFaceOverview:("official"===a||"forward"===n)&&(e.sixFaceOverview??!0)}}async function sendImages(e,t,i,r,n="schematic"){if("official"===r.qqBotType){const a=await composeQqOverview(t),o=[...r.replyAndMention&&e.messageId?[(0,koishi_1.h)("quote",{id:e.messageId})]:[],koishi_1.h.image((0,node_url_1.pathToFileURL)(a).href),(0,koishi_1.h)("text",{content:`${i}\n${n} 已渲染成功,结果如上`})];return void await e.send(o)}const a=await Promise.all(t.map(async({title:e,path:t})=>({title:e,source:`base64://${(await node_fs_1.promises.readFile(t)).toString("base64")}`}))),o=a.map(({title:t,source:i})=>(0,koishi_1.h)("message",{userId:e.selfId,nickname:"投影渲染"},[...r.showViewTitles?[(0,koishi_1.h)("text",{content:t})]:[],(0,koishi_1.h)("img",{src:i})])),s=(0,koishi_1.h)("message",{userId:e.selfId,nickname:"投影信息"},[(0,koishi_1.h)("text",{content:i})]);if("forward"===r.sendMode)return void await e.send((0,koishi_1.h)("figure",{},[...o,s]));const c=r.replyAndMention?replyElements(e,r.qqBotType):[],d=a.flatMap(({title:e,source:t},i)=>[...r.showViewTitles?[(0,koishi_1.h)("text",{content:`${i?"\n":""}${e}\n`})]:[],(0,koishi_1.h)("img",{src:t})]);await e.send([...c,...d,(0,koishi_1.h)("text",{content:`\n${i}\n${n} 已渲染成功,结果如上`})])}async function composeQqOverview(e){if(!e.length)throw new Error("没有可合并的渲染图片");const t=await Promise.all(e.map(async e=>pngjs_1.PNG.sync.read(await node_fs_1.promises.readFile((0,node_path_1.resolve)(e.path))))),i=Math.max(...t.map(e=>e.width)),r=Math.max(4,Math.round(.01*i)),n=[];let a=0;const o=t.slice(0,Math.min(2,t.length)),s=1===o.length?i:Math.floor((i-r)/2),c=o.map(e=>Math.max(1,Math.round(e.height*s/e.width))),d=Math.max(...c);for(let e=0;e<o.length;e++)n.push({image:o[e],x:e*(s+r),y:Math.floor((d-c[e])/2),width:s,height:c[e]});a+=d;for(const e of t.slice(2)){a+=r;const t=Math.max(1,Math.round(e.height*i/e.width));n.push({image:e,x:0,y:a,width:i,height:t}),a+=t}const l=new pngjs_1.PNG({width:i,height:a});for(const e of n)drawScaledPng(l,e);const u=(0,node_path_1.resolve)((0,node_path_1.dirname)(e[0].path),"qq-overview.png");return await node_fs_1.promises.writeFile(u,pngjs_1.PNG.sync.write(l)),u}function drawScaledPng(e,t){const{image:i,x:r,y:n,width:a,height:o}=t;for(let t=0;t<o;t++){const s=Math.min(i.height-1,Math.floor((t+.5)*i.height/o));for(let o=0;o<a;o++){const c=Math.min(i.width-1,Math.floor((o+.5)*i.width/a)),d=4*(s*i.width+c),l=4*((n+t)*e.width+r+o);i.data.copy(e.data,l,d,d+4)}}}function replyElements(e,t=("qq"===e.platform?"official":"selfHosted")){const i=[];return e.messageId&&i.push((0,koishi_1.h)("quote",{id:e.messageId})),"selfHosted"===t&&e.userId&&(i.push((0,koishi_1.h)("at",{id:e.userId})),i.push((0,koishi_1.h)("text",{content:"\n"}))),i}class NbtReader{data;offset=0;constructor(e){this.data=e}byte(){return this.data.readInt8(this.offset++)}ubyte(){return this.data.readUInt8(this.offset++)}short(){const e=this.data.readInt16BE(this.offset);return this.offset+=2,e}int(){const e=this.data.readInt32BE(this.offset);return this.offset+=4,e}float(){const e=this.data.readFloatBE(this.offset);return this.offset+=4,e}double(){const e=this.data.readDoubleBE(this.offset);return this.offset+=8,e}long(){const e=this.data.readBigInt64BE(this.offset);return this.offset+=8,e}text(){const e=this.data.readUInt16BE(this.offset);this.offset+=2;const t=this.data.toString("utf8",this.offset,this.offset+e);return this.offset+=e,t}readNamedRoot(){if(10!==this.ubyte())throw new Error("不是 NBT Compound 数据");return this.text(),this.value(10)}value(e){switch(e){case 0:return null;case 1:return this.byte();case 2:return this.short();case 3:return this.int();case 4:return this.long();case 5:return this.float();case 6:return this.double();case 7:{const e=this.int(),t=this.data.subarray(this.offset,this.offset+e);return this.offset+=e,t}case 8:return this.text();case 9:{const e=this.ubyte(),t=this.int();return Array.from({length:t},()=>this.value(e))}case 10:{const e={};for(;;){const t=this.ubyte();if(!t)return e;e[this.text()]=this.value(t)}}case 11:{const e=this.int();return Array.from({length:e},()=>this.int())}case 12:{const e=this.int();return Array.from({length:e},()=>this.long())}default:throw new Error(`不支持的 NBT 标签类型:${e}`)}}}const MINECRAFT_DATA_VERSIONS=new Map([[4903,"26.2"],[4790,"26.1.2"],[4671,"1.21.11"],[4557,"1.21.10"],[4555,"1.21.9"],[4440,"1.21.8"],[4438,"1.21.7"],[4435,"1.21.6"],[4325,"1.21.5"],[4189,"1.21.4"],[4082,"1.21.3"],[4080,"1.21.2"],[3955,"1.21.1"],[3953,"1.21"],[3839,"1.20.6"],[3837,"1.20.5"],[3700,"1.20.4"],[3698,"1.20.3"],[3578,"1.20.2"],[3465,"1.20.1"],[3463,"1.20"],[3337,"1.19.4"],[3218,"1.19.3"],[3120,"1.19.2"],[3117,"1.19.1"],[3105,"1.19"],[2975,"1.18.2"]]);function readLitematicRoot(e){let t;try{t=(0,node_zlib_1.gunzipSync)(e)}catch{t=e}return new NbtReader(t).readNamedRoot()}function compoundValue(e){return!e||"object"!=typeof e||Array.isArray(e)||Buffer.isBuffer(e)?void 0:e}function numericValue(e){if("number"==typeof e&&Number.isFinite(e))return e;if("bigint"==typeof e){const t=Number(e);if(Number.isSafeInteger(t))return t}}function readMetadataSize(e,t){const i=compoundValue(t.EnclosingSize),r=i&&[numericValue(i.x),numericValue(i.y),numericValue(i.z)];if(r?.every(e=>null!=e))return r.map(e=>Math.abs(e));const n=compoundValue(e.Regions);if(!n)return;let a=1/0,o=1/0,s=1/0,c=-1/0,d=-1/0,l=-1/0;for(const e of Object.values(n)){const t=compoundValue(e),i=compoundValue(t?.Position),r=compoundValue(t?.Size),n=numericValue(i?.x),u=numericValue(i?.y),m=numericValue(i?.z),h=numericValue(r?.x),p=numericValue(r?.y),f=numericValue(r?.z);if([n,u,m,h,p,f].some(e=>null==e)||0===h||0===p||0===f)continue;const g=n+h-Math.sign(h),_=u+p-Math.sign(p),w=m+f-Math.sign(f);a=Math.min(a,n,g),o=Math.min(o,u,_),s=Math.min(s,m,w),c=Math.max(c,n,g),d=Math.max(d,u,_),l=Math.max(l,m,w)}return Number.isFinite(a)?[c-a+1,d-o+1,l-s+1]:void 0}function formatCreatedAt(e){if(null==e||e<=0)return"未知";const t=new Date(e<1e10?1e3*e:e);if(Number.isNaN(t.getTime()))return"未知";const i=new Intl.DateTimeFormat("zh-CN",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(t),r=Object.fromEntries(i.map(e=>[e.type,e.value]));return`${r.year}-${r.month}-${r.day} ${r.hour}:${r.minute}:${r.second}`}function parseLitematicMetadata(e){const t=readLitematicRoot(e),i=compoundValue(t.Metadata)??{},r=numericValue(t.MinecraftDataVersion);return{author:"string"==typeof i.Author&&i.Author.trim()?i.Author.trim():"未知",createdAt:formatCreatedAt(numericValue(i.TimeCreated)),totalBlocks:numericValue(i.TotalBlocks),totalVolume:numericValue(i.TotalVolume),size:readMetadataSize(t,i),litematicVersion:numericValue(t.Version),minecraftDataVersion:r,minecraftVersion:null==r?void 0:MINECRAFT_DATA_VERSIONS.get(r)}}function validateProjectionLimits(e,t,i){const r=Number.isSafeInteger(i)&&i>0?i:5e6,n=()=>{throw new Error(`投影方块数或区域体积超过 ${r.toLocaleString("en-US")} 限制`)};(Math.abs(t.totalBlocks??0)>r||Math.abs(t.totalVolume??0)>r)&&n();const a=compoundValue(readLitematicRoot(e).Regions);if(!a)return;let o=0;for(const e of Object.values(a)){const t=compoundValue(compoundValue(e)?.Size),i=[numericValue(t?.x),numericValue(t?.y),numericValue(t?.z)];if(i.some(e=>null==e))continue;const a=i.reduce((e,t)=>e*Math.abs(t),1);(!Number.isSafeInteger(a)||a>r-o)&&n(),o+=a}}function formatLitematicMetadata(e,t){const i=null==e.totalBlocks?"未知":String(e.totalBlocks),r=null==e.totalVolume?"未知":String(e.totalVolume),n=e.size?.join(" × ")??"未知",a=null==e.litematicVersion?"未知":String(e.litematicVersion),o=e.minecraftVersion??"未知",s=null==e.minecraftDataVersion?"":`(数据版本:${e.minecraftDataVersion})`,c="string"==typeof t&&t.trim()?(0,node_path_1.basename)(t).replace(/\.litematic$/i,""):"";return[...c?[`投影名称:${c}`]:[],`保存者游戏 ID:${e.author}`,`创建时间:${e.createdAt}`,`方块数/体积:${i}/${r}`,`尺寸:${n}`,`Litematic 版本:${a}`,`游戏版本:${o}${s}`].join("\n")}function parseLitematic(e){const t=readLitematicRoot(e).Regions;if(!t||"object"!=typeof t)throw new Error("文件不含 Litematica Regions 数据");const i=[];for(const e of Object.values(t))parseRegion(e,i);if(!i.length)throw new Error("投影中没有非空气方块");return i}function parseRegion(e,t){const i=e.Position,r=e.Size,n=e.BlockStatePalette,a=e.BlockStates;if(!(i&&r&&Array.isArray(n)&&Array.isArray(a)))return;const o=Math.abs(r.x),s=Math.abs(r.y),c=Math.abs(r.z),d=o*s*c;if(!d)return;const l=Math.max(2,Math.ceil(Math.log2(n.length))),u=r.x<0?-1:1,m=r.y<0?-1:1,h=r.z<0?-1:1;for(let e=0;e<d;e++){const r=unpackState(a,e,l),s=n[r]?.Name;if(!s||"minecraft:air"===s||"minecraft:cave_air"===s||"minecraft:void_air"===s)continue;const d=e%o,p=Math.floor(e/o)%c,f=Math.floor(e/(o*c));t.push({x:i.x+d*u,y:i.y+f*m,z:i.z+p*h,name:s})}}function unpackState(e,t,i){const r=BigInt(t*i),n=Number(r/64n),a=r%64n;if(n>=e.length)return 0;const o=(1n<<BigInt(i))-1n;let s=BigInt.asUintN(64,e[n])>>a&o;return a+BigInt(i)>64n&&n+1<e.length&&(s|=BigInt.asUintN(64,e[n+1])<<64n-a&o),Number(s)}function renderSchematic(e,t){const i=getBounds(e);return[{title:"isometric.png",png:renderIsometric(e,i,t,!1)},{title:"isometric-reverse.png",png:renderIsometric(e,i,t,!0)}]}function getBounds(e){return e.reduce((e,t)=>({minX:Math.min(e.minX,t.x),minY:Math.min(e.minY,t.y),minZ:Math.min(e.minZ,t.z),maxX:Math.max(e.maxX,t.x),maxY:Math.max(e.maxY,t.y),maxZ:Math.max(e.maxZ,t.z)}),{minX:1/0,minY:1/0,minZ:1/0,maxX:-1/0,maxY:-1/0,maxZ:-1/0})}const SIX_FACE_ORDER=["up","down","east","south","west","north"],SIX_FACE_LABELS={up:["00000100000","00000100000","00000100000","00000100000","00000111110","00000100000","00000100000","00000100000","00000100000","00000100000","11111111111"],down:["00000000000","11111111111","00000100000","00000100000","00000110000","00000101000","00000100100","00000100100","00000100000","00000100000","00000100000"],east:["00000100000","00000100000","01111111111","00001010000","00010010000","00111111110","00000010000","00010010100","00100010010","01000010001","00001110000"],south:["00000100000","11111111111","00000100000","01111111110","01010001010","01001010010","01111111110","01000100010","01111111110","01000100010","01000100110"],west:["00000000000","11111111111","00001010000","01111111110","01001010010","01001010010","01010010010","01100001110","01000000010","01111111110","01000000010"],north:["00010010000","00010010000","00010010000","11110010011","00010011100","00010010000","00010010000","00110010000","01010010001","10010010001","00010001111"]};function renderSixFaceOverview(e,t,i=t.sixFaceLayout??"horizontal"){if(!e.length)throw new Error("投影中没有可生成六面图的方块");const r=Math.max(128,Math.floor(t.outputSize)),n=Math.max(4,Math.round(.01*r)),a="vertical"===i?2:3,o="vertical"===i?3:2,s=Math.floor((r-n*("vertical"===i?o+1:a+1))/("vertical"===i?o:a)),c=new Raster("vertical"===i?a*s+n*(a+1):r,"vertical"===i?r:o*s+n*(o+1),t),d=getBounds(e);for(const[t,i]of SIX_FACE_ORDER.entries()){const r=n+t%a*(s+n),o=n+Math.floor(t/a)*(s+n);drawOrthographicFace(c,e,d,i,r,o,s,n),drawFaceLabel(c,i,r,o,s,n)}return c.png()}function drawOrthographicFace(e,t,i,r,n,a,o,s){const c="east"===r||"west"===r?i.maxZ-i.minZ+1:i.maxX-i.minX+1,d="up"===r||"down"===r?i.maxZ-i.minZ+1:i.maxY-i.minY+1,l=new Map;for(const e of t){const t=orthographicCoordinates(e,i,r),n=`${t.a},${t.b}`,a=l.get(n);(!a||t.depth>a.depth)&&l.set(n,{block:e,...t})}const u=Math.max(2,Math.floor(s/2)),m=Math.max(1,o-2*u),h=Math.min(m/c,m/d),p=n+u+(m-c*h)/2,f=a+u+(m-d*h)/2;for(const{block:t,a:i,b:r}of[...l.values()].sort((e,t)=>e.b-t.b||e.a-t.a)){const n=Math.floor(p+i*h),a=Math.floor(f+r*h),o=Math.max(n+1,Math.ceil(p+(i+1)*h)),s=Math.max(a+1,Math.ceil(f+(r+1)*h));e.rect(n,a,o-n,s-a,colorFor(t.name))}}function orthographicCoordinates(e,t,i){switch(i){case"up":return{a:e.x-t.minX,b:e.z-t.minZ,depth:e.y};case"down":return{a:t.maxX-e.x,b:e.z-t.minZ,depth:-e.y};case"east":return{a:t.maxZ-e.z,b:t.maxY-e.y,depth:e.x};case"south":return{a:e.x-t.minX,b:t.maxY-e.y,depth:e.z};case"west":return{a:e.z-t.minZ,b:t.maxY-e.y,depth:-e.x};case"north":return{a:t.maxX-e.x,b:t.maxY-e.y,depth:-e.z}}}function drawFaceLabel(e,t,i,r,n,a){const o=SIX_FACE_LABELS[t],s=Math.max(1,Math.min(6,Math.floor(n/80))),c=Math.max(1,Math.floor(s/2)),d=i+Math.max(2,Math.floor(a/2)),l=r+Math.max(2,Math.floor(a/2));e.rect(d,l,o[0].length*s+2*c,o.length*s+2*c,"#000000");for(let t=0;t<o.length;t++)for(let i=0;i<o[t].length;i++)"1"===o[t][i]&&e.rect(d+c+i*s,l+c+t*s,s,s,"#ffffff")}function renderIsometric(e,t,i,r){const n=i.isometricCellSize,a=Math.ceil(n/2),o=(t.maxX-t.minX+t.maxZ-t.minZ+2)*n+4,s=(t.maxX-t.minX+t.maxZ-t.minZ+2)*a+(t.maxY-t.minY+2)*n+4,c=Math.max(1,Math.min(1,i.outputSize/Math.max(o,s))),d=new Raster(Math.ceil(o*c),Math.ceil(s*c),i),l=e=>({x:r?t.maxX-e.x:e.x-t.minX,z:r?t.maxZ-e.z:e.z-t.minZ}),u=[...e].sort((e,t)=>{const i=l(e),r=l(t);return i.x+i.z+e.y-(r.x+r.z+t.y)});for(const e of u){const i=l(e),r=(i.x-i.z)*n+o/2,s=(i.x+i.z)*a+(t.maxY-e.y+1)*n;d.voxel(Math.round(r*c),Math.round(s*c),Math.max(2,Math.round(n*c)),colorFor(e.name))}return d.png()}const COLORS={stone:"#777777",cobblestone:"#707070",deepslate:"#4b4b50",dirt:"#855b37",grass_block:"#63913d",sand:"#dbca85",glass:"#a7d9df",water:"#3f76e4",lava:"#e05b22",oak_planks:"#b9915a",spruce_planks:"#765033",birch_planks:"#d9c485",iron_block:"#d7d7d7",gold_block:"#f6c543",diamond_block:"#5ed6c7",redstone_block:"#b21d1d",netherrack:"#823332",quartz_block:"#e9e4dc",obsidian:"#211d2d",white_wool:"#e9e9e9",black_wool:"#1d1d1d",red_wool:"#a12722",blue_wool:"#3549a7",green_wool:"#4c702c",yellow_wool:"#e5c440"};function colorFor(e){const t=e.replace(/^minecraft:/,"");if(COLORS[t])return COLORS[t];for(const[e,i]of Object.entries(COLORS))if(t.includes(e))return i;const i=(0,node_crypto_1.createHash)("md5").update(t).digest();return`#${(90+i[0]%120).toString(16).padStart(2,"0")}${(90+i[1]%120).toString(16).padStart(2,"0")}${(90+i[2]%120).toString(16).padStart(2,"0")}`}class Raster{width;height;data;background;constructor(e,t,i){this.width=e,this.height=t,this.background=parseColor(i.background,i.transparentBackground?0:255),this.data=Buffer.alloc(e*t*4);for(let e=0;e<this.data.length;e+=4)this.data.set(this.background,e)}rect(e,t,i,r,n){for(let a=Math.max(0,t);a<Math.min(this.height,t+r);a++)for(let t=Math.max(0,e);t<Math.min(this.width,e+i);t++)this.pixel(t,a,n)}pixel(e,t,i){e<0||t<0||e>=this.width||t>=this.height||this.data.set(parseColor(i),4*(t*this.width+e))}voxel(e,t,i,r){const n=adjust(r,1.15),a=adjust(r,.78),o=adjust(r,.6),s=Math.ceil(i/2);for(let r=0;r<s;r++)for(let a=-i+r;a<=i-r;a++)this.pixel(e+a,t-s+r,n);for(let r=0;r<i;r++)for(let n=-i+Math.floor(r/2);n<=0;n++)this.pixel(e+n,t+r,a);for(let r=0;r<i;r++)for(let n=0;n<=i-Math.floor(r/2);n++)this.pixel(e+n,t+r,o)}png(){const e=Buffer.alloc((4*this.width+1)*this.height);for(let t=0;t<this.height;t++)e[t*(4*this.width+1)]=0,this.data.copy(e,t*(4*this.width+1)+1,t*this.width*4,(t+1)*this.width*4);const t=Buffer.alloc(13);return t.writeUInt32BE(this.width,0),t.writeUInt32BE(this.height,4),t.set([8,6,0,0,0],8),Buffer.concat([Buffer.from("PNG\r\n\n","binary"),chunk("IHDR",t),chunk("IDAT",(0,node_zlib_1.deflateSync)(e)),chunk("IEND",Buffer.alloc(0))])}}function parseColor(e,t=255){const i=/^#?([0-9a-f]{6})$/i.exec(e)?.[1]??"182026";return[parseInt(i.slice(0,2),16),parseInt(i.slice(2,4),16),parseInt(i.slice(4,6),16),t]}function adjust(e,t){const[i,r,n]=parseColor(e);return`#${[i,r,n].map(e=>Math.round(Math.min(255,e*t)).toString(16).padStart(2,"0")).join("")}`}function chunk(e,t){const i=Buffer.from(e),r=Buffer.alloc(4);r.writeUInt32BE(t.length);const n=Buffer.alloc(4);return n.writeUInt32BE(crc32(Buffer.concat([i,t]))>>>0),Buffer.concat([r,i,t,n])}const CRC_TABLE=Array.from({length:256},(e,t)=>{let i=t;for(let e=0;e<8;e++)i=1&i?3988292384^i>>>1:i>>>1;return i>>>0});function crc32(e){let t=4294967295;for(const i of e)t=CRC_TABLE[255&(t^i)]^t>>>8;return(4294967295^t)>>>0}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.inject=exports.name=exports.validateResourcePackArchive=exports.saveUploadedResourcePack=exports.resolveResourcePackProfile=exports.supportsStandaloneJavaVersion=exports.standaloneJvmOptions=exports.isJavaMemoryFailure=exports.createGpuRenderRequest=exports.renderSixFaceOverview=exports.renderSchematic=exports.normalizeSchematic=exports.litematicFilename=exports.validateProjectionLimits=exports.readNbtRoot=exports.parseLitematicMetadata=exports.parseLitematic=exports.formatLitematicMetadata=exports.sendImages=exports.resolveSendOptions=exports.replyElements=exports.composeQqOverview=exports.validateDownloadUrl=exports.isSchematicFilename=exports.isGroupAllowed=exports.findLitematicFile=exports.download=exports.canRenderInSession=exports.mergeRenderDiagnostics=exports.getDiagnosticsSummary=exports.formatRenderError=exports.RenderConcurrencyLimiter=exports.renderRateLimitKey=exports.RenderRateLimiter=exports.Config=exports.hashRenderConfiguration=exports.getCacheStats=exports.formatCacheStats=exports.enforceCacheLimit=exports.enforceCacheAge=exports.cacheNameSegment=exports.patchOneBotAdapterSource=exports.resolveOfficialProxyUrl=exports.reloadOfficialQqAdapter=exports.buildSshProxyArguments=exports.decodeDataUrl=exports.validatePngFiles=exports.validatePngBuffer=void 0,exports.addRenderHistory=addRenderHistory,exports.inspectSchematicMetadata=inspectSchematicMetadata,exports.resolveRenderOverrides=resolveRenderOverrides,exports.filenameFromUrl=filenameFromUrl,exports.apply=apply,exports.diagnosticsRequestToken=diagnosticsRequestToken;const koishi_1=require("koishi"),node_crypto_1=require("node:crypto"),node_fs_1=require("node:fs"),node_path_1=require("node:path"),node_url_1=require("node:url"),projectionCache_1=require("./projectionCache"),projectionSearch_1=require("./projectionSearch"),cache_1=require("./cache"),gpuAgentProtocol_1=require("./gpuAgentProtocol"),diagnostics_1=require("./diagnostics"),litematic_1=require("./litematic"),schematicFormats_1=require("./schematicFormats"),messageFiles_1=require("./messageFiles"),messageDelivery_1=require("./messageDelivery"),officialProxy_1=require("./officialProxy"),onebotCompat_1=require("./onebotCompat"),runtimePaths_1=require("./runtimePaths"),cpu_1=require("./render/cpu"),externalGpu_1=require("./render/externalGpu");var imageValidation_1=require("./render/imageValidation");Object.defineProperty(exports,"validatePngBuffer",{enumerable:!0,get:function(){return imageValidation_1.validatePngBuffer}}),Object.defineProperty(exports,"validatePngFiles",{enumerable:!0,get:function(){return imageValidation_1.validatePngFiles}});var webgl_1=require("./render/webgl");Object.defineProperty(exports,"decodeDataUrl",{enumerable:!0,get:function(){return webgl_1.decodeDataUrl}});const gpuAgent_1=require("./render/gpuAgent"),javaBridge_1=require("./render/javaBridge"),standalone_1=require("./render/standalone"),webgl_2=require("./render/webgl"),resourcePacks_1=require("./resourcePacks"),rateLimit_1=require("./rateLimit"),concurrency_1=require("./concurrency");var officialProxy_2=require("./officialProxy");Object.defineProperty(exports,"buildSshProxyArguments",{enumerable:!0,get:function(){return officialProxy_2.buildSshProxyArguments}}),Object.defineProperty(exports,"reloadOfficialQqAdapter",{enumerable:!0,get:function(){return officialProxy_2.reloadOfficialQqAdapter}}),Object.defineProperty(exports,"resolveOfficialProxyUrl",{enumerable:!0,get:function(){return officialProxy_2.resolveOfficialProxyUrl}});var onebotCompat_2=require("./onebotCompat");Object.defineProperty(exports,"patchOneBotAdapterSource",{enumerable:!0,get:function(){return onebotCompat_2.patchOneBotAdapterSource}});var cache_2=require("./cache");Object.defineProperty(exports,"cacheNameSegment",{enumerable:!0,get:function(){return cache_2.cacheNameSegment}}),Object.defineProperty(exports,"enforceCacheAge",{enumerable:!0,get:function(){return cache_2.enforceCacheAge}}),Object.defineProperty(exports,"enforceCacheLimit",{enumerable:!0,get:function(){return cache_2.enforceCacheLimit}}),Object.defineProperty(exports,"formatCacheStats",{enumerable:!0,get:function(){return cache_2.formatCacheStats}}),Object.defineProperty(exports,"getCacheStats",{enumerable:!0,get:function(){return cache_2.getCacheStats}}),Object.defineProperty(exports,"hashRenderConfiguration",{enumerable:!0,get:function(){return cache_2.hashRenderConfiguration}});var config_1=require("./config");Object.defineProperty(exports,"Config",{enumerable:!0,get:function(){return config_1.Config}});var rateLimit_2=require("./rateLimit");Object.defineProperty(exports,"RenderRateLimiter",{enumerable:!0,get:function(){return rateLimit_2.RenderRateLimiter}}),Object.defineProperty(exports,"renderRateLimitKey",{enumerable:!0,get:function(){return rateLimit_2.renderRateLimitKey}});var concurrency_2=require("./concurrency");Object.defineProperty(exports,"RenderConcurrencyLimiter",{enumerable:!0,get:function(){return concurrency_2.RenderConcurrencyLimiter}});var diagnostics_2=require("./diagnostics");Object.defineProperty(exports,"formatRenderError",{enumerable:!0,get:function(){return diagnostics_2.formatRenderError}}),Object.defineProperty(exports,"getDiagnosticsSummary",{enumerable:!0,get:function(){return diagnostics_2.getDiagnosticsSummary}}),Object.defineProperty(exports,"mergeRenderDiagnostics",{enumerable:!0,get:function(){return diagnostics_2.mergeRenderDiagnostics}});var messageFiles_2=require("./messageFiles");Object.defineProperty(exports,"canRenderInSession",{enumerable:!0,get:function(){return messageFiles_2.canRenderInSession}}),Object.defineProperty(exports,"download",{enumerable:!0,get:function(){return messageFiles_2.download}}),Object.defineProperty(exports,"findLitematicFile",{enumerable:!0,get:function(){return messageFiles_2.findLitematicFile}}),Object.defineProperty(exports,"isGroupAllowed",{enumerable:!0,get:function(){return messageFiles_2.isGroupAllowed}}),Object.defineProperty(exports,"isSchematicFilename",{enumerable:!0,get:function(){return messageFiles_2.isSchematicFilename}}),Object.defineProperty(exports,"validateDownloadUrl",{enumerable:!0,get:function(){return messageFiles_2.validateDownloadUrl}});var messageDelivery_2=require("./messageDelivery");Object.defineProperty(exports,"composeQqOverview",{enumerable:!0,get:function(){return messageDelivery_2.composeQqOverview}}),Object.defineProperty(exports,"replyElements",{enumerable:!0,get:function(){return messageDelivery_2.replyElements}}),Object.defineProperty(exports,"resolveSendOptions",{enumerable:!0,get:function(){return messageDelivery_2.resolveSendOptions}}),Object.defineProperty(exports,"sendImages",{enumerable:!0,get:function(){return messageDelivery_2.sendImages}});var litematic_2=require("./litematic");Object.defineProperty(exports,"formatLitematicMetadata",{enumerable:!0,get:function(){return litematic_2.formatLitematicMetadata}}),Object.defineProperty(exports,"parseLitematic",{enumerable:!0,get:function(){return litematic_2.parseLitematic}}),Object.defineProperty(exports,"parseLitematicMetadata",{enumerable:!0,get:function(){return litematic_2.parseLitematicMetadata}}),Object.defineProperty(exports,"readNbtRoot",{enumerable:!0,get:function(){return litematic_2.readNbtRoot}}),Object.defineProperty(exports,"validateProjectionLimits",{enumerable:!0,get:function(){return litematic_2.validateProjectionLimits}});var schematicFormats_2=require("./schematicFormats");Object.defineProperty(exports,"litematicFilename",{enumerable:!0,get:function(){return schematicFormats_2.litematicFilename}}),Object.defineProperty(exports,"normalizeSchematic",{enumerable:!0,get:function(){return schematicFormats_2.normalizeSchematic}});var cpu_2=require("./render/cpu");Object.defineProperty(exports,"renderSchematic",{enumerable:!0,get:function(){return cpu_2.renderSchematic}}),Object.defineProperty(exports,"renderSixFaceOverview",{enumerable:!0,get:function(){return cpu_2.renderSixFaceOverview}});var gpuAgent_2=require("./render/gpuAgent");Object.defineProperty(exports,"createGpuRenderRequest",{enumerable:!0,get:function(){return gpuAgent_2.createGpuRenderRequest}});var standalone_2=require("./render/standalone");Object.defineProperty(exports,"isJavaMemoryFailure",{enumerable:!0,get:function(){return standalone_2.isJavaMemoryFailure}}),Object.defineProperty(exports,"standaloneJvmOptions",{enumerable:!0,get:function(){return standalone_2.standaloneJvmOptions}}),Object.defineProperty(exports,"supportsStandaloneJavaVersion",{enumerable:!0,get:function(){return standalone_2.supportsStandaloneJavaVersion}});var resourcePacks_2=require("./resourcePacks");Object.defineProperty(exports,"resolveResourcePackProfile",{enumerable:!0,get:function(){return resourcePacks_2.resolveResourcePackProfile}}),Object.defineProperty(exports,"saveUploadedResourcePack",{enumerable:!0,get:function(){return resourcePacks_2.saveUploadedResourcePack}}),Object.defineProperty(exports,"validateResourcePackArchive",{enumerable:!0,get:function(){return resourcePacks_2.validateResourcePackArchive}});const Sentry=require("@sentry/node-core/light");exports.name="litematic-renderer",exports.inject={optional:["puppeteer","server","console"]};const CACHE_FORMAT_VERSION=18;function addRenderHistory(e,t,r=20){return e.unshift(t),e.splice(Math.max(0,r)),e}function inspectSchematicMetadata(e,t,r){const a=(0,schematicFormats_1.normalizeSchematic)(e,t,r),i=(0,litematic_1.parseLitematicMetadata)(a.bytes);return(0,litematic_1.validateProjectionLimits)(a.bytes,i,r),{filename:a.filename,metadata:i}}function resolveRenderOverrides(e){const t={};if(null!=e.size){const r=Number(e.size);if(!Number.isInteger(r)||r<128||r>4096)throw new Error("图片尺寸必须是 128 到 4096 之间的整数");t.outputSize=r}if(null!=e.rotation){const r=Number(e.rotation);if(!Number.isFinite(r))throw new Error("旋转角度必须是数字");t.isometricRotation=(r%360+360)%360}if(null!=e.slant){const r=Number(e.slant);if(!Number.isFinite(r)||r<-90||r>90)throw new Error("俯仰角必须在 -90 到 90 度之间");t.isometricSlant=r}if(null!=e.background){const r=String(e.background);if(!/^#[0-9a-f]{6}$/i.test(r))throw new Error("背景颜色必须使用 #RRGGBB 格式");t.background=r}if(!0===e.transparent&&(t.transparentBackground=!0),null!=e.engine){const r=String(e.engine);if(!["standalone","gpuAgent","java","webgl","cpu"].includes(r))throw new Error("渲染引擎必须是 standalone、gpuAgent、java、webgl 或 cpu");t.renderEngine=r}if(null!=e.profile){const r=String(e.profile).trim();if(!r)throw new Error("材质包配置档名称不能为空");t.resourcePackProfile=r}return t}function filenameFromUrl(e){try{const t=new URL(e).pathname.split("/").filter(Boolean).at(-1);return t?decodeURIComponent(t):"schematic.litematic"}catch{return"schematic.litematic"}}function apply(e,t){const r=t,a=e.logger(exports.name),i={requested:0,completed:0,failed:0,cacheHits:0,totalDurationMs:0},n=[],o=new concurrency_1.RenderConcurrencyLimiter(t.maxConcurrentRenders??2),s=new rateLimit_1.RenderRateLimiter(t.renderRateLimitPerMinute??0),c=t.gpuAgentEnabled?new gpuAgentProtocol_1.GpuAgentHub({host:t.gpuAgentListenHost,port:t.gpuAgentListenPort,path:t.gpuAgentPath.startsWith("/")?t.gpuAgentPath:`/${t.gpuAgentPath}`,nodes:t.gpuAgentNodes,heartbeatTimeout:3e4,logger:a}):void 0;if(c?.start(),c&&e.on("dispose",()=>{c.close()}),"official"===t.qqBotType){const r=(0,officialProxy_1.resolveOfficialProxyUrl)(t);if(r){const i=e.root.on("http/config",e=>{e.proxyAgent=r}),n="ssh"===t.officialProxyMode?(0,officialProxy_1.startSshProxyTunnel)(t,a):()=>{};a.info(`官方 QQ 实验性出站代理已启用:${r}`);const o=setInterval(async()=>{try{await e.http.get("https://api.sgroup.qq.com/gateway",{timeout:1e4,responseType:"json"})}catch{}},6e4);let s=Date.now();t.officialGatewayWatchdog&&e.on("message",()=>{s=Date.now()});const c=t.officialGatewayWatchdog?setInterval(()=>{Date.now()-s<=48e4||(0,officialProxy_1.reloadOfficialQqAdapter)(e,a).then(e=>{e&&(s=Date.now())})},6e4):void 0;e.on("dispose",()=>{clearInterval(o),c&&clearInterval(c),i(),n()})}}e.inject(["console"],e=>{const t=runtimePaths_1.PACKAGE_ROOT;e.console.addEntry({dev:(0,node_path_1.join)(t,"client/index.ts"),prod:(0,node_path_1.join)(t,"dist")}),e.console.addListener("litematic/resource-pack-upload",async(t,r)=>(0,resourcePacks_1.saveUploadedResourcePack)(t,r,(0,node_path_1.resolve)(e.baseDir,"data/litematic-resource-packs")),{authority:4})});const l=1024*t.maxFileSize,d=t.sentryDsn||process.env.SENTRY_DSN||"";d&&Sentry.init({dsn:d,tracesSampleRate:1});const m=(e,r)=>{d&&Sentry.withScope(a=>{a.setFingerprint([r]),a.setTag("entrypoint",r),a.setContext("render",{engine:t.renderEngine}),Sentry.captureException(e)})};e.on("dispose",()=>(0,standalone_1.terminateActiveStandaloneJavaProcesses)(a)),"selfHosted"===t.qqBotType&&(0,onebotCompat_1.ensureOneBotGroupUploadCompatibility)(a,t.patchOneBotGroupUpload);const u=(0,node_path_1.resolve)(stringOrDefault(t.diagnosticsFilePath,"data/litematic-renderer-diagnostics.json")),p=(0,node_path_1.join)((0,node_path_1.dirname)(u),"litematic-renderer-diagnostics-archive"),g=(0,node_path_1.join)((0,node_path_1.dirname)(u),"litematic-renderer-diagnostics-disabled");(0,diagnostics_1.rotateDiagnosticsFile)(u,p,a);const f=(0,node_path_1.resolve)(stringOrDefault(t.cacheDirectory,"data/litematic-renderer-cache")),h=(0,node_path_1.join)(f,`v${(0,cache_1.cachePathSegment)(runtimePaths_1.PLUGIN_VERSION)}`),_=Math.floor(t.cacheMaxSizeGb*1024**3),y=new Map;node_fs_1.promises.mkdir(h,{recursive:!0}).then(async()=>{await(0,projectionCache_1.rebuildProjectionLibrary)(f),t.cacheMaxAgeDays>0&&await(0,cache_1.enforceCacheAge)(f,864e5*t.cacheMaxAgeDays),await(0,cache_1.enforceCacheLimit)(f,_)}).catch(e=>a.warn(`缓存初始化失败:${e instanceof Error?e.message:String(e)}`));const w=async()=>{const[e,r]=await Promise.all([(0,cache_1.getCacheStats)(f),(0,diagnostics_1.getDiagnosticsSummary)(u)]);return{generatedAt:(new Date).toISOString(),engine:t.renderEngine,metrics:{...i,averageDurationMs:i.completed?Math.round(i.totalDurationMs/i.completed):0},cache:e,diagnostics:r,gpu:c?.status()??null,history:n}};e.inject(["console"],e=>{e.console.addListener("litematic/operations/status",w,{authority:3}),e.console.addListener("litematic/operations/cache-clear",async()=>(await node_fs_1.promises.rm(f,{recursive:!0,force:!0}),await node_fs_1.promises.mkdir(h,{recursive:!0}),w()),{authority:3}),e.console.addListener("litematic/operations/cache-prune",async e=>{const r=Number(e??t.cacheMaxAgeDays);if(!Number.isFinite(r)||r<0)throw new Error("缓存保留天数必须是非负数字");return r>0&&await(0,cache_1.enforceCacheAge)(f,864e5*r),await(0,cache_1.enforceCacheLimit)(f,_),w()},{authority:3}),e.console.addListener("litematic/operations/diagnostics-export",async()=>({filename:"litematic-renderer-diagnostics.json",base64:(await node_fs_1.promises.readFile(u).catch(()=>Buffer.from('{"format":2}'))).toString("base64")}),{authority:3}),e.console.addListener("litematic/operations/diagnostics-disable",async()=>(await(0,diagnostics_1.disableDiagnosticsSnapshot)(u,g),w()),{authority:3})});const x=async(e,t,r,a,i)=>{const n="gpuAgent"===r.renderEngine?(0,gpuAgent_1.createGpuRenderRequest)(e,r,i,a.name):void 0,o=n?c?.plan(n,t):void 0,s="standalone"===r.renderEngine||"gpuAgent"===r.renderEngine&&r.gpuAgentFallback,l=s?await(0,standalone_1.resolveMinecraftResources)(r):"",d=s?await(0,standalone_1.fingerprintFiles)([l,...(0,standalone_1.resourcePackPaths)(r.resourcePackPaths)]):[],m=(0,cache_1.hashRenderConfiguration)({version:CACHE_FORMAT_VERSION,outputSize:r.outputSize,isometricCellSize:r.isometricCellSize,background:r.background,transparentBackground:r.transparentBackground,gpuRendererCommand:r.gpuRendererCommand,renderEngine:r.renderEngine,standaloneRendererJar:r.standaloneRendererJar,resourceFingerprint:d,resourcePackProfile:a.name,javaResolution:r.javaResolution,javaSupersampling:r.javaSupersampling,webglQuality:r.webglQuality,webglWidth:r.webglWidth,webglHeight:r.webglHeight,isometricSquare:r.isometricSquare,isometricFill:r.isometricFill,isometricRotation:r.isometricRotation,isometricSlant:r.isometricSlant,sixFaceLayout:r.sixFaceLayout,imageSendLayout:r.imageSendLayout,gpuAgentFingerprint:"gpuAgent"===r.renderEngine?o?.fingerprint??"offline":void 0});return n&&(n.renderConfigSha256=m),{gpuRequest:n,gpuPlan:o,minecraftJarPath:l,resourceFingerprint:d,renderHash:m}},P=async(...t)=>{const s=Date.now();i.requested++;const d=await o.acquire();try{const o=await(async(t,i="schematic.litematic",n,o=!1,s,d=l,m={network:"trusted"},p={})=>{const{resourcePackProfile:g,...w}=p,P={...r,...w},v=(0,resourcePacks_1.resolveResourcePackProfile)(P,s?.group,g),b={...P,minecraftJarPath:v.minecraftJarPath,resourcePackPaths:v.resourcePackPaths},S=n??await(0,messageFiles_1.download)(e,t,d,b.renderTimeout,m),F=(0,schematicFormats_1.normalizeSchematic)(S,i,b.maxBlocks),j=F.bytes,R=(0,litematic_1.parseLitematicMetadata)(j);(0,litematic_1.validateProjectionLimits)(j,R,b.maxBlocks);const A=(0,litematic_1.formatLitematicMetadata)(R,i,{showProjectionName:b.showMetadataProjectionName,showAuthor:b.showMetadataAuthor,showCreatedAt:b.showMetadataCreatedAt,showBlockStats:b.showMetadataBlockStats,showSize:b.showMetadataSize,showLitematicVersion:b.showMetadataLitematicVersion,showGameVersion:b.showMetadataGameVersion}),O=(0,cache_1.projectionNameFromFilename)(i),q=(0,node_crypto_1.createHash)("sha256").update(S).digest("hex"),{gpuRequest:L,gpuPlan:C,minecraftJarPath:k,resourceFingerprint:D,renderHash:E}=await x(F.filename,q,b,v,s),M=(0,cache_1.cacheNameSegment)(i),I=(0,node_path_1.join)(h,`${M}-${q}-${E}`),N=(0,node_path_1.join)(I,"projection.litematic");await node_fs_1.promises.mkdir(I,{recursive:!0}),await exists(N)||await node_fs_1.promises.writeFile(N,j),await(0,cache_1.ensureCacheMetadata)(I,{pluginVersion:runtimePaths_1.PLUGIN_VERSION,cacheFormatVersion:CACHE_FORMAT_VERSION,contentSha256:q,normalizedContentSha256:(0,node_crypto_1.createHash)("sha256").update(j).digest("hex"),renderConfigSha256:E,sourceFilename:(0,node_path_1.basename)(i),createdAt:(new Date).toISOString()});const B=["isometric.png","isometric-reverse.png"].map(e=>(0,node_path_1.join)(I,e)),U=async()=>{const e=await(0,projectionCache_1.readRenderManifest)(I);if(e)return!e.rendererFingerprint||!C||e.rendererFingerprint===C.fingerprint;if(await exists((0,node_path_1.join)(I,"images.json")))return!1;const t=await Promise.all(B.map(exists));return t.every(Boolean)||"gpuAgent"===b.renderEngine&&t[0]},G=await U();if(G)a.debug(`命中投影缓存:${q}`);else{let t=y.get(I);t?a.debug(`等待相同投影的缓存任务:${q}`):(t=(async()=>{try{if(await U())return;if(await(0,projectionCache_1.writeCacheJson)((0,node_path_1.join)(I,"images.json"),{images:[],forceSeparateImages:!1}),await Promise.all(B.map(e=>node_fs_1.promises.rm(e,{force:!0}))),!Boolean(b.gpuRendererCommand&&await(0,externalGpu_1.renderWithGpu)(b.gpuRendererCommand,N,I,b.renderTimeout,a,b.maxRenderedImageBytes))||!(await Promise.all(B.map(exists))).every(Boolean))if("standalone"===b.renderEngine)await(0,standalone_1.renderWithStandalone)(N,I,k,b,a),await(0,diagnostics_1.mergeRenderDiagnostics)(I,u,a);else if("gpuAgent"===b.renderEngine)try{if(!c)throw new Error("GPU Agent v2 服务未启用");const e=await c.render(L??(0,gpuAgent_1.createGpuRenderRequest)(F.filename,b,s,v.name),j,b.gpuAgentTimeout,C?.agentId);await(0,projectionCache_1.saveGpuRenderManifest)(I,e)}catch(e){if(!b.gpuAgentFallback)throw e;a.warn(`GPU Agent 渲染失败,回退独立 Java:${e instanceof Error?e.message:String(e)}`),await(0,standalone_1.renderWithStandalone)(N,I,k,b,a),await(0,diagnostics_1.mergeRenderDiagnostics)(I,u,a)}else if("java"===b.renderEngine)await(0,javaBridge_1.renderWithJavaBridge)(N,I,b);else{const t=(0,litematic_1.parseLitematic)(j);let r;if("webgl"===b.renderEngine&&e.puppeteer)try{r=await(0,webgl_2.renderWithWebgl)(e,j,b)}catch(e){a.warn(`WebGL 渲染失败,回退 CPU:${e instanceof Error?e.message:String(e)}`),r=(0,cpu_1.renderSchematic)(t,b)}else r=(0,cpu_1.renderSchematic)(t,b);await Promise.all(r.map(e=>node_fs_1.promises.writeFile((0,node_path_1.join)(I,e.title),e.png)))}if(!await(0,projectionCache_1.readRenderManifest)(I)&&!(await Promise.all(B.map(exists))).every(Boolean))throw new Error("渲染器没有生成两张正二轴测 PNG")}catch(e){throw await(0,diagnostics_1.appendRenderError)(I,u,b.renderEngine,e,a),e}})().finally(()=>y.delete(I)),y.set(I,t)),await t}const $=await(0,projectionCache_1.readRenderManifest)(I),z=$?$.images.filter(e=>o||$.rendererFingerprint||"six-faces.png"!==e.filename).map(e=>({title:e.title,path:(0,node_path_1.join)(I,e.filename)})):await exists(B[1])?B.map((e,t)=>({title:["正二轴测","反向正二轴测(旋转 180°)"][t],path:e})):[{title:"正二轴测",path:B[0]}];if(o){const e=(0,node_path_1.join)(I,"six-faces.png");if(!await exists(e)){const t=`${I}:six-face`;let r=y.get(t);r||(r=(async()=>{try{if("standalone"===b.renderEngine)try{await(0,standalone_1.renderWithStandalone)(N,I,k,b,a,"six-face")}catch(e){a.warn(`真实材质六面图生成失败,回退方块颜色投影:${e instanceof Error?e.message:String(e)}`)}if(!await exists(e)){const t=(0,litematic_1.parseLitematic)(j);await node_fs_1.promises.writeFile(e,(0,cpu_1.renderSixFaceOverview)(t,b,b.sixFaceLayout))}}catch(e){a.warn(`六面正交图生成失败,继续发送轴测图:${e instanceof Error?e.message:String(e)}`)}})().finally(()=>y.delete(t)),y.set(t,r)),await r}await exists(e)&&!z.some(t=>t.path===e)&&z.push({title:"六面正投影",path:e})}return $||await(0,projectionCache_1.writeCacheJson)((0,node_path_1.join)(I,"images.json"),{images:z.map(e=>({filename:(0,node_path_1.basename)(e.path),title:e.title})),forceSeparateImages:!1}),await(0,projectionCache_1.rememberProjection)(f,{contentSha256:q,sourceFilename:i},j,{directory:(0,node_path_1.relative)(f,I),pluginVersion:runtimePaths_1.PLUGIN_VERSION,renderConfigSha256:E},S),await(0,projectionCache_1.recordProjectionUse)(f,q),await(0,cache_1.touchCacheEntry)(I),b.cacheMaxAgeDays>0&&await(0,cache_1.enforceCacheAge)(f,864e5*b.cacheMaxAgeDays,I),await(0,cache_1.enforceCacheLimit)(f,_,I),{images:z,metadata:A,projectionName:O,cacheHit:G,forceSeparateImages:!0===$?.forceSeparateImages}})(...t),d=Date.now()-s;return i.completed++,i.totalDurationMs+=d,i.lastDurationMs=d,i.lastCompletedAt=(new Date).toISOString(),o.cacheHit&&i.cacheHits++,addRenderHistory(n,{projectionName:o.projectionName,engine:t[7]?.renderEngine??r.renderEngine,status:"completed",durationMs:d,cacheHit:o.cacheHit,completedAt:i.lastCompletedAt}),o}catch(e){throw i.failed++,addRenderHistory(n,{projectionName:(0,cache_1.projectionNameFromFilename)(String(t[1]??"schematic.litematic")),engine:r.renderEngine,status:"failed",durationMs:Date.now()-s,completedAt:(new Date).toISOString()}),e}finally{d()}},v=new Map,b=async(e,a)=>{const i=(0,resourcePacks_1.resolveResourcePackProfile)(r,e.guildId),n={...r,minecraftJarPath:i.minecraftJarPath,resourcePackPaths:i.resourcePackPaths};return(0,projectionCache_1.searchCachedProjections)(f,a,t.projectionSearchResultLimit,async(t,r)=>{if(r.pluginVersion!==runtimePaths_1.PLUGIN_VERSION)return!1;const a=await x(`${(0,cache_1.projectionNameFromFilename)(t.sourceFilename)}.litematic`,t.contentSha256,n,i,{group:e.guildId});if(a.renderHash!==r.renderConfigSha256)return!1;const o=await(0,projectionCache_1.readRenderManifest)((0,node_path_1.resolve)(f,r.directory));return!o?.rendererFingerprint||!a.gpuPlan||o.rendererFingerprint===a.gpuPlan.fingerprint})};e.middleware(async(e,r)=>{const i=(e.content??"").trim(),n=/^[/!!]?搜索投影\s+(.+?)\s*$/.exec(i),o=/^[/!!]?发送投影\s*(\d+)(?:\s+(.+?))?\s*$/.exec(i);if(!n&&!o)return r();if(!(0,messageFiles_1.canRenderInSession)(e,t.allowPrivateRender)||!(0,messageFiles_1.isGroupAllowed)(t,e.guildId))return r();try{const r=Date.now();for(const[e,t]of v)t.expiresAt<=r&&v.delete(e);const i=(e=>`${e.platform}|${e.selfId}|${e.guildId??""}|${e.userId??""}|${Boolean(e.isDirect)}`)(e);if(n){const a=await b(e,n[1]);if(!a.entries.length)return e.send("没有找到符合关键词且当前配置可用的已缓存投影");const o=await(0,projectionSearch_1.createProjectionSearchSheet)(a,f);v.set(i,{page:a,expiresAt:r+6e5});try{await e.send("official"===t.qqBotType?koishi_1.h.image((0,node_url_1.pathToFileURL)(o).href):(0,koishi_1.h)("img",{src:`base64://${(await node_fs_1.promises.readFile(o)).toString("base64")}`}))}finally{await node_fs_1.promises.rm(o,{force:!0})}return}const s=Number(o[1]),c=o[2]?.trim(),l=c?await b(e,c):v.get(i)?.page;if(!l)return e.send("请先发送“搜索投影 关键词”,或使用“发送投影1 关键词”");if(!Number.isInteger(s)||s<1||s>l.entries.length)return e.send(`投影序号无效,可选范围为 1-${l.entries.length}`);const d=l.entries[s-1],m=(await b(e,l.keyword)).entries.find(e=>e.record.contentSha256===d.record.contentSha256);if(!m)return e.send("当前配置的渲染图片已失效,请重新渲染后再搜索");const u=await node_fs_1.promises.readFile((0,node_path_1.join)(f,".projection-library",m.record.contentSha256,"projection.litematic")),p=(0,litematic_1.formatLitematicMetadata)((0,litematic_1.parseLitematicMetadata)(u),m.record.sourceFilename,{showProjectionName:t.showMetadataProjectionName,showAuthor:t.showMetadataAuthor,showCreatedAt:t.showMetadataCreatedAt,showBlockStats:t.showMetadataBlockStats,showSize:t.showMetadataSize,showLitematicVersion:t.showMetadataLitematicVersion,showGameVersion:t.showMetadataGameVersion}),g=(0,messageDelivery_1.resolveSendOptions)(t,e.guildId);await(0,messageDelivery_1.sendImages)(e,m.images,p,m.forceSeparateImages?{...g,imageSendLayout:"separate"}:g,(0,cache_1.projectionNameFromFilename)(m.record.sourceFilename),e=>a.warn(e)),await e.send((0,koishi_1.h)("file",{src:(0,node_url_1.pathToFileURL)(m.projectionPath).href,name:m.record.downloadFilename})),await(0,projectionCache_1.recordProjectionUse)(f,m.record.contentSha256),await(0,cache_1.touchCacheEntry)(m.directory)}catch(t){await e.send(`投影搜索失败:${t instanceof Error?t.message:String(t)}`)}}),e.middleware(async(e,r)=>{if(!(0,messageFiles_1.canRenderInSession)(e,t.allowPrivateRender))return r();const i=(0,messageFiles_1.findLitematicFile)(e);if(!i)return r();if(!(0,messageFiles_1.isGroupAllowed)(t,e.guildId))return a.info(`群 ${e.guildId} 不在渲染白名单内或已被拉黑,忽略其投影文件`),await e.send([...(0,messageDelivery_1.replyElements)(e,t.qqBotType),(0,koishi_1.h)("text",{content:`本群未开启投影渲染。如需开启,请将群 ID ${e.guildId} 加入插件白名单`})]),r();const n=s.check((0,rateLimit_1.renderRateLimitKey)(e));if(!n.allowed)return await e.send([...(0,messageDelivery_1.replyElements)(e,t.qqBotType),(0,koishi_1.h)("text",{content:`渲染请求过于频繁,请 ${n.retryAfterSeconds} 秒后重试`})]),r();const o=await(0,messageFiles_1.resolveFileUrl)(e,i);if(!o)return a.warn(`检测到投影文件但无法获取下载地址:${(0,messageFiles_1.fileName)(i)??"unknown.litematic"};请检查 OneBot/NapCat 的 get_group_file_url 接口`),await e.send([...(0,messageDelivery_1.replyElements)(e,t.qqBotType),(0,koishi_1.h)("text",{content:"检测到投影文件,但无法获取群文件下载地址,请检查机器人文件接口"})]),r();const c=Boolean(e.isDirect),l=c?t.privateMaxFileSize:t.maxFileSize,d=1024*l;if((0,messageFiles_1.isOverLimit)(i.size,d))return await(0,diagnostics_1.appendGlobalRenderError)(u,`input:${(0,node_path_1.basename)((0,messageFiles_1.fileName)(i)??"unknown.litematic")}`,"input",`file size exceeds ${l} KB`,a),await e.send([...(0,messageDelivery_1.replyElements)(e,t.qqBotType),(0,koishi_1.h)("text",{content:`文件大小超过 ${(l/1024).toFixed(2)} MB,无法渲染`})]),r();if(!(0,messageFiles_1.isUnderLimit)(i.size,d))return r();try{const r=(0,messageDelivery_1.resolveSendOptions)(t,e.guildId),n=await P(o,(0,messageFiles_1.fileName)(i)??"schematic.litematic",void 0,r.sixFaceOverview,{group:e.guildId??void 0,user:e.userId??void 0},d);await(0,messageDelivery_1.sendImages)(e,n.images,n.metadata,n.forceSeparateImages?{...r,imageSendLayout:"separate"}:r,n.projectionName,e=>a.warn(e))}catch(i){return m(i,c?"private-file-upload":"group-file-upload"),a.warn(i),await e.send([...(0,messageDelivery_1.replyElements)(e,t.qqBotType),(0,koishi_1.h)("text",{content:(0,diagnostics_1.formatRenderError)(i,{maxFileSize:l})})]),r()}return r()}),e.command("litematic.render [url:string]","渲染直链或引用消息中的 .litematic、.schem 或结构 .nbt 文件").option("size","--size <pixels:number> 输出图片边长").option("rotation","-r <degrees:number> 水平旋转角度").option("slant","--slant <degrees:number> 俯仰角").option("background","-b <color:string> 背景颜色 #RRGGBB").option("transparent","-t 输出透明背景").option("sixFace","--six-face 附加六面正投影").option("withoutSixFace","--no-six-face 不生成六面正投影").option("name","-n <filename:string> 指定投影名称").option("profile","-p <profile:string> 临时选择材质包配置档").option("engine","-e <engine:string> 临时选择渲染引擎",{authority:3}).action(async({session:e,options:r},i)=>{const n=r??{},o=t.directUrlPolicy??"public";if(!e)return"此命令只能在消息会话中执行";if(!(0,messageFiles_1.canRenderInSession)(e,t.allowPrivateRender))return"单人对话渲染未开启,请在插件发送设置中启用";if(!(0,messageFiles_1.isGroupAllowed)(t,e.guildId))return`本群未开启投影渲染。如需开启,请将群 ID ${e.guildId} 加入插件白名单`;const c=s.check((0,rateLimit_1.renderRateLimitKey)(e));if(!c.allowed)return`渲染请求过于频繁,请 ${c.retryAfterSeconds} 秒后重试`;const l=e.isDirect?t.privateMaxFileSize:t.maxFileSize,d=1024*l;try{const r=i?void 0:(0,messageFiles_1.findLitematicFile)(e)??(e.quote?(0,messageFiles_1.findLitematicFile)({elements:e.quote.elements,content:e.quote.content}):void 0);if(!i&&!r)return"请提供投影直链,或引用一条包含投影文件的消息";if(i&&"disabled"===o)return"管理员已关闭直链渲染命令";if(r&&(0,messageFiles_1.isOverLimit)(r.size,d))return`文件大小超过 ${(l/1024).toFixed(2)} MB,无法渲染`;const s=i??(r?await(0,messageFiles_1.resolveFileUrl)(e,r):void 0);if(!s)return"检测到投影文件,但无法获取下载地址";const c="string"==typeof n.name&&n.name.trim()?n.name.trim():(r?(0,messageFiles_1.fileName)(r):void 0)||filenameFromUrl(s),m=resolveRenderOverrides(n),u=(0,messageDelivery_1.resolveSendOptions)(t,e.guildId),p=!n.withoutSixFace&&(!!n.sixFace||u.sixFaceOverview),g=await P(s,c,void 0,p,{group:e.guildId??void 0,user:e.userId??void 0},d,{network:r||"any"===o||"disabled"===o?"trusted":"public",allowedHosts:t.directUrlAllowedHosts??[]},m);await(0,messageDelivery_1.sendImages)(e,g.images,g.metadata,g.forceSeparateImages?{...u,imageSendLayout:"separate"}:u,g.projectionName,e=>a.warn(e))}catch(e){return m(e,"litematic.render"),(0,diagnostics_1.formatRenderError)(e,{maxFileSize:l})}}),e.command("litematic.info [url:string]","查看投影元数据,不启动渲染器",{authority:1}).option("name","-n <filename:string> 指定投影名称").action(async({session:r,options:a},i)=>{if(!r)return"此命令只能在消息会话中执行";if(!(0,messageFiles_1.canRenderInSession)(r,t.allowPrivateRender))return"单人对话渲染未开启,请在插件发送设置中启用";if(!(0,messageFiles_1.isGroupAllowed)(t,r.guildId))return"本群未开启投影渲染";const n=s.check((0,rateLimit_1.renderRateLimitKey)(r));if(!n.allowed)return`渲染请求过于频繁,请 ${n.retryAfterSeconds} 秒后重试`;const o=i?void 0:(0,messageFiles_1.findLitematicFile)(r)??(r.quote?(0,messageFiles_1.findLitematicFile)({elements:r.quote.elements,content:r.quote.content}):void 0);if(!i&&!o)return"请提供投影直链,或引用一条包含投影文件的消息";if(i&&"disabled"===(t.directUrlPolicy??"public"))return"管理员已关闭直链渲染命令";const c=r.isDirect?t.privateMaxFileSize:t.maxFileSize,l=1024*c;if(o&&(0,messageFiles_1.isOverLimit)(o.size,l))return`文件大小超过 ${(c/1024).toFixed(2)} MB,无法读取`;const d=i??(o?await(0,messageFiles_1.resolveFileUrl)(r,o):void 0);if(!d)return"检测到投影文件,但无法获取下载地址";const u="string"==typeof a?.name&&a.name.trim()?a.name.trim():(o?(0,messageFiles_1.fileName)(o):void 0)||filenameFromUrl(d);try{const r=inspectSchematicMetadata(await(0,messageFiles_1.download)(e,d,l,t.renderTimeout,{network:o||"any"===t.directUrlPolicy||"disabled"===t.directUrlPolicy?"trusted":"public",allowedHosts:t.directUrlAllowedHosts??[]}),u,t.maxBlocks);return(0,litematic_1.formatLitematicMetadata)(r.metadata,r.filename)}catch(e){return m(e,"litematic.info"),(0,diagnostics_1.formatRenderError)(e,{maxFileSize:c})}}),e.command("litematic.cache.clear","清理投影渲染缓存",{authority:3}).action(async()=>(await node_fs_1.promises.rm(f,{recursive:!0,force:!0}),await node_fs_1.promises.mkdir(h,{recursive:!0}),"投影渲染缓存已清理")),e.command("litematic.cache.stats","查看投影渲染缓存占用",{authority:3}).action(async()=>(0,cache_1.formatCacheStats)(await(0,cache_1.getCacheStats)(f))),e.command("litematic.cache.prune [days:number]","按保留天数清理投影渲染缓存",{authority:3}).action(async({session:e},r)=>{const a=null==r?t.cacheMaxAgeDays:Number(r);if(!Number.isFinite(a)||a<0)return"缓存保留天数必须是非负数字";const i=a>0?await(0,cache_1.enforceCacheAge)(f,864e5*a):void 0,n=await(0,cache_1.enforceCacheLimit)(f,_),o=`已清理 ${i?.removedEntries??0} 个过期条目和 ${n.removedEntries} 个超容量条目`;return e?`${o}\n${(0,cache_1.formatCacheStats)(await(0,cache_1.getCacheStats)(f))}`:o}),e.command("litematic.agent.status","查看 GPU Agent 节点和任务状态",{authority:3}).action(()=>c?(0,gpuAgentProtocol_1.formatGpuAgentStatus)(c.status()):"GPU Agent 服务未启用,请开启 gpuAgentEnabled"),e.command("litematic.agent.cancel <taskId:string>","取消排队中的 GPU Agent 任务",{authority:3}).action(({session:e},t)=>c?c.cancel(t)?e?`已取消 GPU Agent 任务:${t}`:"GPU Agent 任务已取消":`未找到排队中的任务:${t}`:"GPU Agent 服务未启用,请开启 gpuAgentEnabled"),e.command("litematic.errors.export","export render diagnostics",{authority:3}).action(async()=>`Diagnostics file: ${u}`),e.command("litematic.errors.disable","disable current render diagnostics snapshot",{authority:3}).action(async()=>(0,diagnostics_1.disableDiagnosticsSnapshot)(u,g)),e.command("litematic.proxy.check","检查 Koishi 当前公网出口 IP",{authority:3}).action(async()=>{try{const t=await e.http.get("https://ifconfig.me/ip",{responseType:"text",timeout:1e4,headers:{"User-Agent":"koishi-plugin-litematic-renderer"}});return`当前 Koishi 出口 IP:${String(t).trim()}`}catch(e){return`出口 IP 检查失败:${e instanceof Error?e.message:String(e)}`}});const S=e.server,F=t.diagnosticsHttpToken?.trim();S?.get&&F&&S.get("/litematic-renderer/diagnostics",async e=>{if(!secureTextEqual(diagnosticsRequestToken(e),F))return e.status=401,e.set("WWW-Authenticate",'Bearer realm="litematic-renderer"'),void(e.body="Unauthorized");e.type="application/json",e.set("Content-Disposition",'attachment; filename="litematic-renderer-diagnostics.json"'),e.body=await node_fs_1.promises.readFile(u,"utf8").catch(()=>'{"format":2,"blocks":[],"errors":[]}')})}function diagnosticsRequestToken(e){const t=e?.headers?.authorization??e?.request?.headers?.authorization;if("string"==typeof t){const e=t.match(/^Bearer\s+(.+)$/i);if(e)return e[1]}return"string"==typeof e?.query?.token?e.query.token:""}function secureTextEqual(e,t){if("string"!=typeof e)return!1;const r=Buffer.from(e),a=Buffer.from(t);return r.length===a.length&&(0,node_crypto_1.timingSafeEqual)(r,a)}async function exists(e){try{return await node_fs_1.promises.access(e,node_fs_1.constants.R_OK),!0}catch{return!1}}function stringOrDefault(e,t){return"string"==typeof e&&e.trim()?e:t}
|
package/lib/jsonFile.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.readJson=readJson;const node_fs_1=require("node:fs");async function readJson(e){try{return JSON.parse(await node_fs_1.promises.readFile(e,"utf8"))}catch(e){if("ENOENT"===e?.code||e instanceof SyntaxError)return;throw e}}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/** 投影中的非空气方块及其世界坐标 */
|
|
2
|
+
export interface Block {
|
|
3
|
+
x: number;
|
|
4
|
+
y: number;
|
|
5
|
+
z: number;
|
|
6
|
+
name: string;
|
|
7
|
+
}
|
|
8
|
+
/** 从 Litematic 根标签中提取的展示元数据 */
|
|
9
|
+
export interface LitematicMetadata {
|
|
10
|
+
/** 创建投影的游戏 ID,缺失时为“未知” */
|
|
11
|
+
author: string;
|
|
12
|
+
/** 格式化后的创建时间,使用中国标准时间 */
|
|
13
|
+
createdAt: string;
|
|
14
|
+
/** 文件声明的非空气方块总数 */
|
|
15
|
+
totalBlocks?: number;
|
|
16
|
+
/** 文件声明的区域总体积 */
|
|
17
|
+
totalVolume?: number;
|
|
18
|
+
/** 投影包围盒在 X、Y、Z 轴上的尺寸 */
|
|
19
|
+
size?: [number, number, number];
|
|
20
|
+
/** Litematic 文件格式版本 */
|
|
21
|
+
litematicVersion?: number;
|
|
22
|
+
/** Minecraft 数据版本号 */
|
|
23
|
+
minecraftDataVersion?: number;
|
|
24
|
+
/** 由数据版本号推断出的 Minecraft 版本 */
|
|
25
|
+
minecraftVersion?: string;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* 解压可能使用 Gzip 的 Litematic 数据并读取 NBT 根标签
|
|
29
|
+
*
|
|
30
|
+
* @param data - Gzip 压缩或原始 NBT 数据
|
|
31
|
+
* @returns 解码后的 NBT 根复合标签
|
|
32
|
+
* @throws 数据不是受支持的 NBT 文档时抛出错误
|
|
33
|
+
*/
|
|
34
|
+
export declare function readNbtRoot(data: Buffer): Record<string, unknown>;
|
|
35
|
+
/**
|
|
36
|
+
* 将未知 NBT 值收窄为复合标签对象
|
|
37
|
+
*
|
|
38
|
+
* @param value - 待检查的 NBT 值
|
|
39
|
+
* @returns 普通对象值,无效时返回 `undefined`
|
|
40
|
+
*/
|
|
41
|
+
export declare function compoundValue(value: unknown): Record<string, unknown> | undefined;
|
|
42
|
+
/**
|
|
43
|
+
* 将安全的 NBT 数值或长整型转换为 JavaScript 数字
|
|
44
|
+
*
|
|
45
|
+
* @param value - 待转换的 NBT 值
|
|
46
|
+
* @returns 有限安全数值,无效时返回 `undefined`
|
|
47
|
+
*/
|
|
48
|
+
export declare function numericValue(value: unknown): number | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* 从 Litematic 文件读取展示和限制校验所需的元数据
|
|
51
|
+
*
|
|
52
|
+
* @param data - Gzip 压缩或未压缩的 Litematic NBT 数据
|
|
53
|
+
* @returns 规范化的作者、时间、尺寸和版本信息
|
|
54
|
+
* @throws 数据不是有效 NBT 或包含不支持的标签类型时抛出错误
|
|
55
|
+
*/
|
|
56
|
+
export declare function parseLitematicMetadata(data: Buffer): LitematicMetadata;
|
|
57
|
+
/**
|
|
58
|
+
* 校验文件声明值及每个区域的实际总体积是否超过资源限制
|
|
59
|
+
*
|
|
60
|
+
* @remarks
|
|
61
|
+
* 无效的自定义限制会回退为 5000000,区域体积使用绝对尺寸计算
|
|
62
|
+
*
|
|
63
|
+
* @param data - 原始 Litematic NBT 数据
|
|
64
|
+
* @param metadata - 预先解析的 Litematic 元数据
|
|
65
|
+
* @param configuredLimit - 允许的方块数和总体积上限
|
|
66
|
+
* @returns 校验通过时无返回值
|
|
67
|
+
* @throws 声明值、区域总体积或计算结果超过限制时抛出错误
|
|
68
|
+
*/
|
|
69
|
+
export declare function validateProjectionLimits(data: Buffer, metadata: LitematicMetadata, configuredLimit?: number): void;
|
|
70
|
+
/** 聊天消息中的元数据开关;未指定的字段保持显示 */
|
|
71
|
+
export interface MetadataDisplayOptions {
|
|
72
|
+
/** 是否显示投影名称;省略时显示,兼容旧调用方 */
|
|
73
|
+
showProjectionName?: boolean;
|
|
74
|
+
/** 是否显示保存者游戏 ID;省略时显示,兼容旧调用方 */
|
|
75
|
+
showAuthor?: boolean;
|
|
76
|
+
/** 是否显示创建时间;省略时显示,兼容旧调用方 */
|
|
77
|
+
showCreatedAt?: boolean;
|
|
78
|
+
/** 是否显示方块数和总体积;省略时显示,兼容旧调用方 */
|
|
79
|
+
showBlockStats?: boolean;
|
|
80
|
+
/** 是否显示投影尺寸;省略时显示,兼容旧调用方 */
|
|
81
|
+
showSize?: boolean;
|
|
82
|
+
/** 是否显示 Litematic 格式版本;省略时显示,兼容旧调用方 */
|
|
83
|
+
showLitematicVersion?: boolean;
|
|
84
|
+
/** 是否显示游戏版本和数据版本;省略时显示,兼容旧调用方 */
|
|
85
|
+
showGameVersion?: boolean;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* 将 Litematic 元数据格式化为适合聊天消息展示的多行文本
|
|
89
|
+
*
|
|
90
|
+
* @param metadata - 已解析的 Litematic 元数据
|
|
91
|
+
* @param filename - 可选的源文件名,用于显示投影名称
|
|
92
|
+
* @param options - 各字段的显示开关;省略时全部显示
|
|
93
|
+
* @returns 按显示开关筛选的中文文本;全部关闭时为空字符串
|
|
94
|
+
*/
|
|
95
|
+
export declare function formatLitematicMetadata(metadata: LitematicMetadata, filename?: string, options?: MetadataDisplayOptions): string;
|
|
96
|
+
/**
|
|
97
|
+
* 解析 Litematic 所有区域中的非空气方块
|
|
98
|
+
*
|
|
99
|
+
* @param data - Gzip 压缩或未压缩的 Litematic NBT 数据
|
|
100
|
+
* @returns 带世界坐标和方块名称的非空气方块列表
|
|
101
|
+
* @throws 文件缺少区域数据或不包含非空气方块时抛出错误
|
|
102
|
+
*/
|
|
103
|
+
export declare function parseLitematic(data: Buffer): Block[];
|
package/lib/litematic.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.readNbtRoot=readNbtRoot,exports.compoundValue=compoundValue,exports.numericValue=numericValue,exports.parseLitematicMetadata=parseLitematicMetadata,exports.validateProjectionLimits=validateProjectionLimits,exports.formatLitematicMetadata=formatLitematicMetadata,exports.parseLitematic=parseLitematic;const node_zlib_1=require("node:zlib"),node_path_1=require("node:path");class NbtReader{data;offset=0;constructor(t){this.data=t}ensure(t){if(!Number.isSafeInteger(t)||t<0||this.offset+t>this.data.length)throw new Error("NBT 数据提前结束或包含无效长度")}count(t=1){const e=this.int();if(e<0||e>1e7||e*t>this.data.length-this.offset)throw new Error(`NBT 集合长度无效:${e}`);return e}byte(){return this.ensure(1),this.data.readInt8(this.offset++)}ubyte(){return this.ensure(1),this.data.readUInt8(this.offset++)}short(){this.ensure(2);const t=this.data.readInt16BE(this.offset);return this.offset+=2,t}int(){this.ensure(4);const t=this.data.readInt32BE(this.offset);return this.offset+=4,t}float(){this.ensure(4);const t=this.data.readFloatBE(this.offset);return this.offset+=4,t}double(){this.ensure(8);const t=this.data.readDoubleBE(this.offset);return this.offset+=8,t}long(){this.ensure(8);const t=this.data.readBigInt64BE(this.offset);return this.offset+=8,t}text(){this.ensure(2);const t=this.data.readUInt16BE(this.offset);this.offset+=2,this.ensure(t);const e=this.data.toString("utf8",this.offset,this.offset+t);return this.offset+=t,e}readNamedRoot(){if(10!==this.ubyte())throw new Error("不是 NBT Compound 数据");return this.text(),this.value(10)}value(t){switch(t){case 0:return null;case 1:return this.byte();case 2:return this.short();case 3:return this.int();case 4:return this.long();case 5:return this.float();case 6:return this.double();case 7:{const t=this.count(),e=this.data.subarray(this.offset,this.offset+t);return this.offset+=t,e}case 8:return this.text();case 9:{const t=this.ubyte(),e=this.count();if(!t&&e)throw new Error("NBT End 列表不能包含元素");return Array.from({length:e},()=>this.value(t))}case 10:{const t={};for(;;){const e=this.ubyte();if(!e)return t;t[this.text()]=this.value(e)}}case 11:{const t=this.count(4);return Array.from({length:t},()=>this.int())}case 12:{const t=this.count(8);return Array.from({length:t},()=>this.long())}default:throw new Error(`不支持的 NBT 标签类型:${t}`)}}}const MINECRAFT_DATA_VERSIONS=new Map([[5023,"26.3"],[4903,"26.2"],[4790,"26.1.2"],[4671,"1.21.11"],[4557,"1.21.10"],[4555,"1.21.9"],[4440,"1.21.8"],[4438,"1.21.7"],[4435,"1.21.6"],[4325,"1.21.5"],[4189,"1.21.4"],[4082,"1.21.3"],[4080,"1.21.2"],[3955,"1.21.1"],[3953,"1.21"],[3839,"1.20.6"],[3837,"1.20.5"],[3700,"1.20.4"],[3698,"1.20.3"],[3578,"1.20.2"],[3465,"1.20.1"],[3463,"1.20"],[3337,"1.19.4"],[3218,"1.19.3"],[3120,"1.19.2"],[3117,"1.19.1"],[3105,"1.19"],[2975,"1.18.2"]]);function readNbtRoot(t){let e=t;const r={maxOutputLength:268435456};if(31===t[0]&&139===t[1])e=(0,node_zlib_1.gunzipSync)(t,r);else if(120===t[0])try{e=(0,node_zlib_1.inflateSync)(t,r)}catch{e=t}return new NbtReader(e).readNamedRoot()}function compoundValue(t){return!t||"object"!=typeof t||Array.isArray(t)||Buffer.isBuffer(t)?void 0:t}function numericValue(t){if("number"==typeof t&&Number.isFinite(t))return t;if("bigint"==typeof t){const e=Number(t);if(Number.isSafeInteger(e))return e}}function readMetadataSize(t,e){const r=compoundValue(e.EnclosingSize),n=r&&[numericValue(r.x),numericValue(r.y),numericValue(r.z)];if(n?.every(t=>null!=t))return n.map(t=>Math.abs(t));const a=compoundValue(t.Regions);if(!a)return;let i=1/0,o=1/0,s=1/0,u=-1/0,c=-1/0,h=-1/0;for(const t of Object.values(a)){const e=compoundValue(t),r=compoundValue(e?.Position),n=compoundValue(e?.Size),a=numericValue(r?.x),l=numericValue(r?.y),f=numericValue(r?.z),m=numericValue(n?.x),d=numericValue(n?.y),g=numericValue(n?.z);if([a,l,f,m,d,g].some(t=>null==t)||0===m||0===d||0===g)continue;const V=a+m-Math.sign(m),b=l+d-Math.sign(d),p=f+g-Math.sign(g);i=Math.min(i,a,V),o=Math.min(o,l,b),s=Math.min(s,f,p),u=Math.max(u,a,V),c=Math.max(c,l,b),h=Math.max(h,f,p)}return Number.isFinite(i)?[u-i+1,c-o+1,h-s+1]:void 0}function formatCreatedAt(t){if(null==t||t<=0)return"未知";const e=new Date(t<1e10?1e3*t:t);if(Number.isNaN(e.getTime()))return"未知";const r=new Intl.DateTimeFormat("zh-CN",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(e),n=Object.fromEntries(r.map(t=>[t.type,t.value]));return`${n.year}-${n.month}-${n.day} ${n.hour}:${n.minute}:${n.second}`}function parseLitematicMetadata(t){const e=readNbtRoot(t),r=compoundValue(e.Metadata)??{},n=numericValue(e.MinecraftDataVersion);return{author:"string"==typeof r.Author&&r.Author.trim()?r.Author.trim():"未知",createdAt:formatCreatedAt(numericValue(r.TimeCreated)),totalBlocks:numericValue(r.TotalBlocks),totalVolume:numericValue(r.TotalVolume),size:readMetadataSize(e,r),litematicVersion:numericValue(e.Version),minecraftDataVersion:n,minecraftVersion:null==n?void 0:MINECRAFT_DATA_VERSIONS.get(n)}}function validateProjectionLimits(t,e,r){const n=Number.isSafeInteger(r)&&r>0?r:5e6,a=()=>{throw new Error(`投影方块数或区域体积超过 ${n.toLocaleString("en-US")} 限制`)};(Math.abs(e.totalBlocks??0)>n||Math.abs(e.totalVolume??0)>n)&&a();const i=compoundValue(readNbtRoot(t).Regions);if(!i)return;let o=0;for(const t of Object.values(i)){const e=compoundValue(compoundValue(t)?.Size),r=[numericValue(e?.x),numericValue(e?.y),numericValue(e?.z)];if(r.some(t=>null==t))continue;const i=r.reduce((t,e)=>t*Math.abs(e),1);(!Number.isSafeInteger(i)||i>n-o)&&a(),o+=i}}function formatLitematicMetadata(t,e,r={}){const n=null==t.totalBlocks?"未知":String(t.totalBlocks),a=null==t.totalVolume?"未知":String(t.totalVolume),i=t.size?.join(" × ")??"未知",o=null==t.litematicVersion?"未知":String(t.litematicVersion),s=t.minecraftVersion??"未知",u=null==t.minecraftDataVersion?"":`(数据版本:${t.minecraftDataVersion})`,c="string"==typeof e&&e.trim()?(0,node_path_1.basename)(e).replace(/\.(?:litematic|schem|nbt)$/i,""):"";return[...!1!==r.showProjectionName&&c?[`投影名称:${c}`]:[],...!1!==r.showAuthor?[`保存者游戏 ID:${t.author}`]:[],...!1!==r.showCreatedAt?[`创建时间:${t.createdAt}`]:[],...!1!==r.showBlockStats?[`方块数/体积:${n}/${a}`]:[],...!1!==r.showSize?[`尺寸:${i}`]:[],...!1!==r.showLitematicVersion?[`Litematic 版本:${o}`]:[],...!1!==r.showGameVersion?[`游戏版本:${s}${u}`]:[]].join("\n")}function parseLitematic(t){const e=readNbtRoot(t).Regions;if(!e||"object"!=typeof e)throw new Error("文件不含 Litematica Regions 数据");const r=[];for(const t of Object.values(e))parseRegion(t,r);if(!r.length)throw new Error("投影中没有非空气方块");return r}function parseRegion(t,e){const r=t.Position,n=t.Size,a=t.BlockStatePalette,i=t.BlockStates;if(!(r&&n&&Array.isArray(a)&&Array.isArray(i)))return;const o=Math.abs(n.x),s=Math.abs(n.y),u=Math.abs(n.z),c=o*s*u;if(!c)return;const h=Math.max(2,Math.ceil(Math.log2(a.length))),l=n.x<0?-1:1,f=n.y<0?-1:1,m=n.z<0?-1:1;for(let t=0;t<c;t++){const n=unpackState(i,t,h),s=a[n]?.Name;if(!s||"minecraft:air"===s||"minecraft:cave_air"===s||"minecraft:void_air"===s)continue;const c=t%o,d=Math.floor(t/o)%u,g=Math.floor(t/(o*u));e.push({x:r.x+c*l,y:r.y+g*f,z:r.z+d*m,name:s})}}function unpackState(t,e,r){const n=BigInt(e*r),a=Number(n/64n),i=n%64n;if(a>=t.length)return 0;const o=(1n<<BigInt(r))-1n;let s=BigInt.asUintN(64,t[a])>>i&o;return i+BigInt(r)>64n&&a+1<t.length&&(s|=BigInt.asUintN(64,t[a+1])<<64n-i&o),Number(s)}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { h } from "koishi";
|
|
2
|
+
import type { Session } from "koishi";
|
|
3
|
+
import { PNG } from "pngjs";
|
|
4
|
+
import { type ImageSendLayout, type Config, type QqBotType, type SendMode } from "./config";
|
|
5
|
+
/** 已写入磁盘、可发送给会话的渲染图 */
|
|
6
|
+
export interface ImageResult {
|
|
7
|
+
title: string;
|
|
8
|
+
path: string;
|
|
9
|
+
}
|
|
10
|
+
/** 已结合全局配置和群聊覆盖项的最终发送选项 */
|
|
11
|
+
export interface ResolvedSendOptions {
|
|
12
|
+
/** 当前 QQ 机器人的接入方式 */
|
|
13
|
+
qqBotType: QqBotType;
|
|
14
|
+
/** 多张图片的发送方式 */
|
|
15
|
+
sendMode: SendMode;
|
|
16
|
+
/** 是否引用并按平台能力提及发送者 */
|
|
17
|
+
replyAndMention: boolean;
|
|
18
|
+
/** 是否在图片前显示视图标题 */
|
|
19
|
+
showViewTitles: boolean;
|
|
20
|
+
/** 官方 QQ 的布局;Agent 要求拆分时覆盖为 separate */
|
|
21
|
+
imageSendLayout?: ImageSendLayout;
|
|
22
|
+
/** 是否生成并发送六面正交合成图 */
|
|
23
|
+
sixFaceOverview: boolean;
|
|
24
|
+
}
|
|
25
|
+
/** 解析消息发送选项所需的配置子集 */
|
|
26
|
+
type SendConfig = Pick<Config, "sendAsForward" | "replyAndMention" | "groupSendOptions"> & Partial<Pick<Config, "qqBotType" | "showViewTitles" | "sixFaceOverview" | "imageSendLayout">>;
|
|
27
|
+
/**
|
|
28
|
+
* 合并全局发送配置与指定群聊最后一条匹配的覆盖项
|
|
29
|
+
*
|
|
30
|
+
* @param config - 全局发送配置及群聊覆盖项
|
|
31
|
+
* @param groupId - 当前 QQ 群号
|
|
32
|
+
* @returns 适用于当前会话的最终发送选项
|
|
33
|
+
*/
|
|
34
|
+
export declare function resolveSendOptions(config: SendConfig, groupId?: string): ResolvedSendOptions;
|
|
35
|
+
/**
|
|
36
|
+
* 根据 QQ 接入类型和发送模式发送渲染图及投影元数据
|
|
37
|
+
*
|
|
38
|
+
* @remarks
|
|
39
|
+
* 官方 QQ 按布局拼接或逐张发送,合成图超过 10 MiB 时拆分;自建 QQ 保留合并转发或联合消息
|
|
40
|
+
*
|
|
41
|
+
* @param session - 接收渲染结果的 Koishi 会话
|
|
42
|
+
* @param images - 已写入磁盘的渲染图片
|
|
43
|
+
* @param metadata - 格式化后的投影元数据
|
|
44
|
+
* @param options - 已解析的发送选项
|
|
45
|
+
* @param projectionName - 在成功消息中展示的投影名称
|
|
46
|
+
* @param warn - 合成图过大时接收拆图原因的可选日志回调
|
|
47
|
+
* @returns 所有图片和元数据发送完成后解决的 Promise
|
|
48
|
+
* @throws 图片读取、合成或消息发送失败时抛出错误
|
|
49
|
+
*/
|
|
50
|
+
export declare function sendImages(session: Session, images: ImageResult[], metadata: string, options: ResolvedSendOptions, projectionName?: string, warn?: (message: string) => void): Promise<void>;
|
|
51
|
+
/**
|
|
52
|
+
* 将轴测图和可选六面图排版为官方 QQ 使用的单张总览 PNG
|
|
53
|
+
*
|
|
54
|
+
* @param images - 要合成的磁盘 PNG 图片
|
|
55
|
+
* @param layout - 横向或竖向排列,默认横向
|
|
56
|
+
* @returns 写入首张图片所在目录的总览图绝对路径
|
|
57
|
+
* @throws 图片列表为空、图片无效或文件系统操作失败时抛出错误
|
|
58
|
+
*/
|
|
59
|
+
export declare function composeQqOverview(images: ImageResult[], layout?: "horizontal" | "vertical"): Promise<string>;
|
|
60
|
+
/**
|
|
61
|
+
* 使用最近邻采样将一张 PNG 绘制到目标 PNG 的指定区域
|
|
62
|
+
*
|
|
63
|
+
* @param target - 接收像素的目标 PNG
|
|
64
|
+
* @param placement - 源图和目标位置及尺寸
|
|
65
|
+
* @returns 无返回值
|
|
66
|
+
*/
|
|
67
|
+
export declare function drawScaledPng(target: PNG, placement: {
|
|
68
|
+
image: PNG;
|
|
69
|
+
x: number;
|
|
70
|
+
y: number;
|
|
71
|
+
width: number;
|
|
72
|
+
height: number;
|
|
73
|
+
}): void;
|
|
74
|
+
/**
|
|
75
|
+
* 创建适合当前 QQ 接入方式的引用和提及消息元素
|
|
76
|
+
*
|
|
77
|
+
* @param session - 要回复的 Koishi 会话
|
|
78
|
+
* @param qqBotType - QQ 机器人接入方式
|
|
79
|
+
* @returns 官方 QQ 最多包含引用,自建 QQ 还会包含发送者提及
|
|
80
|
+
*/
|
|
81
|
+
export declare function replyElements(session: Session, qqBotType?: QqBotType): h[];
|
|
82
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.resolveSendOptions=resolveSendOptions,exports.sendImages=sendImages,exports.composeQqOverview=composeQqOverview,exports.drawScaledPng=drawScaledPng,exports.replyElements=replyElements;const koishi_1=require("koishi"),node_fs_1=require("node:fs"),node_path_1=require("node:path"),node_url_1=require("node:url"),pngjs_1=require("pngjs"),config_1=require("./config");function resolveSendOptions(e,t){const o=t?[...e.groupSendOptions].reverse().find(e=>e.groupId.trim()===t):void 0,i="enabled"===o?.replyAndMention||"disabled"!==o?.replyAndMention&&e.replyAndMention,n=o?.sendMode??(e.sendAsForward?"forward":"combined"),s=e.qqBotType??"selfHosted";return{qqBotType:s,imageSendLayout:(0,config_1.normalizeImageSendLayout)(e.imageSendLayout),sendMode:n,replyAndMention:i,showViewTitles:e.showViewTitles??!1,sixFaceOverview:("official"===s||"forward"===n)&&(e.sixFaceOverview??!0)}}async function sendImages(e,t,o,i,n="schematic",s){if("official"===i.qqBotType){const a=(0,config_1.normalizeImageSendLayout)(i.imageSendLayout),r=`${o?`${o}\n`:""}${n} 已渲染成功,结果如上`,h=i.replyAndMention&&e.messageId?[(0,koishi_1.h)("quote",{id:e.messageId})]:[];if("separate"!==a){const o=await composeQqOverview(t,a);if((await node_fs_1.promises.stat(o)).size<=10485760)return void await e.send([...h,koishi_1.h.image((0,node_url_1.pathToFileURL)(o).href),(0,koishi_1.h)("text",{content:r})]);s?.("官方 QQ 合成图超过 10 MiB,改为逐张发送")}for(const[o,i]of t.entries())await e.send([...0===o?h:[],koishi_1.h.image((0,node_url_1.pathToFileURL)((0,node_path_1.resolve)(i.path)).href),...o===t.length-1?[(0,koishi_1.h)("text",{content:r})]:[]]);return}const a=await Promise.all(t.map(async({title:e,path:t})=>({title:e,source:`base64://${(await node_fs_1.promises.readFile(t)).toString("base64")}`}))),r=a.map(({title:t,source:o})=>(0,koishi_1.h)("message",{userId:e.selfId,nickname:"投影渲染"},[...i.showViewTitles?[(0,koishi_1.h)("text",{content:t})]:[],(0,koishi_1.h)("img",{src:o})])),h=(0,koishi_1.h)("message",{userId:e.selfId,nickname:"投影信息"},[(0,koishi_1.h)("text",{content:o})]);if("forward"===i.sendMode)return void await e.send((0,koishi_1.h)("figure",{},[...r,...o?[h]:[]]));const d=i.replyAndMention?replyElements(e,i.qqBotType):[],l=a.flatMap(({title:e,source:t},o)=>[...i.showViewTitles?[(0,koishi_1.h)("text",{content:`${o?"\n":""}${e}\n`})]:[],(0,koishi_1.h)("img",{src:t})]);await e.send([...d,...l,(0,koishi_1.h)("text",{content:`\n${o}\n${n} 已渲染成功,结果如上`})])}async function composeQqOverview(e,t="horizontal"){if(!e.length)throw new Error("没有可合并的渲染图片");const o=await Promise.all(e.map(async e=>pngjs_1.PNG.sync.read(await node_fs_1.promises.readFile((0,node_path_1.resolve)(e.path))))),i=Math.max(4,Math.round(.01*Math.max(...o.map(e=>Math.max(e.width,e.height))))),n=[],s="vertical"===t,a=s?Math.max(...o.map(e=>e.width)):Math.max(...o.map(e=>e.height));let r=s?a:0,h=s?0:a;for(const e of o){const t=s?a:Math.max(1,Math.round(e.width*a/e.height)),o=s?Math.max(1,Math.round(e.height*a/e.width)):a;s?h+=o:r+=t}const d=i*Math.max(0,o.length-1);s?h+=d:r+=d;let l=0;for(const e of o){const t=s?a:Math.max(1,Math.round(e.width*a/e.height)),o=s?Math.max(1,Math.round(e.height*a/e.width)):a;n.push({image:e,x:s?Math.floor((r-t)/2):l,y:s?l:Math.floor((h-o)/2),width:t,height:o}),l+=(s?o:t)+i}const c=new pngjs_1.PNG({width:r,height:h});for(const e of n)drawScaledPng(c,e);const p=(0,node_path_1.resolve)((0,node_path_1.dirname)(e[0].path),"qq-overview.png");return await node_fs_1.promises.writeFile(p,pngjs_1.PNG.sync.write(c)),p}function drawScaledPng(e,t){const{image:o,x:i,y:n,width:s,height:a}=t;for(let t=0;t<a;t++){const r=Math.min(o.height-1,Math.floor((t+.5)*o.height/a));for(let a=0;a<s;a++){const h=Math.min(o.width-1,Math.floor((a+.5)*o.width/s)),d=4*(r*o.width+h),l=4*((n+t)*e.width+i+a);o.data.copy(e.data,l,d,d+4)}}}function replyElements(e,t=("qq"===e.platform?"official":"selfHosted")){const o=[];return e.messageId&&o.push((0,koishi_1.h)("quote",{id:e.messageId})),"selfHosted"===t&&e.userId&&(o.push((0,koishi_1.h)("at",{id:e.userId})),o.push((0,koishi_1.h)("text",{content:"\n"}))),o}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { Context, Session } from "koishi";
|
|
2
|
+
import type { Config } from "./config";
|
|
3
|
+
export interface DownloadOptions {
|
|
4
|
+
/** trusted 仅校验协议;public 还会拒绝解析到私网或保留地址的主机。 */
|
|
5
|
+
network?: "trusted" | "public";
|
|
6
|
+
allowedHosts?: string[];
|
|
7
|
+
maxRedirects?: number;
|
|
8
|
+
}
|
|
9
|
+
type AddressResolver = (hostname: string) => Promise<Array<{
|
|
10
|
+
address: string;
|
|
11
|
+
family: number;
|
|
12
|
+
}>>;
|
|
13
|
+
interface FileElement {
|
|
14
|
+
name?: string;
|
|
15
|
+
filename?: string;
|
|
16
|
+
file_name?: string;
|
|
17
|
+
fileName?: string;
|
|
18
|
+
url?: string;
|
|
19
|
+
src?: string;
|
|
20
|
+
file?: string | Record<string, unknown>;
|
|
21
|
+
size?: string | number;
|
|
22
|
+
id?: string;
|
|
23
|
+
file_id?: string;
|
|
24
|
+
fileId?: string;
|
|
25
|
+
busid?: string | number;
|
|
26
|
+
}
|
|
27
|
+
/** 已写入磁盘、可发送给会话的渲染图 */
|
|
28
|
+
/** 查找上传文件所需的最小会话数据 */
|
|
29
|
+
type FileSession = Pick<Session, "elements" | "content"> & {
|
|
30
|
+
event?: unknown;
|
|
31
|
+
_data?: unknown;
|
|
32
|
+
data?: unknown;
|
|
33
|
+
message?: unknown;
|
|
34
|
+
};
|
|
35
|
+
/** 判断群聊、频道或显式启用的私聊是否允许进入渲染流程。 */
|
|
36
|
+
export declare function canRenderInSession(session: Pick<Session, "guildId" | "isDirect">, allowPrivateRender: boolean): boolean;
|
|
37
|
+
/** 群白/黑名单各自由独立开关控制,黑名单优先。 */
|
|
38
|
+
export declare function isGroupAllowed(config: Pick<Config, "groupWhitelist" | "groupBlacklist" | "groupWhitelistEnabled" | "groupBlacklistEnabled">, groupId?: string | null): boolean;
|
|
39
|
+
/**
|
|
40
|
+
* 在 Koishi 会话元素及常见适配器原始事件字段中查找支持的投影文件
|
|
41
|
+
*
|
|
42
|
+
* @param session - 包含消息元素或适配器原始数据的会话
|
|
43
|
+
* @returns 首个识别出的 `.litematic`、`.schem` 或 `.nbt` 文件
|
|
44
|
+
*/
|
|
45
|
+
export declare function findLitematicFile(session: FileSession): FileElement | undefined;
|
|
46
|
+
/** 判断文件名是否使用受支持的投影格式扩展名。 */
|
|
47
|
+
export declare function isSchematicFilename(filename?: string): boolean;
|
|
48
|
+
/**
|
|
49
|
+
* 从不同适配器使用的字段中读取规范化文件名
|
|
50
|
+
*
|
|
51
|
+
* @param file - 兼容多种字段命名的文件元素
|
|
52
|
+
* @returns 去除首尾空白的文件名,字段无效时返回 `undefined`
|
|
53
|
+
*/
|
|
54
|
+
export declare function fileName(file: FileElement): string | undefined;
|
|
55
|
+
/**
|
|
56
|
+
* 从文件元素或 OneBot 群文件接口解析可下载地址
|
|
57
|
+
*
|
|
58
|
+
* @param session - 提供机器人接口和群号的 Koishi 会话
|
|
59
|
+
* @param file - 待解析的文件元素
|
|
60
|
+
* @returns 直接地址或 OneBot 查询结果,无法解析时返回 `undefined`
|
|
61
|
+
* @throws OneBot 群文件接口调用失败时抛出错误
|
|
62
|
+
*/
|
|
63
|
+
export declare function resolveFileUrl(session: Session, file: FileElement): Promise<any>;
|
|
64
|
+
/**
|
|
65
|
+
* 判断已知文件大小是否有效且未超过限制
|
|
66
|
+
*
|
|
67
|
+
* @param size - 适配器报告的文件字节数
|
|
68
|
+
* @param limit - 允许的最大字节数
|
|
69
|
+
* @returns 大小未知或位于有效范围内时返回 `true`
|
|
70
|
+
*/
|
|
71
|
+
export declare function isUnderLimit(size: string | number | undefined, limit: number): boolean;
|
|
72
|
+
/**
|
|
73
|
+
* 下载文件,并在读取后校验实际字节数
|
|
74
|
+
*
|
|
75
|
+
* @param ctx - 提供 HTTP 服务的 Koishi 上下文
|
|
76
|
+
* @param url - 文件直链
|
|
77
|
+
* @param maxSize - 允许的最大字节数
|
|
78
|
+
* @param timeout - 下载超时时间,单位为毫秒
|
|
79
|
+
* @returns 下载完成的文件缓冲区
|
|
80
|
+
* @throws 网络失败、超时或实际大小超限时抛出错误
|
|
81
|
+
*/
|
|
82
|
+
export declare function download(ctx: Context, url: string, maxSize: number, timeout: number, options?: DownloadOptions): Promise<Buffer<ArrayBufferLike>>;
|
|
83
|
+
/** 校验下载地址协议,并按需拒绝本机、私网和保留地址。 */
|
|
84
|
+
export declare function validateDownloadUrl(value: string, network?: "trusted" | "public", allowedHosts?: string[], resolver?: AddressResolver): Promise<URL>;
|
|
85
|
+
/**
|
|
86
|
+
* 判断适配器报告的文件大小是否明确超过限制
|
|
87
|
+
*
|
|
88
|
+
* @param size - 适配器报告的文件字节数
|
|
89
|
+
* @param limit - 允许的最大字节数
|
|
90
|
+
* @returns 大小有效且超过限制时返回 `true`
|
|
91
|
+
*/
|
|
92
|
+
export declare function isOverLimit(size: string | number | undefined, limit: number): boolean;
|
|
93
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.canRenderInSession=canRenderInSession,exports.isGroupAllowed=isGroupAllowed,exports.findLitematicFile=findLitematicFile,exports.isSchematicFilename=isSchematicFilename,exports.fileName=fileName,exports.resolveFileUrl=resolveFileUrl,exports.isUnderLimit=isUnderLimit,exports.download=download,exports.validateDownloadUrl=validateDownloadUrl,exports.isOverLimit=isOverLimit;const koishi_1=require("koishi"),promises_1=require("node:dns/promises"),node_net_1=require("node:net"),node_path_1=require("node:path"),PRIVATE_NETWORKS=new node_net_1.BlockList;for(const[e,t]of[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.0.2.0",24],["192.168.0.0",16],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24],["224.0.0.0",4],["240.0.0.0",4]])PRIVATE_NETWORKS.addSubnet(e,t,"ipv4");for(const[e,t]of[["::",128],["::1",128],["::ffff:0:0",96],["100::",64],["2001:db8::",32],["fc00::",7],["fe80::",10],["ff00::",8]])PRIVATE_NETWORKS.addSubnet(e,t,"ipv6");function fileElements(e){return[...e.elements??[],...koishi_1.h.parse(e.content??"")]}function canRenderInSession(e,t){return Boolean(e.guildId)||Boolean(e.isDirect)&&t}function isGroupAllowed(e,t){if(!t)return!0;const i=t.trim();return!i||(!e.groupBlacklistEnabled||!e.groupBlacklist.some(e=>e.trim()===i))&&!(e.groupWhitelistEnabled&&e.groupWhitelist.length>0&&!e.groupWhitelist.some(e=>e.trim()===i))}function findLitematicFile(e){const t=fileElements(e).filter(e=>"file"===e.type),i=t.find(e=>isSchematicFilename(fileName(e.attrs)));if(i?.attrs)return i.attrs;for(const t of[e.event,e._data,e.data,e.message]){const e=findLitematicInFilePayload(t);if(e)return e}const r=inferLitematicName(e.content);return r&&t[0]?.attrs?{...t[0].attrs,name:r}:void 0}function findLitematicInFilePayload(e,t=new Set,i=0){if(!e||"object"!=typeof e||i>6||t.has(e))return;t.add(e);const r=e,n=r,o=n.file&&"object"==typeof n.file?n.file:void 0;if(o&&isSchematicFilename(fileName(o)))return{...o,id:o.id??n.id,file_id:o.file_id??n.file_id,fileId:o.fileId??n.fileId,busid:o.busid??n.busid};if(isSchematicFilename(fileName(n)))return n;for(const[e,n]of Object.entries(r))if(n&&"object"==typeof n&&/file|upload|message|data|event/i.test(e)){const e=findLitematicInFilePayload(n,t,i+1);if(e)return e}}function inferLitematicName(e){if(!e)return;const t=e.match(/(?:file|文件)\s+(.+?\.(?:litematic|schem|nbt))(?=$|[\]】\r\n])/i);return t?.[1]?t[1].trim():e.match(/([^\s\]】<>"']+\.(?:litematic|schem|nbt))(?=$|[\s\]】])/i)?.[1]?.trim()}function isSchematicFilename(e){return[".litematic",".schem",".nbt"].includes((0,node_path_1.extname)(e??"").toLowerCase())}function fileName(e){const t=e.file&&"object"==typeof e.file?e.file:void 0,i=e.name??e.filename??e.file_name??e.fileName??t?.name??t?.filename??t?.file_name??t?.fileName;return"string"==typeof i&&i.trim()?i.trim():void 0}async function resolveFileUrl(e,t){const i=t.file&&"object"==typeof t.file?t.file:void 0,r=t.url??t.src??("string"==typeof t.file?t.file:void 0)??i?.url??i?.src;if("string"==typeof r&&r)return r;const n=t.id??t.file_id??t.fileId??i?.id??i?.file_id??i?.fileId,o=e.bot.internal;if(!e.guildId||!n||"function"!=typeof o?.getGroupFileUrl)return;const a=await o.getGroupFileUrl(e.guildId,n,Number(t.busid??i?.busid??0));return"string"==typeof a?a:a?.url}function isUnderLimit(e,t){if(null==e||""===e)return!0;const i=Number(e);return Number.isFinite(i)&&i>0&&i<=t}async function download(e,t,i,r,n={}){const o=Math.max(0,Math.min(10,n.maxRedirects??5));let a=t;for(let t=0;t<=o;t++){await validateDownloadUrl(a,n.network??"trusted",n.allowedHosts);const l=await e.http(a,{method:"GET",redirect:"manual",timeout:r,validateStatus:e=>e>=200&&e<400,responseType:async e=>{if(e.status>=300)return await(e.body?.cancel()),Buffer.alloc(0);const t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>i)throw fileSizeError(i);if(!e.body)return Buffer.alloc(0);const r=e.body.getReader(),n=[];let o=0;try{for(;;){const{done:e,value:t}=await r.read();if(e)break;if(o+=t.byteLength,o>i)throw await r.cancel(),fileSizeError(i);n.push(Buffer.from(t))}}finally{r.releaseLock()}return Buffer.concat(n,o)}});if(l.status<300)return l.data;const s=l.headers.get("location");if(!s)throw new Error(`下载重定向缺少 Location:HTTP ${l.status}`);if(t===o)throw new Error(`下载重定向超过 ${o} 次限制`);a=new URL(s,a).href}throw new Error("下载失败")}async function validateDownloadUrl(e,t="public",i=[],r=async e=>(0,promises_1.lookup)(e,{all:!0,verbatim:!0})){let n;try{n=new URL(e)}catch{throw new Error("文件直链不是有效 URL")}if("http:"!==n.protocol&&"https:"!==n.protocol)throw new Error("文件直链只允许 HTTP 或 HTTPS 协议");if(n.username||n.password)throw new Error("文件直链不能包含用户名或密码");if("trusted"===t)return n;const o=n.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(new Set(i.filter(e=>"string"==typeof e).map(e=>e.trim().toLowerCase().replace(/\.$/,"")).filter(Boolean)).has(o))return n;if("localhost"===o||o.endsWith(".localhost"))throw new Error("文件直链不能访问本机或私有网络");const a=(0,node_net_1.isIP)(o)?[{address:o,family:(0,node_net_1.isIP)(o)}]:await r(o);if(!a.length)throw new Error("文件直链主机无法解析");if(a.some(({address:e,family:t})=>PRIVATE_NETWORKS.check(e,6===t?"ipv6":"ipv4")))throw new Error("文件直链不能访问本机、私网或保留网络");return n}function fileSizeError(e){return new Error(`文件超过 ${(e/1024/1024).toFixed(2)} MB 限制`)}function isOverLimit(e,t){if(null==e||""===e)return!1;const i=Number(e);return Number.isFinite(i)&&i>t}
|