@tbox.cn/app-sdk-server 0.26.4 → 0.26.6

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 CHANGED
@@ -12,6 +12,8 @@ integrations/provider catalog、dev 平台设施(inspector)。
12
12
 
13
13
  ## 开发预览异常插件
14
14
 
15
- `./platform` 导出 `previewErrorReporter({ observationMs?: number, enabled?: boolean })`,供 Vite 6 配置注册。默认观察时间 5000ms,范围 5000–60000ms;生产构建和 vitest 不注入。插件自带浏览器异常预捕获,经应用现有 HMR 接收后输出结构化终端记录,供 CodingBox 复用 build_error 展示。
15
+ `./platform` 导出 `previewErrorReporter({ observationMs?: number, enabled?: boolean, ignoredScriptUrls?: readonly string[] })`,供 Vite 6 配置注册。默认观察时间 5000ms,范围 5000–60000ms;生产构建和 vitest 不注入。插件自带浏览器异常预捕获,经应用现有 HMR 接收后输出结构化终端记录,供 CodingBox 复用 build_error 展示。
16
+
17
+ `ignoredScriptUrls` 用于显式排除非关键第三方脚本,例如 `previewErrorReporter({ ignoredScriptUrls: ['https://metrics.example/sdk.js'] })`。浏览器噪音的默认过滤规则、URL 匹配边界与页面观察语义见下方模板参考。
16
18
 
17
19
  只覆盖 dev 文档的未捕获 JS、Promise rejection 和脚本加载失败;不劫持 console,不需要 client SDK 初始化,不保证业务恢复或覆盖 static 页面。应用需保留插件注册与 HMR 接线。详细契约见 [模板参考](../../docs/reference/templates.md#开发预览异常上报)。
@@ -139,6 +139,10 @@ interface PreviewErrorReporterOptions {
139
139
  /** Minimum 5000ms. Only new, connected, error-free documents clear old snapshots. */
140
140
  observationMs?: number;
141
141
  enabled?: boolean;
142
+ /** Explicit third-party script URLs to ignore (absolute HTTP(S); query/hash are ignored). */
143
+ ignoredScriptUrls?: readonly string[];
144
+ /** Exact document pathnames to omit from capture; query/hash are ignored. Defaults to none. */
145
+ excludedPagePaths?: readonly string[];
142
146
  }
143
147
  /** Dev-only browser exception transport over the application's existing Vite HMR socket. */
144
148
  declare function previewErrorReporter(options?: PreviewErrorReporterOptions): Plugin;
@@ -1,20 +1,20 @@
1
- var st="https://env-00jx4e7pq1un-static.normal.cloudstatic.cn/asset/codingbox/inspector.umd.js",Y="/__vs_inspector__.js",ue=`<script src="${Y}" defer></script>`,Z="",de=!1;async function at(e=3){for(let t=0;t<e;t++)try{let n=await fetch(st);if(!n.ok)throw new Error(`HTTP ${n.status}`);Z=await n.text(),de=!0,console.log(`[inspector] runtime loaded (${Z.length} bytes)`);return}catch(n){console.warn(`[inspector] fetch failed (attempt ${t+1}/${e}):`,n.message),t<e-1&&await new Promise(s=>setTimeout(s,1e3*(t+1)))}console.error("[inspector] runtime unavailable; inspector script will be skipped")}function Pe(e){if(e.includes(Y))return e;let t=e.search(/<\/head\s*>/i);if(t!==-1)return e.slice(0,t)+ue+e.slice(t);let n=e.search(/<body[\s>]/i);return n!==-1?e.slice(0,n)+ue+e.slice(n):e}function ct(){return de}function lt(e){at(),e.get(Y,(t,n)=>{if(!Z){n.status(503).type("application/javascript").send("// inspector runtime not ready");return}n.type("application/javascript").set("Cache-Control","no-cache").send(Z)}),e.use((t,n,s)=>{if(!de)return s();let c=[],a=n.write.bind(n),f=n.end.bind(n),h=!1,p=()=>{let g=String(n.getHeader("content-type")||""),u=String(n.getHeader("content-encoding")||"");return g.includes("text/html")&&!u};n.write=((g,...u)=>(!h&&!c.length&&(h=p()),h&&g?(c.push(Buffer.isBuffer(g)?g:Buffer.from(g)),!0):a(g,...u))),n.end=((g,...u)=>{if(!h&&!c.length&&(h=p()),h){g&&c.push(Buffer.isBuffer(g)?g:Buffer.from(g));try{let o=Buffer.concat(c).toString("utf8"),v=Pe(o);return n.setHeader("Content-Length",Buffer.byteLength(v)),f(v,...u)}catch(o){return console.warn("[inspector] inject failed, fallback to original:",o.message),f(Buffer.concat(c),...u)}}return f(g,...u)}),s()})}import{createHash as Ge,randomUUID as Et,timingSafeEqual as xt}from"crypto";import{existsSync as St,readFileSync as _t,statSync as Rt}from"fs";import{readFile as X}from"fs/promises";import Dt from"express";import H from"path";var He=["api","ws","assets"],ut=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu,dt=/^[a-z][a-z0-9-]*$/,ft=/^[a-z0-9][a-z0-9-]*$/,pt=/^[a-zA-Z][a-zA-Z0-9-]*$/;function V(e){if(!e.includes("%"))return e;try{return decodeURI(e)}catch{return null}}function B(e){return e.normalize("NFC").toLowerCase()}function Q(e){if(e==="/")return;let t=e.slice(1).split("/");if(!t.some(n=>n.length===0))return`${t.join("/")}/index.html`}function Ne(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ce(e,t={}){let n=[],s=[],c=new Set([...He,...t.reservedSegments??[]]),a=t.maxRoutes??100;if(!Array.isArray(e))return{ok:!1,errors:["E01: routes.json 顶层必须是数组"],warnings:s,entries:[]};e.length>a&&n.push(`E09: 路由总数 ${e.length} 超过上限 ${a}`);for(let[u,o]of e.entries())Ne(o)||n.push(`E01: 第 ${u} 项必须是对象`);if(n.length>0)return{ok:!1,errors:n,warnings:s,entries:[]};let f=[],h=new Set,p=new Map,g=0;for(let[u,o]of e.entries()){let v=`第 ${u} 项`,m=o.id;if(typeof m!="string"||m.length===0){n.push(`E02: ${v} 缺少 id`);continue}if(m.length>64||!dt.test(m)){n.push(`E03: ${v} id "${m}" 不符合 ^[a-z][a-z0-9-]*$(≤64 字符)`);continue}if(ut.test(m)){n.push(`E03: ${v} id "${m}" 是 Windows 保留名`);continue}if(h.has(m)){n.push(`E02: id "${m}" 重复`);continue}h.add(m);let i=o.path;if(typeof i!="string"||i.length===0||i[0]!=="/"){n.push(`E04: ${v}(id=${m})path 必须以 / 开头的字符串`);continue}let y=V(i);if(y===null){n.push(`E12: ${v}(id=${m})path 含非法百分号编码`);continue}if(y!=="/"){let M=y.slice(1).split("/").find(j=>!ft.test(j));if(M!==void 0){n.push(`E04: ${v}(id=${m})path 段 "${M}" 不合法——每段必须匹配 ^[a-z0-9][a-z0-9-]*$(禁点号/冒号/通配/下划线;动态路由已按方案裁决放弃)`);continue}}let d=B(y),R=p.get(d);if(R!==void 0){n.push(`E12: path "${i}"(id=${m})与 "${R}" 解码归一后冲突`);continue}if(p.set(d,i),y!=="/"){let I=y.slice(1).split("/")[0];if(c.has(B(`/${I}`).slice(1))){n.push(`E08: ${v}(id=${m})首段 "${I}" 落在保留命名空间(${[...c].join("/")})`);continue}}y==="/"&&(g+=1,o.page!==void 0&&n.push(`E05: 根路由(id=${m})禁用 page 字段——根入口恒为应用根 main 链`),(o.title!==void 0||o.meta!==void 0)&&s.push(`根路由(id=${m})的 title/meta 不生效——根文档标题维持应用 index.html 静态值(租户主题运行时覆写)`));let b;if(o.title!==void 0){if(typeof o.title!="string"||o.title.length===0){n.push(`E04: ${v}(id=${m})title 必须是非空字符串`);continue}if(o.title.length>200){n.push(`E04: ${v}(id=${m})title 超过 200 字符`);continue}b=o.title}let S;if(o.meta!==void 0){if(!Ne(o.meta)){n.push(`E04: ${v}(id=${m})meta 必须是 Record<string, string>`);continue}let I=Object.keys(o.meta);if(I.length>20){n.push(`E04: ${v}(id=${m})meta 条目超过 20`);continue}let M=I.find(U=>!pt.test(U));if(M!==void 0){n.push(`E04: ${v}(id=${m})meta 键 "${M}" 不符合 ^[a-zA-Z][a-zA-Z0-9-]*$`);continue}let j=I.find(U=>typeof o.meta[U]!="string");if(j!==void 0){n.push(`E04: ${v}(id=${m})meta["${j}"] 必须是字符串`);continue}let q=I.find(U=>o.meta[U].length>500);if(q!==void 0){n.push(`E04: ${v}(id=${m})meta["${q}"] 超过 500 字符`);continue}S=o.meta}let P;if(o.page!==void 0){if(typeof o.page!="string"||!o.page.startsWith("@/")){n.push(`E04: ${v}(id=${m})page 必须以 @/ 开头的模块路径`);continue}P=o.page}f.push({id:m,path:y,...b!==void 0?{title:b}:{},...S?{meta:S}:{},...P?{page:P}:{}})}return g===0?n.push('E05: 必须恰有一个 path 为 "/" 的根路由'):g>1&&n.push(`E05: 根路由数量 ${g} > 1`),{ok:n.length===0,errors:n,warnings:s,entries:f}}function W(e){let t;try{t=JSON.parse(e)}catch(n){return{ok:!1,errors:[`E01: routes.json JSON 解析失败:${n.message}`],warnings:[],entries:[]}}return Ce(t)}import{randomUUID as Ae}from"crypto";import{existsSync as te,mkdirSync as mt,readFileSync as Oe,readdirSync as gt,renameSync as fe,rmSync as ve,writeFileSync as ee}from"fs";import _ from"path";var Le="/src/main.tsx",je=".tbox-gen",Ue="@/platform/mount-page",ht=/^[a-z0-9][a-z0-9-]*$/;function Fe(e){let t=[],n=(s,c)=>{for(let a of gt(s,{withFileTypes:!0})){let f=c?`${c}/${a.name}`:a.name;a.isDirectory()?n(_.join(s,a.name),f):t.push(f)}};return n(e,""),t}function Be(e,t,n){let s=[],c=new Set(t.map(p=>B(`/${p}`)));t.includes("index.html")&&s.push("E11: public/index.html 会覆盖构建产物入口 HTML(copyDir 后置 clobber)");let a=new Map,f=(p,g)=>{let u=B(`/${p}`),o=a.get(u);o!==void 0?s.push(`E11: 文档输出 "${p}"(${g})与 "${o}" 归一化后冲突`):a.set(u,g),c.has(u)&&s.push(`E11: public 文件与生成文档同路径 "${p}"(${g})——构建后拷贝将覆盖产物`);let v=p.split("/");for(let m=1;m<v.length;m++){let i=v.slice(0,m).join("/");c.has(B(`/${i}`))&&s.push(`E11: public 文件 "${i}" 占据了 "${p}"(${g})所需的目录路径`)}};for(let p of e){let g=Q(p.path);g&&f(g,`路由 ${p.id}`)}for(let p of n)f(p.document,`平台文档 ${p.inputName}`);let h=new Set;for(let p of n)h.has(p.inputName)?s.push(`E11: 平台文档 inputName "${p.inputName}" 重复——.tbox-gen/ 生成文件互相覆写`):h.add(p.inputName);for(let p of e)h.has(p.id)&&s.push(`E11: 路由 id "${p.id}" 与平台文档 inputName 同名——共享 .tbox-gen/ 命名空间将静默覆写(改写 route id 或平台 inputName)`);return s}function pe(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function me(e,t,n){let s=t??e.page??`@/pages/${e.id}`;return`import { mountPage } from '${n}';
2
- mountPage(() => import('${s}'));
3
- `}function G(e,t,n){let s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`(<script\\b[^>]*\\bsrc=")${s}(")`,"g"),a=e.match(c);return!a||a.length===0?null:e.replace(c,`$1${n}$2`)}function ge(e,t){let n=G(e,t.clientEntrySrc,t.entrySrc);if(n===null)throw new Error(`[tbox-mpa] 根 index.html 中未找到 entry script(src="${t.clientEntrySrc}")——per-template 契约被破坏`);let s=n;if(t.title!==void 0){let c=pe(t.title);if(/<title>[^<]*<\/title>/i.test(s))s=s.replace(/<title>[^<]*<\/title>/i,`<title>${c}</title>`);else if(/<\/head>/i.test(s))s=s.replace(/<\/head>/i,`<title>${c}</title></head>`);else throw new Error("[tbox-mpa] 根 index.html 缺少 <title>/<head>——无法注入文档标题")}if(t.meta&&Object.keys(t.meta).length>0){if(!/<\/head>/i.test(s))throw new Error("[tbox-mpa] 根 index.html 缺少 </head>——无法注入 meta");let c=Object.entries(t.meta).map(([a,f])=>`<meta name="${pe(a)}" content="${pe(f)}">`).join("");s=s.replace(/<\/head>/i,`${c}</head>`)}return s}function he(e){let t=_.join(e.root,e.genDirName);ve(t,{recursive:!0,force:!0}),mt(t,{recursive:!0});let n={},s={},c=e.withHtml?Oe(_.join(e.root,"index.html"),"utf-8"):void 0;for(let a of e.entries){let f=Q(a.path);if(f&&(ee(_.join(t,`${a.id}.ts`),me(a,void 0,e.mountHelperId)),c!==void 0)){let h=ge(c,{clientEntrySrc:e.clientEntrySrc,entrySrc:`/${e.genDirName}/${a.id}.ts`,...a.title!==void 0?{title:a.title}:{},...a.meta?{meta:a.meta}:{}});ee(_.join(t,`${a.id}.html`),h),n[`tbox_${a.id}`]=_.join(t,`${a.id}.html`),s[`${e.genDirName}/${a.id}.html`]=f}}for(let a of e.extraDocuments){if(!ht.test(a.inputName))throw new Error(`[tbox-mpa] 平台文档 inputName "${a.inputName}" 不符合 ^[a-z0-9][a-z0-9-]*$`);if(ee(_.join(t,`${a.inputName}.ts`),me({id:a.inputName},a.entry,e.mountHelperId)),c!==void 0){let f=ge(c,{clientEntrySrc:e.clientEntrySrc,entrySrc:`/${e.genDirName}/${a.inputName}.ts`,...a.title!==void 0?{title:a.title}:{}});ee(_.join(t,`${a.inputName}.html`),f),n[`tbox_extra_${a.inputName}`]=_.join(t,`${a.inputName}.html`),s[`${e.genDirName}/${a.inputName}.html`]=a.document}}return{inputs:n,renames:s}}function Ve(e){return _.join(_.dirname(e),`.tbox-dist-staging-${Ae().slice(0,8)}`)}function ze(e,t){if(!te(_.join(e,"index.html")))throw new Error(`[tbox-mpa] staging 产物不完整(缺 index.html):${e}——拒绝发布`);let n=_.join(_.dirname(t),`.tbox-dist-backup-${Ae().slice(0,8)}`),s=te(t);s&&fe(t,n);try{fe(e,t)}catch(c){throw s&&fe(n,t),c}s&&ve(n,{recursive:!0,force:!0})}function Me(e,t,n,s){if(!te(e))return null;let c=W(Oe(e,"utf-8"));if(!c.ok)throw new Error(`[tbox-mpa] routes.json 校验失败(${_.relative(s,e)}):
4
- - ${c.errors.join(`
5
- - `)}`);let a=t!==!1&&te(t)?Fe(t):[],f=Be(c.entries,a,n);if(f.length>0)throw new Error(`[tbox-mpa] 路由 × public 冲突族校验失败:
1
+ var st="https://env-00jx4e7pq1un-static.normal.cloudstatic.cn/asset/codingbox/inspector.umd.js",Y="/__vs_inspector__.js",ue=`<script src="${Y}" defer></script>`,Z="",de=!1;async function at(e=3){for(let t=0;t<e;t++)try{let n=await fetch(st);if(!n.ok)throw new Error(`HTTP ${n.status}`);Z=await n.text(),de=!0,console.log(`[inspector] runtime loaded (${Z.length} bytes)`);return}catch(n){console.warn(`[inspector] fetch failed (attempt ${t+1}/${e}):`,n.message),t<e-1&&await new Promise(i=>setTimeout(i,1e3*(t+1)))}console.error("[inspector] runtime unavailable; inspector script will be skipped")}function ke(e){if(e.includes(Y))return e;let t=e.search(/<\/head\s*>/i);if(t!==-1)return e.slice(0,t)+ue+e.slice(t);let n=e.search(/<body[\s>]/i);return n!==-1?e.slice(0,n)+ue+e.slice(n):e}function ct(){return de}function lt(e){at(),e.get(Y,(t,n)=>{if(!Z){n.status(503).type("application/javascript").send("// inspector runtime not ready");return}n.type("application/javascript").set("Cache-Control","no-cache").send(Z)}),e.use((t,n,i)=>{if(!de)return i();let a=[],o=n.write.bind(n),f=n.end.bind(n),h=!1,g=()=>{let v=String(n.getHeader("content-type")||""),p=String(n.getHeader("content-encoding")||"");return v.includes("text/html")&&!p};n.write=((v,...p)=>(!h&&!a.length&&(h=g()),h&&v?(a.push(Buffer.isBuffer(v)?v:Buffer.from(v)),!0):o(v,...p))),n.end=((v,...p)=>{if(!h&&!a.length&&(h=g()),h){v&&a.push(Buffer.isBuffer(v)?v:Buffer.from(v));try{let l=Buffer.concat(a).toString("utf8"),y=ke(l);return n.setHeader("Content-Length",Buffer.byteLength(y)),f(y,...p)}catch(l){return console.warn("[inspector] inject failed, fallback to original:",l.message),f(Buffer.concat(a),...p)}}return f(v,...p)}),i()})}import{createHash as Ge,randomUUID as Et,timingSafeEqual as xt}from"crypto";import{existsSync as St,readFileSync as Rt,statSync as _t}from"fs";import{readFile as X}from"fs/promises";import Dt from"express";import C from"path";var He=["api","ws","assets"],ut=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu,dt=/^[a-z][a-z0-9-]*$/,ft=/^[a-z0-9][a-z0-9-]*$/,pt=/^[a-zA-Z][a-zA-Z0-9-]*$/;function B(e){if(!e.includes("%"))return e;try{return decodeURI(e)}catch{return null}}function z(e){return e.normalize("NFC").toLowerCase()}function Q(e){if(e==="/")return;let t=e.slice(1).split("/");if(!t.some(n=>n.length===0))return`${t.join("/")}/index.html`}function Ne(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ce(e,t={}){let n=[],i=[],a=new Set([...He,...t.reservedSegments??[]]),o=t.maxRoutes??100;if(!Array.isArray(e))return{ok:!1,errors:["E01: routes.json 顶层必须是数组"],warnings:i,entries:[]};e.length>o&&n.push(`E09: 路由总数 ${e.length} 超过上限 ${o}`);for(let[p,l]of e.entries())Ne(l)||n.push(`E01: 第 ${p} 项必须是对象`);if(n.length>0)return{ok:!1,errors:n,warnings:i,entries:[]};let f=[],h=new Set,g=new Map,v=0;for(let[p,l]of e.entries()){let y=`第 ${p} 项`,c=l.id;if(typeof c!="string"||c.length===0){n.push(`E02: ${y} 缺少 id`);continue}if(c.length>64||!dt.test(c)){n.push(`E03: ${y} id "${c}" 不符合 ^[a-z][a-z0-9-]*$(≤64 字符)`);continue}if(ut.test(c)){n.push(`E03: ${y} id "${c}" 是 Windows 保留名`);continue}if(h.has(c)){n.push(`E02: id "${c}" 重复`);continue}h.add(c);let m=l.path;if(typeof m!="string"||m.length===0||m[0]!=="/"){n.push(`E04: ${y}(id=${c})path 必须以 / 开头的字符串`);continue}let R=B(m);if(R===null){n.push(`E12: ${y}(id=${c})path 含非法百分号编码`);continue}if(R!=="/"){let M=R.slice(1).split("/").find(k=>!ft.test(k));if(M!==void 0){n.push(`E04: ${y}(id=${c})path 段 "${M}" 不合法——每段必须匹配 ^[a-z0-9][a-z0-9-]*$(禁点号/冒号/通配/下划线;动态路由已按方案裁决放弃)`);continue}}let d=z(R),b=g.get(d);if(b!==void 0){n.push(`E12: path "${m}"(id=${c})与 "${b}" 解码归一后冲突`);continue}if(g.set(d,m),R!=="/"){let D=R.slice(1).split("/")[0];if(a.has(z(`/${D}`).slice(1))){n.push(`E08: ${y}(id=${c})首段 "${D}" 落在保留命名空间(${[...a].join("/")})`);continue}}R==="/"&&(v+=1,l.page!==void 0&&n.push(`E05: 根路由(id=${c})禁用 page 字段——根入口恒为应用根 main 链`),(l.title!==void 0||l.meta!==void 0)&&i.push(`根路由(id=${c})的 title/meta 不生效——根文档标题维持应用 index.html 静态值(租户主题运行时覆写)`));let s;if(l.title!==void 0){if(typeof l.title!="string"||l.title.length===0){n.push(`E04: ${y}(id=${c})title 必须是非空字符串`);continue}if(l.title.length>200){n.push(`E04: ${y}(id=${c})title 超过 200 字符`);continue}s=l.title}let x;if(l.meta!==void 0){if(!Ne(l.meta)){n.push(`E04: ${y}(id=${c})meta 必须是 Record<string, string>`);continue}let D=Object.keys(l.meta);if(D.length>20){n.push(`E04: ${y}(id=${c})meta 条目超过 20`);continue}let M=D.find(j=>!pt.test(j));if(M!==void 0){n.push(`E04: ${y}(id=${c})meta 键 "${M}" 不符合 ^[a-zA-Z][a-zA-Z0-9-]*$`);continue}let k=D.find(j=>typeof l.meta[j]!="string");if(k!==void 0){n.push(`E04: ${y}(id=${c})meta["${k}"] 必须是字符串`);continue}let q=D.find(j=>l.meta[j].length>500);if(q!==void 0){n.push(`E04: ${y}(id=${c})meta["${q}"] 超过 500 字符`);continue}x=l.meta}let P;if(l.page!==void 0){if(typeof l.page!="string"||!l.page.startsWith("@/")){n.push(`E04: ${y}(id=${c})page 必须以 @/ 开头的模块路径`);continue}P=l.page}f.push({id:c,path:R,...s!==void 0?{title:s}:{},...x?{meta:x}:{},...P?{page:P}:{}})}return v===0?n.push('E05: 必须恰有一个 path 为 "/" 的根路由'):v>1&&n.push(`E05: 根路由数量 ${v} > 1`),{ok:n.length===0,errors:n,warnings:i,entries:f}}function V(e){let t;try{t=JSON.parse(e)}catch(n){return{ok:!1,errors:[`E01: routes.json JSON 解析失败:${n.message}`],warnings:[],entries:[]}}return Ce(t)}import{randomUUID as Ae}from"crypto";import{existsSync as te,mkdirSync as mt,readFileSync as Oe,readdirSync as gt,renameSync as fe,rmSync as ve,writeFileSync as ee}from"fs";import _ from"path";var Le="/src/main.tsx",Ue=".tbox-gen",je="@/platform/mount-page",ht=/^[a-z0-9][a-z0-9-]*$/;function Fe(e){let t=[],n=(i,a)=>{for(let o of gt(i,{withFileTypes:!0})){let f=a?`${a}/${o.name}`:o.name;o.isDirectory()?n(_.join(i,o.name),f):t.push(f)}};return n(e,""),t}function ze(e,t,n){let i=[],a=new Set(t.map(g=>z(`/${g}`)));t.includes("index.html")&&i.push("E11: public/index.html 会覆盖构建产物入口 HTML(copyDir 后置 clobber)");let o=new Map,f=(g,v)=>{let p=z(`/${g}`),l=o.get(p);l!==void 0?i.push(`E11: 文档输出 "${g}"(${v})与 "${l}" 归一化后冲突`):o.set(p,v),a.has(p)&&i.push(`E11: public 文件与生成文档同路径 "${g}"(${v})——构建后拷贝将覆盖产物`);let y=g.split("/");for(let c=1;c<y.length;c++){let m=y.slice(0,c).join("/");a.has(z(`/${m}`))&&i.push(`E11: public 文件 "${m}" 占据了 "${g}"(${v})所需的目录路径`)}};for(let g of e){let v=Q(g.path);v&&f(v,`路由 ${g.id}`)}for(let g of n)f(g.document,`平台文档 ${g.inputName}`);let h=new Set;for(let g of n)h.has(g.inputName)?i.push(`E11: 平台文档 inputName "${g.inputName}" 重复——.tbox-gen/ 生成文件互相覆写`):h.add(g.inputName);for(let g of e)h.has(g.id)&&i.push(`E11: 路由 id "${g.id}" 与平台文档 inputName 同名——共享 .tbox-gen/ 命名空间将静默覆写(改写 route id 或平台 inputName)`);return i}function pe(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function me(e,t,n){let i=t??e.page??`@/pages/${e.id}`;return`import { mountPage } from '${n}';
2
+ mountPage(() => import('${i}'));
3
+ `}function G(e,t,n){let i=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`(<script\\b[^>]*\\bsrc=")${i}(")`,"g"),o=e.match(a);return!o||o.length===0?null:e.replace(a,`$1${n}$2`)}function ge(e,t){let n=G(e,t.clientEntrySrc,t.entrySrc);if(n===null)throw new Error(`[tbox-mpa] 根 index.html 中未找到 entry script(src="${t.clientEntrySrc}")——per-template 契约被破坏`);let i=n;if(t.title!==void 0){let a=pe(t.title);if(/<title>[^<]*<\/title>/i.test(i))i=i.replace(/<title>[^<]*<\/title>/i,`<title>${a}</title>`);else if(/<\/head>/i.test(i))i=i.replace(/<\/head>/i,`<title>${a}</title></head>`);else throw new Error("[tbox-mpa] 根 index.html 缺少 <title>/<head>——无法注入文档标题")}if(t.meta&&Object.keys(t.meta).length>0){if(!/<\/head>/i.test(i))throw new Error("[tbox-mpa] 根 index.html 缺少 </head>——无法注入 meta");let a=Object.entries(t.meta).map(([o,f])=>`<meta name="${pe(o)}" content="${pe(f)}">`).join("");i=i.replace(/<\/head>/i,`${a}</head>`)}return i}function he(e){let t=_.join(e.root,e.genDirName);ve(t,{recursive:!0,force:!0}),mt(t,{recursive:!0});let n={},i={},a=e.withHtml?Oe(_.join(e.root,"index.html"),"utf-8"):void 0;for(let o of e.entries){let f=Q(o.path);if(f&&(ee(_.join(t,`${o.id}.ts`),me(o,void 0,e.mountHelperId)),a!==void 0)){let h=ge(a,{clientEntrySrc:e.clientEntrySrc,entrySrc:`/${e.genDirName}/${o.id}.ts`,...o.title!==void 0?{title:o.title}:{},...o.meta?{meta:o.meta}:{}});ee(_.join(t,`${o.id}.html`),h),n[`tbox_${o.id}`]=_.join(t,`${o.id}.html`),i[`${e.genDirName}/${o.id}.html`]=f}}for(let o of e.extraDocuments){if(!ht.test(o.inputName))throw new Error(`[tbox-mpa] 平台文档 inputName "${o.inputName}" 不符合 ^[a-z0-9][a-z0-9-]*$`);if(ee(_.join(t,`${o.inputName}.ts`),me({id:o.inputName},o.entry,e.mountHelperId)),a!==void 0){let f=ge(a,{clientEntrySrc:e.clientEntrySrc,entrySrc:`/${e.genDirName}/${o.inputName}.ts`,...o.title!==void 0?{title:o.title}:{}});ee(_.join(t,`${o.inputName}.html`),f),n[`tbox_extra_${o.inputName}`]=_.join(t,`${o.inputName}.html`),i[`${e.genDirName}/${o.inputName}.html`]=o.document}}return{inputs:n,renames:i}}function Be(e){return _.join(_.dirname(e),`.tbox-dist-staging-${Ae().slice(0,8)}`)}function We(e,t){if(!te(_.join(e,"index.html")))throw new Error(`[tbox-mpa] staging 产物不完整(缺 index.html):${e}——拒绝发布`);let n=_.join(_.dirname(t),`.tbox-dist-backup-${Ae().slice(0,8)}`),i=te(t);i&&fe(t,n);try{fe(e,t)}catch(a){throw i&&fe(n,t),a}i&&ve(n,{recursive:!0,force:!0})}function Me(e,t,n,i){if(!te(e))return null;let a=V(Oe(e,"utf-8"));if(!a.ok)throw new Error(`[tbox-mpa] routes.json 校验失败(${_.relative(i,e)}):
4
+ - ${a.errors.join(`
5
+ - `)}`);let o=t!==!1&&te(t)?Fe(t):[],f=ze(a.entries,o,n);if(f.length>0)throw new Error(`[tbox-mpa] 路由 × public 冲突族校验失败:
6
6
  - ${f.join(`
7
- - `)}`);return{entries:c.entries,warnings:c.warnings}}function vt(e={}){let t=e.genDirName??je,n=e.clientEntrySrc??Le,s=e.mountHelperId??Ue,c=e.extraDocuments??[],a={root:"",renames:{},inputPaths:[],transaction:!1,wrote:!1};return{name:"tbox-mpa-pages",config(f,h){if(h.command!=="build"||process.env.VITEST)return;let p=_.resolve(f.root??process.cwd());a.root=p;let g=e.routesModule??_.join(p,"src/business/routes.json"),u=e.publicDir===!1?!1:e.publicDir??_.join(p,"public"),o=Me(g,u,c,p);if(!o)return;for(let b of o.warnings)console.warn(`[tbox-mpa] ${b}`);let v=he({root:p,entries:o.entries,extraDocuments:c,genDirName:t,mountHelperId:s,clientEntrySrc:n,withHtml:!0});a.renames=v.renames,a.inputPaths=Object.values(v.inputs);let m=f.build?.watch,i=typeof m=="object"&&m!==null,y=f.build?.outDir??"dist",d=_.resolve(p,y),R={build:{rollupOptions:{input:v.inputs}}};if(!i&&Object.keys(v.inputs).length+1>1){let b=Ve(d),S=_.relative(p,b);S.startsWith("..")||_.isAbsolute(S)?console.warn(`[tbox-mpa] outDir ${y} 位于 root 外——跳过输出事务(直写 dist)`):(a.stagingDir=b,a.distDir=d,a.transaction=!0,R.build.outDir=S)}return R},configResolved(f){if(f.command!=="build"||process.env.VITEST||a.inputPaths.length===0)return;if(f.base!=="/")throw new Error(`[tbox-mpa] MPA 文档模式要求 vite base === '/'(当前 "${f.base}")——生成文档的资产引用会随路径深度断链`);let h=f.build.rollupOptions.input,p=h===void 0?[]:typeof h=="string"||Array.isArray(h)?Array.isArray(h)?h:[h]:Object.values(h),g=new Set(p.map(u=>_.resolve(f.root,u)));for(let u of a.inputPaths)if(!g.has(u))throw new Error(`[tbox-mpa] 生成输入 ${u} 未出现在最终 rollupOptions.input——被其他配置移除(框架产物不可覆盖)`)},configureServer(f){if(process.env.VITEST)return;let h=f.config.root,p=e.routesModule??_.join(h,"src/business/routes.json"),g=e.publicDir===!1?!1:e.publicDir??_.join(h,"public"),u=Me(p,g,c,h);if(u){for(let o of u.warnings)console.warn(`[tbox-mpa] ${o}`);he({root:h,entries:u.entries,extraDocuments:c,genDirName:t,mountHelperId:s,clientEntrySrc:n,withHtml:!1})}},generateBundle:{order:"post",handler(f,h){for(let[p,g]of Object.entries(h)){if(g.type!=="asset")continue;let u=a.renames[p];u!==void 0&&(g.fileName=u)}}},writeBundle(){a.wrote=!0},closeBundle(){a.transaction&&(a.transaction=!1,a.stagingDir&&a.distDir&&(a.wrote?ze(a.stagingDir,a.distDir):ve(a.stagingDir,{recursive:!0,force:!0})))}}}import{statSync as We}from"fs";import{readFile as yt}from"fs/promises";import J from"path";import bt from"express";function ye(e){let t=new Map;for(let n of e){let s=V(n.path);s&&t.set(s,n)}return t}var C='<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>404</title></head><body style="font-family:system-ui;padding:40px;color:#333"><h1>404</h1><p>页面不存在</p></body></html>',be='<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>503</title><meta http-equiv="refresh" content="3">',L=`${be}</head><body style="font-family:system-ui;padding:40px;color:#333"><h1>503</h1><p>构建进行中,请稍后刷新</p></body></html>`;function T(e,t,n,s,c){if(t.statusCode=n,t.setHeader("Content-Type","text/html; charset=utf-8"),t.setHeader("Cache-Control","no-store"),t.setHeader("Content-Length",Buffer.byteLength(s)),c)for(let[a,f]of Object.entries(c))t.setHeader(a,f);e.method!=="HEAD"&&t.write(s),t.end()}function wt(e){let t;try{t=new URL(e,"http://tbox.local")}catch{return null}let n=V(t.pathname);return n===null?null:{decoded:n,rawPathname:t.pathname,search:t.search}}function ne(e){let t=e.split("/"),n=t[t.length-1]??"";return n.length>0&&n.includes(".")}function O(e,t){let n=J.resolve(e,`.${t}`);return n!==e&&!n.startsWith(e+J.sep)?null:n}function N(e){try{return We(e).isFile()}catch{return!1}}function re(e){try{return We(e).isDirectory()}catch{return!1}}function we(e){let{distDir:t,decorateHtml:n,logger:s}=e,c=e.html503??L,a=e.platformPages??[],f=e.isBuildActive??(()=>!1),h=bt.static(t,{index:!1,redirect:!1,fallthrough:!0}),p=ye(a);async function g(u,o,v){let m;try{m=await yt(v,"utf-8")}catch{T(u,o,f()?503:404,f()?c:C);return}let i=n?await n(m):m;o.statusCode=200,o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.setHeader("Content-Length",Buffer.byteLength(i)),u.method!=="HEAD"&&o.write(i),o.end()}return(u,o,v)=>{(async()=>{if(u.method!=="GET"&&u.method!=="HEAD"){o.statusCode=404,o.setHeader("Cache-Control","no-store"),o.setHeader("Content-Type","text/plain; charset=utf-8"),o.end("Not Found");return}if(!N(J.join(t,"index.html"))){s?.debug("strict_static_unready",{pathname:u.path}),T(u,o,503,c);return}let m=wt(u.url??"/");if(!m){T(u,o,404,C);return}let{decoded:i,search:y}=m,d=p.get(i);if(d){let b=O(t,`/${d.document}`);b&&N(b)?await g(u,o,b):(s?.debug("strict_static_platform_off",{pathname:i}),T(u,o,404,C));return}if(i.endsWith(".html")||i.endsWith(".htm")){let b=O(t,i);if(b&&N(b)){await g(u,o,b);return}T(u,o,f()?503:404,f()?c:C);return}if(await new Promise(b=>{h(u,o,()=>b())}),o.writableEnded)return;if(i.endsWith("/")){let b=O(t,i),S=b===null?null:J.join(b,"index.html");if(S&&N(S)){await g(u,o,S);return}}else{let b=O(t,i);if(b&&re(b)&&N(J.join(b,"index.html"))){let S=`${m.rawPathname}/${y}`,P=S.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),I=`<!doctype html><html><head><title>301</title></head><body>Redirecting to <a href="${P}">${P}</a></body></html>`;T(u,o,301,I,{Location:S});return}}let R=f()?503:404;if(ne(i)){s?.debug("strict_static_miss_asset",{pathname:i,buildActive:f()}),o.statusCode=R,o.setHeader("Content-Type","text/plain; charset=utf-8"),o.setHeader("Cache-Control","no-store"),u.method!=="HEAD"&&o.write(f()?"Service Unavailable":"Not Found"),o.end();return}s?.debug("strict_static_miss",{pathname:i,buildActive:f()}),T(u,o,R,f()?c:C)})().catch(v)}}var Ke="TBOX_DEV_TOKEN",K="tbox_dev_token",oe="/__tbox_dev_hot_reload",Ee=/^[A-Za-z0-9_-]{20,128}$/,qe="tbox_hmr_protocol",$t={debug(){},info(){},warn(){}};function It(e){let t=e[Ke];return t===void 0||t===""?{mode:"classic"}:Ee.test(t)?{mode:"protected",token:t}:{mode:"protected",token:void 0}}function xe(e,t){if(!e||!t||!Ee.test(e)||!Ee.test(t))return!1;let n=Ge("sha256").update(e).digest(),s=Ge("sha256").update(t).digest();return xt(n,s)}function Ze(e){try{return new URL(e,"http://tbox.local").searchParams.get(K)??void 0}catch{return}}function Tt(e){if(e)for(let t of e.split(";")){let n=t.trim();if(n.startsWith(`${K}=`))return n.slice(K.length+1)}}function kt(e,t){if(t===void 0)return{face:"static",credSource:"none",reason:"no-cred"};let n=Ze(e.url??"/"),s=Tt(e.headers.cookie),c="none";if(n!==void 0&&xe(n,t)?c="query":s!==void 0&&xe(s,t)?c="cookie":(n!==void 0||s!==void 0)&&(c="invalid"),c!=="query"&&c!=="cookie")return{face:"static",credSource:c,reason:"no-cred"};let a=e.headers["sec-fetch-site"],f=e.headers["sec-fetch-mode"];return f==="navigate"?{face:"dev",credSource:c,reason:"navigate"}:a==="same-origin"||a==="none"?{face:"dev",credSource:c,reason:"same-origin"}:a===void 0&&f===void 0?{face:"dev",credSource:c,reason:"no-sec-fetch-header"}:{face:"static",credSource:c,reason:"cross-site-subresource"}}function z(e,t){let n=/<head[^>]*>/i.exec(e);if(!n)return e;let s=n.index+n[0].length;return e.slice(0,s)+t+e.slice(s)}function Pt(e,t){return t.some(n=>e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))}function Je(e,t,n){return`<script>window.__TBOX_DEV_TOKEN__='${e}';(function(){var OW=window.WebSocket;function PW(url,protocols){if((typeof url==='string'||url instanceof URL)&&new URL(url,'http://tbox.local').pathname===${JSON.stringify(t)}){var u=new URL(url,window.location?.href||'http://tbox.local');u.searchParams.set('${K}',window.__TBOX_DEV_TOKEN__);`+(n?`var p=Array.isArray(protocols)&&protocols.length===1?protocols[0]:protocols;if(p==='vite-hmr'||p==='vite-ping'){u.searchParams.set('${qe}',p);protocols=undefined;}`:"")+"url=u.href;}return protocols===undefined?new OW(url):new OW(url,protocols);}PW.prototype=OW.prototype;Object.setPrototypeOf(PW,OW);window.WebSocket=PW;})();</script>"}var Ye="__tbox_build__",Xe=`<script>(function(){var es=new EventSource('${oe}');var last=null;var meta=null;try{var m=document.getElementById('${Ye}');if(m){meta=JSON.parse(m.textContent);}}catch(e){}var G='__tbox_sse_reload__';function gr(){try{var t=Number(sessionStorage.getItem(G)||0);if(t&&Date.now()-t<10000){return;}sessionStorage.setItem(G,String(Date.now()));}catch(e){}location.reload();}es.onmessage=function(e){try{var d=JSON.parse(e.data);if(last===null){last=d;if(meta){if(d.serverSessionId&&meta.serverSessionId&&d.serverSessionId!==meta.serverSessionId){gr();return;}if(typeof d.buildId==='number'&&typeof meta.buildId==='number'&&d.buildId>meta.buildId){gr();return;}}try{sessionStorage.removeItem(G);sessionStorage.removeItem('__tbox_wait_count__');}catch(e2){}return;}if(d.buildId!==last.buildId){location.reload();}last=d;}catch(err){}};})();</script>`;function Nt(){return`<script>(function(){var es=new EventSource('${oe}');var last=null;es.onmessage=function(e){try{var d=JSON.parse(e.data).buildId;if(last===null){last=d;return;}if(d!==last){location.reload();}last=d;}catch(err){}};var C='__tbox_wait_count__';try{var n=Number(sessionStorage.getItem(C)||0)+1;if(n>20){var m=document.querySelector('meta[http-equiv=refresh]');if(m){m.remove();}var b=document.querySelector('body');if(b){b.innerHTML='<h1>503</h1><p>构建时间较长,请稍后手动刷新页面。</p>';}return;}sessionStorage.setItem(C,String(n));}catch(e){}})();</script>`}function Ht(e){let t=e.logger??$t,n=Symbol("tboxDevFace"),s=e.tokenState.mode==="classic",c=e.tokenState.mode==="protected"?e.tokenState.token:void 0,a=!s&&c!==void 0&&e.vite.ws!==void 0,f=new WeakSet;e.vite.ws?.on("headers",(r,l)=>{if(f.has(l))for(let E=r.length-1;E>=0;E--)/^sec-websocket-protocol\s*:/i.test(r[E])&&r.splice(E,1)});let h=0,p=!1,g=Et(),u=new Set,o=e.sseKeepaliveMs??15e3,v=Dt.static(e.clientDist,{index:!1,fallthrough:!0}),m=new Set,i=e.pagePolicy,y=i!==void 0&&St(i.routesModule),d=i?.clientEntrySrc??"/src/main.tsx",R=i?.genDirName??".tbox-gen",b=i?.publicDir??H.join(e.clientRoot,"public"),S=ye(i?.platformPages??[]),P=(()=>{if(!y)return null;let r=null;return{load:()=>{try{let E=Rt(i.routesModule);if(r&&r.mtimeMs===E.mtimeMs)return r.byPath;let x=W(_t(i.routesModule,"utf-8"));if(!x.ok)return t.warn("strict_routes_invalid",{errors:x.errors.slice(0,3)}),null;let w=new Map;for(let D of x.entries)w.set(D.path,D.id);return r={mtimeMs:E.mtimeMs,byPath:w},w}catch{return null}}}})(),I=y?we({distDir:e.clientDist,...i?.platformPages?{platformPages:i.platformPages}:{},decorateHtml:r=>z(z(r,Xe),j()),isBuildActive:()=>p,html503:`${be}${Nt()}</head><body style="font-family:system-ui;padding:40px;color:#333"><h1>503</h1><p>构建进行中,页面将在就绪后自动刷新</p></body></html>`,logger:t}):null;if(y){let r=P?.load()??null;t.info("dev_guard_mode",{strictPages:!0,routesCount:r?r.size:0})}t.info("dev_guard_mode",{hmrNoSubprotocol:a,mode:e.tokenState.mode,tokenShapeOk:e.tokenState.mode==="protected"&&c!==void 0,fsAllowNarrowed:e.fsAllowNarrowed===!0});function M(){return JSON.stringify({buildId:h,serverSessionId:g})}function j(){return`<script type="application/json" id="${Ye}">${JSON.stringify({serverSessionId:g,buildId:h})}</script>`}function q(r){r.setHeader("Content-Type","text/event-stream; charset=utf-8"),r.setHeader("Cache-Control","no-store"),r.setHeader("X-Accel-Buffering","no"),r.flushHeaders(),r.write(`data: ${M()}
7
+ - `)}`);return{entries:a.entries,warnings:a.warnings}}function vt(e={}){let t=e.genDirName??Ue,n=e.clientEntrySrc??Le,i=e.mountHelperId??je,a=e.extraDocuments??[],o={root:"",renames:{},inputPaths:[],transaction:!1,wrote:!1};return{name:"tbox-mpa-pages",config(f,h){if(h.command!=="build"||process.env.VITEST)return;let g=_.resolve(f.root??process.cwd());o.root=g;let v=e.routesModule??_.join(g,"src/business/routes.json"),p=e.publicDir===!1?!1:e.publicDir??_.join(g,"public"),l=Me(v,p,a,g);if(!l)return;for(let s of l.warnings)console.warn(`[tbox-mpa] ${s}`);let y=he({root:g,entries:l.entries,extraDocuments:a,genDirName:t,mountHelperId:i,clientEntrySrc:n,withHtml:!0});o.renames=y.renames,o.inputPaths=Object.values(y.inputs);let c=f.build?.watch,m=typeof c=="object"&&c!==null,R=f.build?.outDir??"dist",d=_.resolve(g,R),b={build:{rollupOptions:{input:y.inputs}}};if(!m&&Object.keys(y.inputs).length+1>1){let s=Be(d),x=_.relative(g,s);x.startsWith("..")||_.isAbsolute(x)?console.warn(`[tbox-mpa] outDir ${R} 位于 root 外——跳过输出事务(直写 dist)`):(o.stagingDir=s,o.distDir=d,o.transaction=!0,b.build.outDir=x)}return b},configResolved(f){if(f.command!=="build"||process.env.VITEST||o.inputPaths.length===0)return;if(f.base!=="/")throw new Error(`[tbox-mpa] MPA 文档模式要求 vite base === '/'(当前 "${f.base}")——生成文档的资产引用会随路径深度断链`);let h=f.build.rollupOptions.input,g=h===void 0?[]:typeof h=="string"||Array.isArray(h)?Array.isArray(h)?h:[h]:Object.values(h),v=new Set(g.map(p=>_.resolve(f.root,p)));for(let p of o.inputPaths)if(!v.has(p))throw new Error(`[tbox-mpa] 生成输入 ${p} 未出现在最终 rollupOptions.input——被其他配置移除(框架产物不可覆盖)`)},configureServer(f){if(process.env.VITEST)return;let h=f.config.root,g=e.routesModule??_.join(h,"src/business/routes.json"),v=e.publicDir===!1?!1:e.publicDir??_.join(h,"public"),p=Me(g,v,a,h);if(p){for(let l of p.warnings)console.warn(`[tbox-mpa] ${l}`);he({root:h,entries:p.entries,extraDocuments:a,genDirName:t,mountHelperId:i,clientEntrySrc:n,withHtml:!1})}},generateBundle:{order:"post",handler(f,h){for(let[g,v]of Object.entries(h)){if(v.type!=="asset")continue;let p=o.renames[g];p!==void 0&&(v.fileName=p)}}},writeBundle(){o.wrote=!0},closeBundle(){o.transaction&&(o.transaction=!1,o.stagingDir&&o.distDir&&(o.wrote?We(o.stagingDir,o.distDir):ve(o.stagingDir,{recursive:!0,force:!0})))}}}import{statSync as Ve}from"fs";import{readFile as yt}from"fs/promises";import J from"path";import bt from"express";function ye(e){let t=new Map;for(let n of e){let i=B(n.path);i&&t.set(i,n)}return t}var A='<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>404</title></head><body style="font-family:system-ui;padding:40px;color:#333"><h1>404</h1><p>页面不存在</p></body></html>',be='<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>503</title><meta http-equiv="refresh" content="3">',U=`${be}</head><body style="font-family:system-ui;padding:40px;color:#333"><h1>503</h1><p>构建进行中,请稍后刷新</p></body></html>`;function T(e,t,n,i,a){if(t.statusCode=n,t.setHeader("Content-Type","text/html; charset=utf-8"),t.setHeader("Cache-Control","no-store"),t.setHeader("Content-Length",Buffer.byteLength(i)),a)for(let[o,f]of Object.entries(a))t.setHeader(o,f);e.method!=="HEAD"&&t.write(i),t.end()}function wt(e){let t;try{t=new URL(e,"http://tbox.local")}catch{return null}let n=B(t.pathname);return n===null?null:{decoded:n,rawPathname:t.pathname,search:t.search}}function ne(e){let t=e.split("/"),n=t[t.length-1]??"";return n.length>0&&n.includes(".")}function L(e,t){let n=J.resolve(e,`.${t}`);return n!==e&&!n.startsWith(e+J.sep)?null:n}function H(e){try{return Ve(e).isFile()}catch{return!1}}function re(e){try{return Ve(e).isDirectory()}catch{return!1}}function we(e){let{distDir:t,decorateHtml:n,logger:i}=e,a=e.html503??U,o=e.platformPages??[],f=e.isBuildActive??(()=>!1),h=bt.static(t,{index:!1,redirect:!1,fallthrough:!0}),g=ye(o);async function v(p,l,y){let c;try{c=await yt(y,"utf-8")}catch{T(p,l,f()?503:404,f()?a:A);return}let m=n?await n(c):c;l.statusCode=200,l.setHeader("Content-Type","text/html; charset=utf-8"),l.setHeader("Cache-Control","no-store"),l.setHeader("Content-Length",Buffer.byteLength(m)),p.method!=="HEAD"&&l.write(m),l.end()}return(p,l,y)=>{(async()=>{if(p.method!=="GET"&&p.method!=="HEAD"){l.statusCode=404,l.setHeader("Cache-Control","no-store"),l.setHeader("Content-Type","text/plain; charset=utf-8"),l.end("Not Found");return}if(!H(J.join(t,"index.html"))){i?.debug("strict_static_unready",{pathname:p.path}),T(p,l,503,a);return}let c=wt(p.url??"/");if(!c){T(p,l,404,A);return}let{decoded:m,search:R}=c,d=g.get(m);if(d){let s=L(t,`/${d.document}`);s&&H(s)?await v(p,l,s):(i?.debug("strict_static_platform_off",{pathname:m}),T(p,l,404,A));return}if(m.endsWith(".html")||m.endsWith(".htm")){let s=L(t,m);if(s&&H(s)){await v(p,l,s);return}T(p,l,f()?503:404,f()?a:A);return}if(await new Promise(s=>{h(p,l,()=>s())}),l.writableEnded)return;if(m.endsWith("/")){let s=L(t,m),x=s===null?null:J.join(s,"index.html");if(x&&H(x)){await v(p,l,x);return}}else{let s=L(t,m);if(s&&re(s)&&H(J.join(s,"index.html"))){let x=`${c.rawPathname}/${R}`,P=x.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),D=`<!doctype html><html><head><title>301</title></head><body>Redirecting to <a href="${P}">${P}</a></body></html>`;T(p,l,301,D,{Location:x});return}}let b=f()?503:404;if(ne(m)){i?.debug("strict_static_miss_asset",{pathname:m,buildActive:f()}),l.statusCode=b,l.setHeader("Content-Type","text/plain; charset=utf-8"),l.setHeader("Cache-Control","no-store"),p.method!=="HEAD"&&l.write(f()?"Service Unavailable":"Not Found"),l.end();return}i?.debug("strict_static_miss",{pathname:m,buildActive:f()}),T(p,l,b,f()?a:A)})().catch(y)}}var Ke="TBOX_DEV_TOKEN",K="tbox_dev_token",oe="/__tbox_dev_hot_reload",Ee=/^[A-Za-z0-9_-]{20,128}$/,qe="tbox_hmr_protocol",$t={debug(){},info(){},warn(){}};function It(e){let t=e[Ke];return t===void 0||t===""?{mode:"classic"}:Ee.test(t)?{mode:"protected",token:t}:{mode:"protected",token:void 0}}function xe(e,t){if(!e||!t||!Ee.test(e)||!Ee.test(t))return!1;let n=Ge("sha256").update(e).digest(),i=Ge("sha256").update(t).digest();return xt(n,i)}function Ze(e){try{return new URL(e,"http://tbox.local").searchParams.get(K)??void 0}catch{return}}function Tt(e){if(e)for(let t of e.split(";")){let n=t.trim();if(n.startsWith(`${K}=`))return n.slice(K.length+1)}}function Pt(e,t){if(t===void 0)return{face:"static",credSource:"none",reason:"no-cred"};let n=Ze(e.url??"/"),i=Tt(e.headers.cookie),a="none";if(n!==void 0&&xe(n,t)?a="query":i!==void 0&&xe(i,t)?a="cookie":(n!==void 0||i!==void 0)&&(a="invalid"),a!=="query"&&a!=="cookie")return{face:"static",credSource:a,reason:"no-cred"};let o=e.headers["sec-fetch-site"],f=e.headers["sec-fetch-mode"];return f==="navigate"?{face:"dev",credSource:a,reason:"navigate"}:o==="same-origin"||o==="none"?{face:"dev",credSource:a,reason:"same-origin"}:o===void 0&&f===void 0?{face:"dev",credSource:a,reason:"no-sec-fetch-header"}:{face:"static",credSource:a,reason:"cross-site-subresource"}}function W(e,t){let n=/<head[^>]*>/i.exec(e);if(!n)return e;let i=n.index+n[0].length;return e.slice(0,i)+t+e.slice(i)}function kt(e,t){return t.some(n=>e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))}function Je(e,t,n){return`<script>window.__TBOX_DEV_TOKEN__='${e}';(function(){var OW=window.WebSocket;function PW(url,protocols){if((typeof url==='string'||url instanceof URL)&&new URL(url,'http://tbox.local').pathname===${JSON.stringify(t)}){var u=new URL(url,window.location?.href||'http://tbox.local');u.searchParams.set('${K}',window.__TBOX_DEV_TOKEN__);`+(n?`var p=Array.isArray(protocols)&&protocols.length===1?protocols[0]:protocols;if(p==='vite-hmr'||p==='vite-ping'){u.searchParams.set('${qe}',p);protocols=undefined;}`:"")+"url=u.href;}return protocols===undefined?new OW(url):new OW(url,protocols);}PW.prototype=OW.prototype;Object.setPrototypeOf(PW,OW);window.WebSocket=PW;})();</script>"}var Ye="__tbox_build__",Xe=`<script>(function(){var es=new EventSource('${oe}');var last=null;var meta=null;try{var m=document.getElementById('${Ye}');if(m){meta=JSON.parse(m.textContent);}}catch(e){}var G='__tbox_sse_reload__';function gr(){try{var t=Number(sessionStorage.getItem(G)||0);if(t&&Date.now()-t<10000){return;}sessionStorage.setItem(G,String(Date.now()));}catch(e){}location.reload();}es.onmessage=function(e){try{var d=JSON.parse(e.data);if(last===null){last=d;if(meta){if(d.serverSessionId&&meta.serverSessionId&&d.serverSessionId!==meta.serverSessionId){gr();return;}if(typeof d.buildId==='number'&&typeof meta.buildId==='number'&&d.buildId>meta.buildId){gr();return;}}try{sessionStorage.removeItem(G);sessionStorage.removeItem('__tbox_wait_count__');}catch(e2){}return;}if(d.buildId!==last.buildId){location.reload();}last=d;}catch(err){}};})();</script>`;function Nt(){return`<script>(function(){var es=new EventSource('${oe}');var last=null;es.onmessage=function(e){try{var d=JSON.parse(e.data).buildId;if(last===null){last=d;return;}if(d!==last){location.reload();}last=d;}catch(err){}};var C='__tbox_wait_count__';try{var n=Number(sessionStorage.getItem(C)||0)+1;if(n>20){var m=document.querySelector('meta[http-equiv=refresh]');if(m){m.remove();}var b=document.querySelector('body');if(b){b.innerHTML='<h1>503</h1><p>构建时间较长,请稍后手动刷新页面。</p>';}return;}sessionStorage.setItem(C,String(n));}catch(e){}})();</script>`}function Ht(e){let t=e.logger??$t,n=Symbol("tboxDevFace"),i=e.tokenState.mode==="classic",a=e.tokenState.mode==="protected"?e.tokenState.token:void 0,o=!i&&a!==void 0&&e.vite.ws!==void 0,f=new WeakSet;e.vite.ws?.on("headers",(r,u)=>{if(f.has(u))for(let E=r.length-1;E>=0;E--)/^sec-websocket-protocol\s*:/i.test(r[E])&&r.splice(E,1)});let h=0,g=!1,v=Et(),p=new Set,l=e.sseKeepaliveMs??15e3,y=Dt.static(e.clientDist,{index:!1,fallthrough:!0}),c=new Set,m=e.pagePolicy,R=m!==void 0&&St(m.routesModule),d=m?.clientEntrySrc??"/src/main.tsx",b=m?.genDirName??".tbox-gen",s=m?.publicDir??C.join(e.clientRoot,"public"),x=ye(m?.platformPages??[]),P=(()=>{if(!R)return null;let r=null;return{load:()=>{try{let E=_t(m.routesModule);if(r&&r.mtimeMs===E.mtimeMs)return r.byPath;let S=V(Rt(m.routesModule,"utf-8"));if(!S.ok)return t.warn("strict_routes_invalid",{errors:S.errors.slice(0,3)}),null;let w=new Map;for(let $ of S.entries)w.set($.path,$.id);return r={mtimeMs:E.mtimeMs,byPath:w},w}catch{return null}}}})(),D=R?we({distDir:e.clientDist,...m?.platformPages?{platformPages:m.platformPages}:{},decorateHtml:r=>W(W(r,Xe),k()),isBuildActive:()=>g,html503:`${be}${Nt()}</head><body style="font-family:system-ui;padding:40px;color:#333"><h1>503</h1><p>构建进行中,页面将在就绪后自动刷新</p></body></html>`,logger:t}):null;if(R){let r=P?.load()??null;t.info("dev_guard_mode",{strictPages:!0,routesCount:r?r.size:0})}t.info("dev_guard_mode",{hmrNoSubprotocol:o,mode:e.tokenState.mode,tokenShapeOk:e.tokenState.mode==="protected"&&a!==void 0,fsAllowNarrowed:e.fsAllowNarrowed===!0});function M(){return JSON.stringify({buildId:h,serverSessionId:v})}function k(){return`<script type="application/json" id="${Ye}">${JSON.stringify({serverSessionId:v,buildId:h})}</script>`}function q(r){r.setHeader("Content-Type","text/event-stream; charset=utf-8"),r.setHeader("Cache-Control","no-store"),r.setHeader("X-Accel-Buffering","no"),r.flushHeaders(),r.write(`data: ${M()}
8
8
 
9
- `),u.add(r);let l=setInterval(()=>{r.destroyed||r.write(`: keepalive
9
+ `),p.add(r);let u=setInterval(()=>{r.destroyed||r.write(`: keepalive
10
10
 
11
- `)},o);r.on("close",()=>{clearInterval(l),u.delete(r),t.debug("dev_sse_close",{subscriberCount:u.size})}),t.debug("dev_sse_conn",{subscriberCount:u.size})}let U=(r,l,E)=>{if(s){e.vite.middlewares(r,l,E);return}if(r.method==="GET"&&r.path===oe){q(l);return}let x=kt(r,c);r[n]=x.face,t.debug("dev_face_decision",{face:x.face,credSource:x.credSource,reason:x.reason,method:r.method,pathname:r.path,secFetchSite:r.headers["sec-fetch-site"]??null,secFetchMode:r.headers["sec-fetch-mode"]??null,requestId:r.headers["x-request-id"]??null,reqIdSource:"header"}),x.face==="dev"?e.vite.middlewares(r,l,E):E()},rt=(r,l,E)=>{ot(r,l,E)};async function ot(r,l,E){if(Pt(r.path??"/",e.spaExcludePrefixes)){E();return}let x=s?"classic":r[n]??"static";if(x==="static"&&I){I(r,l,E);return}if(x!=="static"){if(y){try{await it(r,l,E)}catch(w){E(w)}return}try{let w=await X(H.join(e.clientRoot,"index.html"),"utf-8");w=await e.vite.transformIndexHtml(r.originalUrl??"/",w),x==="dev"&&(w=z(w,Je(c,e.hmrPath,a))),w=e.decorateHtml?e.decorateHtml(w,"dev"):w,l.statusCode=200,l.setHeader("Content-Type","text/html; charset=utf-8"),x==="dev"&&l.setHeader("Cache-Control","no-store"),l.end(w),m.has("dev")||(m.add("dev"),t.info("dev_html_face",{face:"dev",pathname:r.path,source:"clientRoot"}))}catch(w){E(w)}return}v(r,l,()=>{if(r.method!=="GET"&&r.method!=="HEAD"){l.statusCode=404,l.setHeader("Cache-Control","no-store"),l.end("Not Found");return}X(H.join(e.clientDist,"index.html"),"utf-8").then(w=>{let D=z(z(w,Xe),j()),$=e.decorateHtml?e.decorateHtml(D,"static"):D;l.statusCode=200,l.setHeader("Content-Type","text/html; charset=utf-8"),l.setHeader("Cache-Control","no-store"),l.end($),t.debug("dev_spa_fallback_hit",{face:"static",pathname:r.path,method:r.method,distReady:!0})}).catch(()=>{l.statusCode=404,l.setHeader("Cache-Control","no-store"),l.end("Not Found"),t.debug("dev_spa_fallback_hit",{face:"static",pathname:r.path,method:r.method,distReady:!1})})})}async function it(r,l,E){if(r.method!=="GET"&&r.method!=="HEAD"){l.statusCode=404,l.setHeader("Cache-Control","no-store"),l.setHeader("Content-Type","text/plain; charset=utf-8"),l.end("Not Found");return}let x=null,w="",D=r.path??"/";try{let k=new URL(r.url??"/","http://tbox.local");D=k.pathname,w=k.search,x=V(k.pathname)}catch{x=null}if(x===null){T(r,l,404,C);return}let $=x,ce=S.get($);if(ce!==void 0){t.debug("strict_dev_platform_hit",{pathname:$});let k=H.join(e.clientRoot,R,`${ce.inputName}.ts`);if(!N(k)){t.warn("strict_dev_platform_entry_missing",{pathname:$,expected:H.relative(e.clientRoot,k)}),T(r,l,503,L);return}let A=await X(H.join(e.clientRoot,"index.html"),"utf-8"),F=G(A,d,`/${R}/${ce.inputName}.ts`);if(F===null){t.warn("strict_dev_platform_entry_replace_failed",{pathname:$,clientEntrySrc:d}),T(r,l,503,L);return}await ae(r,l,E,F,se(r));return}if(ne($)){l.statusCode=404,l.setHeader("Content-Type","text/plain; charset=utf-8"),l.setHeader("Cache-Control","no-store"),r.method!=="HEAD"&&l.write("Not Found"),l.end();return}let De=P?.load()??null;if(De===null){T(r,l,503,L);return}let $e=await X(H.join(e.clientRoot,"index.html"),"utf-8");if($!=="/"&&!$.endsWith("/")){let k=O(b,$);if(k&&re(k)&&N(H.join(k,"index.html"))){let A=`${D}/${w}`,F=A.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");T(r,l,301,`<!doctype html><html><head><title>301</title></head><body>Redirecting to <a href="${F}">${F}</a></body></html>`,{Location:A});return}}if($!=="/"&&$.endsWith("/")){let k=O(b,$),A=k===null?null:H.join(k,"index.html");if(A&&N(A)){let F=await X(A,"utf-8");l.statusCode=200,l.setHeader("Content-Type","text/html; charset=utf-8"),l.setHeader("Cache-Control","no-store"),r.method!=="HEAD"&&l.write(F),l.end();return}}let Ie=$.endsWith("/")&&$!=="/"?$.slice(0,-1):$,le=De.get(Ie);if(le===void 0){T(r,l,404,C);return}if(Ie==="/"){await ae(r,l,E,$e,se(r));return}let Te=H.join(e.clientRoot,R,`${le}.ts`);if(!N(Te)){t.warn("strict_dev_entry_missing",{pathname:$,expected:H.relative(e.clientRoot,Te)}),T(r,l,503,L);return}let ke=G($e,d,`/${R}/${le}.ts`);if(ke===null){t.warn("strict_dev_entry_replace_failed",{pathname:$,clientEntrySrc:d}),T(r,l,503,L);return}await ae(r,l,E,ke,se(r))}function se(r){return r[n]??"classic"}async function ae(r,l,E,x,w){try{let D=await e.vite.transformIndexHtml(r.originalUrl??"/",x);w==="dev"&&(D=z(D,Je(c,e.hmrPath,a))),D=e.decorateHtml?e.decorateHtml(D,"dev"):D,l.statusCode=200,l.setHeader("Content-Type","text/html; charset=utf-8"),w==="dev"&&l.setHeader("Cache-Control","no-store"),l.end(D)}catch(D){E(D)}}return{gate:U,final:rt,handleUpgrade:(r,l,E)=>{let x;try{x=new URL(r.url||"/","http://localhost").pathname}catch{return!1}if(x!==e.hmrPath)return!1;let w=r.headers["sec-websocket-protocol"],D=a?new URL(r.url||"/","http://localhost").searchParams.get(qe):void 0;if(!w)r.headers["sec-websocket-protocol"]=D==="vite-ping"?"vite-ping":"vite-hmr";else if(w!=="vite-hmr"&&w!=="vite-ping")return!1;if(!s){let $=Ze(r.url??"/");if(c===void 0||!xe($,c))return l.write(`HTTP/1.1 401 Unauthorized\r
11
+ `)},l);r.on("close",()=>{clearInterval(u),p.delete(r),t.debug("dev_sse_close",{subscriberCount:p.size})}),t.debug("dev_sse_conn",{subscriberCount:p.size})}let j=(r,u,E)=>{if(i){e.vite.middlewares(r,u,E);return}if(r.method==="GET"&&r.path===oe){q(u);return}let S=Pt(r,a);r[n]=S.face,t.debug("dev_face_decision",{face:S.face,credSource:S.credSource,reason:S.reason,method:r.method,pathname:r.path,secFetchSite:r.headers["sec-fetch-site"]??null,secFetchMode:r.headers["sec-fetch-mode"]??null,requestId:r.headers["x-request-id"]??null,reqIdSource:"header"}),S.face==="dev"?e.vite.middlewares(r,u,E):E()},rt=(r,u,E)=>{ot(r,u,E)};async function ot(r,u,E){if(kt(r.path??"/",e.spaExcludePrefixes)){E();return}let S=i?"classic":r[n]??"static";if(S==="static"&&D){D(r,u,E);return}if(S!=="static"){if(R){try{await it(r,u,E)}catch(w){E(w)}return}try{let w=await X(C.join(e.clientRoot,"index.html"),"utf-8");w=await e.vite.transformIndexHtml(r.originalUrl??"/",w),S==="dev"&&(w=W(w,Je(a,e.hmrPath,o))),w=e.decorateHtml?e.decorateHtml(w,"dev"):w,u.statusCode=200,u.setHeader("Content-Type","text/html; charset=utf-8"),S==="dev"&&u.setHeader("Cache-Control","no-store"),u.end(w),c.has("dev")||(c.add("dev"),t.info("dev_html_face",{face:"dev",pathname:r.path,source:"clientRoot"}))}catch(w){E(w)}return}y(r,u,()=>{if(r.method!=="GET"&&r.method!=="HEAD"){u.statusCode=404,u.setHeader("Cache-Control","no-store"),u.end("Not Found");return}X(C.join(e.clientDist,"index.html"),"utf-8").then(w=>{let $=W(W(w,Xe),k()),I=e.decorateHtml?e.decorateHtml($,"static"):$;u.statusCode=200,u.setHeader("Content-Type","text/html; charset=utf-8"),u.setHeader("Cache-Control","no-store"),u.end(I),t.debug("dev_spa_fallback_hit",{face:"static",pathname:r.path,method:r.method,distReady:!0})}).catch(()=>{u.statusCode=404,u.setHeader("Cache-Control","no-store"),u.end("Not Found"),t.debug("dev_spa_fallback_hit",{face:"static",pathname:r.path,method:r.method,distReady:!1})})})}async function it(r,u,E){if(r.method!=="GET"&&r.method!=="HEAD"){u.statusCode=404,u.setHeader("Cache-Control","no-store"),u.setHeader("Content-Type","text/plain; charset=utf-8"),u.end("Not Found");return}let S=null,w="",$=r.path??"/";try{let N=new URL(r.url??"/","http://tbox.local");$=N.pathname,w=N.search,S=B(N.pathname)}catch{S=null}if(S===null){T(r,u,404,A);return}let I=S,ce=x.get(I);if(ce!==void 0){t.debug("strict_dev_platform_hit",{pathname:I});let N=C.join(e.clientRoot,b,`${ce.inputName}.ts`);if(!H(N)){t.warn("strict_dev_platform_entry_missing",{pathname:I,expected:C.relative(e.clientRoot,N)}),T(r,u,503,U);return}let O=await X(C.join(e.clientRoot,"index.html"),"utf-8"),F=G(O,d,`/${b}/${ce.inputName}.ts`);if(F===null){t.warn("strict_dev_platform_entry_replace_failed",{pathname:I,clientEntrySrc:d}),T(r,u,503,U);return}await ae(r,u,E,F,se(r));return}if(ne(I)){u.statusCode=404,u.setHeader("Content-Type","text/plain; charset=utf-8"),u.setHeader("Cache-Control","no-store"),r.method!=="HEAD"&&u.write("Not Found"),u.end();return}let De=P?.load()??null;if(De===null){T(r,u,503,U);return}let $e=await X(C.join(e.clientRoot,"index.html"),"utf-8");if(I!=="/"&&!I.endsWith("/")){let N=L(s,I);if(N&&re(N)&&H(C.join(N,"index.html"))){let O=`${$}/${w}`,F=O.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");T(r,u,301,`<!doctype html><html><head><title>301</title></head><body>Redirecting to <a href="${F}">${F}</a></body></html>`,{Location:O});return}}if(I!=="/"&&I.endsWith("/")){let N=L(s,I),O=N===null?null:C.join(N,"index.html");if(O&&H(O)){let F=await X(O,"utf-8");u.statusCode=200,u.setHeader("Content-Type","text/html; charset=utf-8"),u.setHeader("Cache-Control","no-store"),r.method!=="HEAD"&&u.write(F),u.end();return}}let Ie=I.endsWith("/")&&I!=="/"?I.slice(0,-1):I,le=De.get(Ie);if(le===void 0){T(r,u,404,A);return}if(Ie==="/"){await ae(r,u,E,$e,se(r));return}let Te=C.join(e.clientRoot,b,`${le}.ts`);if(!H(Te)){t.warn("strict_dev_entry_missing",{pathname:I,expected:C.relative(e.clientRoot,Te)}),T(r,u,503,U);return}let Pe=G($e,d,`/${b}/${le}.ts`);if(Pe===null){t.warn("strict_dev_entry_replace_failed",{pathname:I,clientEntrySrc:d}),T(r,u,503,U);return}await ae(r,u,E,Pe,se(r))}function se(r){return r[n]??"classic"}async function ae(r,u,E,S,w){try{let $=await e.vite.transformIndexHtml(r.originalUrl??"/",S);w==="dev"&&($=W($,Je(a,e.hmrPath,o))),$=e.decorateHtml?e.decorateHtml($,"dev"):$,u.statusCode=200,u.setHeader("Content-Type","text/html; charset=utf-8"),w==="dev"&&u.setHeader("Cache-Control","no-store"),u.end($)}catch($){E($)}}return{gate:j,final:rt,handleUpgrade:(r,u,E)=>{let S;try{S=new URL(r.url||"/","http://localhost").pathname}catch{return!1}if(S!==e.hmrPath)return!1;let w=r.headers["sec-websocket-protocol"],$=o?new URL(r.url||"/","http://localhost").searchParams.get(qe):void 0;if(!w)r.headers["sec-websocket-protocol"]=$==="vite-ping"?"vite-ping":"vite-hmr";else if(w!=="vite-hmr"&&w!=="vite-ping")return!1;if(!i){let I=Ze(r.url??"/");if(a===void 0||!xe(I,a))return u.write(`HTTP/1.1 401 Unauthorized\r
12
12
  Connection: close\r
13
13
  Content-Length: 0\r
14
14
  \r
15
- `),l.end(()=>{l.destroyed||l.destroy()}),t.info("dev_hmr_upgrade",{outcome:"rejected-401",pathname:x,protocol:r.headers["sec-websocket-protocol"]}),!0}return!w&&(D==="vite-hmr"||D==="vite-ping")&&f.add(r),e.hmrHub.emit("upgrade",r,l,E),t.info("dev_hmr_upgrade",{outcome:"claimed",pathname:x,protocol:r.headers["sec-websocket-protocol"]}),!0},notifyBuildEnd:()=>{p=!1,h+=1;for(let r of u)r.destroyed||r.write(`data: ${M()}
15
+ `),u.end(()=>{u.destroyed||u.destroy()}),t.info("dev_hmr_upgrade",{outcome:"rejected-401",pathname:S,protocol:r.headers["sec-websocket-protocol"]}),!0}return!w&&($==="vite-hmr"||$==="vite-ping")&&f.add(r),e.hmrHub.emit("upgrade",r,u,E),t.info("dev_hmr_upgrade",{outcome:"claimed",pathname:S,protocol:r.headers["sec-websocket-protocol"]}),!0},notifyBuildEnd:()=>{g=!1,h+=1;for(let r of p)r.destroyed||r.write(`data: ${M()}
16
16
 
17
- `);t.info("dev_build_end",{buildId:h})},notifyBuildStart:()=>{p=!0,t.info("dev_build_start",{})}}}import{randomUUID as Se}from"crypto";var Qe=String.raw`function installPreviewCapture(ticket) {
17
+ `);t.info("dev_build_end",{buildId:h})},notifyBuildStart:()=>{g=!0,t.info("dev_build_start",{})}}}import{randomUUID as Se}from"crypto";var Qe=String.raw`function installPreviewCapture(ticket, ignoredScriptUrls = []) {
18
18
  const root = window;
19
19
  if (root.__tboxPreviewErrors)
20
20
  return;
@@ -57,7 +57,35 @@ Content-Length: 0\r
57
57
  return undefined;
58
58
  }
59
59
  };
60
+ const extensionSource = /^(?:chrome-extension|moz-extension|safari-web-extension|safari-extension):\/\//i;
61
+ const ignoredSources = new Set(ignoredScriptUrls);
62
+ const isNoise = (reason, event) => {
63
+ const sources = [];
64
+ const filename = event?.filename || event?.target?.src;
65
+ if (filename)
66
+ sources.push(text(filename, 6000));
67
+ const stack = text(get(reason, 'stack'), 6001);
68
+ // Incomplete evidence must not hide an application frame beyond the capture limit.
69
+ if (stack.length > 6000)
70
+ return false;
71
+ for (const line of stack.split('\n')) {
72
+ // Inspect stack frames, never URLs mentioned in the error message.
73
+ if (!/^\s*at\s|^[^\s]*@/.test(line))
74
+ continue;
75
+ const urls = line.match(/(?:[a-z][a-z\d+.-]*:\/\/|blob:)[^\s)]+/gi) || [];
76
+ if (!urls.length && !/\((?:native|<anonymous>)\)|\[native code\]/.test(line))
77
+ return false;
78
+ sources.push(...urls.map(source => source.replace(/:\d+(?::\d+)?$/, '')));
79
+ }
80
+ return sources.length > 0 && sources.every(source => {
81
+ if (extensionSource.test(source))
82
+ return true;
83
+ return ignoredSources.has(url(source));
84
+ });
85
+ };
60
86
  const report = (kind, reason, event) => {
87
+ if (isNoise(reason, event))
88
+ return;
61
89
  state.failed = true;
62
90
  try {
63
91
  const data = {
@@ -159,7 +187,7 @@ Content-Length: 0\r
159
187
  document.addEventListener('DOMContentLoaded', () => { ready = true; observe(); }, { once: true });
160
188
  bind();
161
189
  hot.dispose(() => { clearTimeout(timer); state.connected = false; state.flush = () => { }; });
162
- }`;var tt="tbox:preview-report",nt="[TBOX_PREVIEW_REPORT] ",_e="\0tbox-preview-errors",Re=e=>typeof e=="string"&&/^[\w:-]{1,160}$/.test(e),Ct=(e,t)=>typeof e=="string"?e.slice(0,t).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,""):"",ie=(e,t)=>Ct(e,t).replace(/https?:\/\/[^\s)]+/g,n=>{try{let s=new URL(n);return s.origin+s.pathname}catch{return"[URL]"}});function Mt(e={}){let t=Math.max(5e3,Math.min(6e4,Math.trunc(e.observationMs||5e3))),n=Se(),s=new Map,c=new Map,a=new Map,f=0,h="/",p=!1,g=()=>{},u=(o,v,m={})=>{let i={v:1,type:v,serverSessionId:n,scopeId:o.scopeId,pageId:o.pageId,documentEpoch:o.epoch,seq:++o.seq,errorRevision:o.revision,...m},y=nt+JSON.stringify(i)+`
163
- `;for(;Buffer.byteLength(y)>16384;){let d=["stack","message","filename"].sort((b,S)=>String(i[S]??"").length-String(i[b]??"").length)[0],R=String(i[d]??"");if(R.length<2)return;i[d]=R.slice(0,Math.floor(R.length/2)),y=nt+JSON.stringify(i)+`
190
+ }`;var tt="tbox:preview-report",nt="[TBOX_PREVIEW_REPORT] ",Re="\0tbox-preview-errors",_e=e=>typeof e=="string"&&/^[\w:-]{1,160}$/.test(e),Ct=(e,t)=>typeof e=="string"?e.slice(0,t).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,""):"",ie=(e,t)=>Ct(e,t).replace(/https?:\/\/[^\s)]+/g,n=>{try{let i=new URL(n);return i.origin+i.pathname}catch{return"[URL]"}});function Mt(e={}){let t=new Set(e.excludedPagePaths??[]);for(let c of t)if(!c.startsWith("/")||c.startsWith("//")||new URL(c,"http://tbox.local").pathname!==c)throw new Error("previewErrorReporter: excludedPagePaths requires absolute pathnames without query/hash");let n=Math.max(5e3,Math.min(6e4,Math.trunc(e.observationMs||5e3))),i=(e.ignoredScriptUrls??[]).map(c=>{let m;try{m=new URL(c)}catch{throw new Error("previewErrorReporter: ignoredScriptUrls requires absolute HTTP(S) URLs")}if(!["http:","https:"].includes(m.protocol))throw new Error("previewErrorReporter: ignoredScriptUrls requires absolute HTTP(S) URLs");return m.origin+m.pathname}),a=Se(),o=new Map,f=new Map,h=new Map,g=0,v="/",p=!1,l=()=>{},y=(c,m,R={})=>{let d={v:1,type:m,serverSessionId:a,scopeId:c.scopeId,pageId:c.pageId,documentEpoch:c.epoch,seq:++c.seq,errorRevision:c.revision,...R},b=nt+JSON.stringify(d)+`
191
+ `;for(;Buffer.byteLength(b)>16384;){let s=["stack","message","filename"].sort((P,D)=>String(d[D]??"").length-String(d[P]??"").length)[0],x=String(d[s]??"");if(x.length<2)return;d[s]=x.slice(0,Math.floor(x.length/2)),b=nt+JSON.stringify(d)+`
164
192
  `}process.stdout.write(`
165
- `+y)};return{name:"tbox-preview-error-reporter",apply:"serve",configResolved(o){p=e.enabled!==!1&&!process.env.VITEST&&o.command==="serve",h=o.base},resolveId(o){if(p&&o===_e)return _e},load(o){if(p&&o===_e)return`(${et})(import.meta.hot);`},transformIndexHtml:{order:"pre",handler(){if(!p)return;let o=Date.now();for(let[m,i]of s)o-i.at>6e5&&s.delete(m);s.size>=256&&s.delete(s.keys().next().value);let v=Se();return s.set(v,{epoch:++f,at:o}),[{tag:"script",children:`(${Qe})(${JSON.stringify(v)});`,injectTo:"head-prepend"},{tag:"script",attrs:{type:"module",src:`${h}@id/__x00__tbox-preview-errors`},injectTo:"head-prepend"}]}},configureServer(o){if(!p)return;let v=(i,y)=>{try{if(!i||!Re(i.ticket)||!Re(i.pageId)||!Re(i.scopeId))return;let d=c.get(i.pageId),R=s.get(i.ticket)??(d&&d.ticket===i.ticket?{epoch:d.epoch,at:d.startedAt}:void 0);if(!R)return;if(i.type==="page-start"){if(d){if(d.ticket!==i.ticket||d.client!==y&&d.client.socket.readyState===1)return;d.client!==y&&(d.available=!1),d.client=y}else{for(let[P,I]of c)I.client.socket.readyState!==1&&Date.now()-I.startedAt>6e5&&(c.delete(P),a.get(I.scopeId)===I&&a.delete(I.scopeId));if(c.size>=128)return;let b=i.scopeId,S=a.get(b);if(S&&R.epoch<=S.epoch)return;S?.client.socket.readyState===1?b=Se():S&&c.delete(S.pageId),d={ticket:i.ticket,scopeId:b,pageId:i.pageId,epoch:R.epoch,client:y,seq:0,clientSeq:0,revision:0,startedAt:Date.now(),available:!0,windowAt:Date.now(),count:0},c.set(i.pageId,d),a.set(b,d),u(d,"page-start")}y.send("tbox:preview-bound",{pageId:d.pageId,scopeId:d.scopeId,observationMs:t});return}if(!d||d.ticket!==i.ticket||d.client!==y||a.get(d.scopeId)!==d||!Number.isSafeInteger(i.clientSeq)||i.clientSeq<1)return;if(i.clientSeq<=d.clientSeq){y.send("tbox:preview-ack",{pageId:d.pageId,clientSeq:i.clientSeq});return}if(i.clientSeq!==d.clientSeq+1&&(d.available=!1),d.clientSeq=i.clientSeq,Date.now()-d.windowAt>=1e3&&(d.windowAt=Date.now(),d.count=0),++d.count>10){d.available&&(d.available=!1,u(d,"unavailable"));return}if(i.type==="error"){if(!["javascript","promise","script"].includes(i.kind))return;d.revision++,u(d,"error",{kind:i.kind,name:ie(i.name,120),message:ie(i.message,3e3),stack:ie(i.stack,5e3),filename:ie(i.filename,1e3).split(/[?#]/)[0],line:Number.isSafeInteger(i.line)&&i.line>=0?i.line:0,column:Number.isSafeInteger(i.column)&&i.column>=0?i.column:0})}else i.type==="observed"&&d.available&&!d.revision&&Date.now()-d.startedAt>=t?u(d,"observed",{observedMs:t}):i.type==="unavailable"&&(d.available=!1,u(d,"unavailable"));y.send("tbox:preview-ack",{pageId:d.pageId,clientSeq:i.clientSeq})}catch{}},m=i=>{i.once("close",()=>{for(let y of c.values())y.client.socket===i&&(y.available=!1,u(y,"unavailable"))})};o.ws.on(tt,v),o.ws.on("connection",m),g=()=>{o.ws.off(tt,v),o.ws.off("connection",m),c.clear(),a.clear(),s.clear()}},closeBundle(){g()}}}export{Le as DEFAULT_CLIENT_ENTRY_SRC,je as DEFAULT_GEN_DIR_NAME,Ue as DEFAULT_MOUNT_HELPER_ID,oe as DEV_SSE_PATH,Ke as DEV_TOKEN_ENV,K as DEV_TOKEN_NAME,He as RESERVED_ROUTE_SEGMENTS,Y as RUNTIME_PATH,ue as SCRIPT_TAG,C as STRICT_HTML_404,L as STRICT_HTML_503,ge as buildDocumentHtml,me as buildEntryModule,B as canonicalRouteKey,we as createStrictStaticHandler,Ht as createTboxDevRuntime,V as decodeRoutePathname,he as generateRouteFiles,Pe as injectScript,lt as installInspector,re as isDirectory,N as isFile,ct as isReady,ne as lastSegmentHasExtension,Fe as listPublicFiles,W as parseRoutesJson,Mt as previewErrorReporter,ze as publishStagedDist,G as replaceClientEntrySrc,It as resolveDevTokenFromEnv,Ve as resolveStagingDir,Q as routeDocumentOutput,O as safeJoin,T as sendStrictHtml,vt as tboxMpaPlugin,Be as validateRouteConflicts,Ce as validateRoutes};
193
+ `+b)};return{name:"tbox-preview-error-reporter",apply:"serve",configResolved(c){p=e.enabled!==!1&&!process.env.VITEST&&c.command==="serve",v=c.base},resolveId(c){if(p&&c===Re)return Re},load(c){if(p&&c===Re)return`(${et})(import.meta.hot);`},transformIndexHtml:{order:"pre",handler(c,m){if(!p)return;let R=new URL(m?.originalUrl??m?.path??"/","http://tbox.local").pathname;if(t.has(R))return;let d=Date.now();for(let[s,x]of o)d-x.at>6e5&&o.delete(s);o.size>=256&&o.delete(o.keys().next().value);let b=Se();return o.set(b,{epoch:++g,at:d}),[{tag:"script",children:`(${Qe})(${JSON.stringify(b)}, ${JSON.stringify(i).replace(/</g,"\\u003c")});`,injectTo:"head-prepend"},{tag:"script",attrs:{type:"module",src:`${v}@id/__x00__tbox-preview-errors`},injectTo:"head-prepend"}]}},configureServer(c){if(!p)return;let m=(d,b)=>{try{if(!d||!_e(d.ticket)||!_e(d.pageId)||!_e(d.scopeId))return;let s=f.get(d.pageId),x=o.get(d.ticket)??(s&&s.ticket===d.ticket?{epoch:s.epoch,at:s.startedAt}:void 0);if(!x)return;if(d.type==="page-start"){if(s){if(s.ticket!==d.ticket||s.client!==b&&s.client.socket.readyState===1)return;s.client!==b&&(s.available=!1),s.client=b}else{for(let[M,k]of f)k.client.socket.readyState!==1&&Date.now()-k.startedAt>6e5&&(f.delete(M),h.get(k.scopeId)===k&&h.delete(k.scopeId));if(f.size>=128)return;let P=d.scopeId,D=h.get(P);if(D&&x.epoch<=D.epoch)return;D?.client.socket.readyState===1?P=Se():D&&f.delete(D.pageId),s={ticket:d.ticket,scopeId:P,pageId:d.pageId,epoch:x.epoch,client:b,seq:0,clientSeq:0,revision:0,startedAt:Date.now(),available:!0,windowAt:Date.now(),count:0},f.set(d.pageId,s),h.set(P,s),y(s,"page-start")}b.send("tbox:preview-bound",{pageId:s.pageId,scopeId:s.scopeId,observationMs:n});return}if(!s||s.ticket!==d.ticket||s.client!==b||h.get(s.scopeId)!==s||!Number.isSafeInteger(d.clientSeq)||d.clientSeq<1)return;if(d.clientSeq<=s.clientSeq){b.send("tbox:preview-ack",{pageId:s.pageId,clientSeq:d.clientSeq});return}if(d.clientSeq!==s.clientSeq+1&&(s.available=!1),s.clientSeq=d.clientSeq,Date.now()-s.windowAt>=1e3&&(s.windowAt=Date.now(),s.count=0),++s.count>10){s.available&&(s.available=!1,y(s,"unavailable"));return}if(d.type==="error"){if(!["javascript","promise","script"].includes(d.kind))return;s.revision++,y(s,"error",{kind:d.kind,name:ie(d.name,120),message:ie(d.message,3e3),stack:ie(d.stack,5e3),filename:ie(d.filename,1e3).split(/[?#]/)[0],line:Number.isSafeInteger(d.line)&&d.line>=0?d.line:0,column:Number.isSafeInteger(d.column)&&d.column>=0?d.column:0})}else d.type==="observed"&&s.available&&!s.revision&&Date.now()-s.startedAt>=n?y(s,"observed",{observedMs:n}):d.type==="unavailable"&&(s.available=!1,y(s,"unavailable"));b.send("tbox:preview-ack",{pageId:s.pageId,clientSeq:d.clientSeq})}catch{}},R=d=>{d.once("close",()=>{for(let b of f.values())b.client.socket===d&&(b.available=!1,y(b,"unavailable"))})};c.ws.on(tt,m),c.ws.on("connection",R),l=()=>{c.ws.off(tt,m),c.ws.off("connection",R),f.clear(),h.clear(),o.clear()}},closeBundle(){l()}}}export{Le as DEFAULT_CLIENT_ENTRY_SRC,Ue as DEFAULT_GEN_DIR_NAME,je as DEFAULT_MOUNT_HELPER_ID,oe as DEV_SSE_PATH,Ke as DEV_TOKEN_ENV,K as DEV_TOKEN_NAME,He as RESERVED_ROUTE_SEGMENTS,Y as RUNTIME_PATH,ue as SCRIPT_TAG,A as STRICT_HTML_404,U as STRICT_HTML_503,ge as buildDocumentHtml,me as buildEntryModule,z as canonicalRouteKey,we as createStrictStaticHandler,Ht as createTboxDevRuntime,B as decodeRoutePathname,he as generateRouteFiles,ke as injectScript,lt as installInspector,re as isDirectory,H as isFile,ct as isReady,ne as lastSegmentHasExtension,Fe as listPublicFiles,V as parseRoutesJson,Mt as previewErrorReporter,We as publishStagedDist,G as replaceClientEntrySrc,It as resolveDevTokenFromEnv,Be as resolveStagingDir,Q as routeDocumentOutput,L as safeJoin,T as sendStrictHtml,vt as tboxMpaPlugin,ze as validateRouteConflicts,Ce as validateRoutes};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tbox.cn/app-sdk-server",
3
- "version": "0.26.4",
3
+ "version": "0.26.6",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "tbox-inspector-check": "bin/check-inspector.mjs"
@@ -56,7 +56,7 @@
56
56
  "typescript": "5.9.3",
57
57
  "vite": "6.4.3",
58
58
  "vitest": "4.1.10",
59
- "@tbox.cn/app-agent-sdk-server": "0.3.4",
59
+ "@tbox.cn/app-agent-sdk-server": "0.3.5",
60
60
  "@tbox.cn/app-sdk-client": "0.21.4"
61
61
  },
62
62
  "license": "MIT",