@tbox.cn/app-sdk-server 0.26.5 → 0.26.7
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/dist/platform/index.d.ts +2 -0
- package/dist/platform/index.js +13 -13
- package/package.json +4 -4
package/dist/platform/index.d.ts
CHANGED
|
@@ -141,6 +141,8 @@ interface PreviewErrorReporterOptions {
|
|
|
141
141
|
enabled?: boolean;
|
|
142
142
|
/** Explicit third-party script URLs to ignore (absolute HTTP(S); query/hash are ignored). */
|
|
143
143
|
ignoredScriptUrls?: readonly string[];
|
|
144
|
+
/** Exact document pathnames to omit from capture; query/hash are ignored. Defaults to none. */
|
|
145
|
+
excludedPagePaths?: readonly string[];
|
|
144
146
|
}
|
|
145
147
|
/** Dev-only browser exception transport over the application's existing Vite HMR socket. */
|
|
146
148
|
declare function previewErrorReporter(options?: PreviewErrorReporterOptions): Plugin;
|
package/dist/platform/index.js
CHANGED
|
@@ -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(i=>setTimeout(i,1e3*(t+1)))}console.error("[inspector] runtime unavailable; inspector script will be skipped")}function
|
|
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,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function me(e,t,n){let i=t??e.page??`@/pages/${e.id}`;return`import { mountPage } from '${n}';
|
|
2
2
|
mountPage(() => import('${i}'));
|
|
3
|
-
`}function G(e,t,n){let i=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),
|
|
4
|
-
- ${
|
|
5
|
-
- `)}`);let o=t!==!1&&te(t)?Fe(t):[],
|
|
6
|
-
- ${
|
|
7
|
-
- `)}`);return{entries:s.entries,warnings:s.warnings}}function vt(e={}){let t=e.genDirName??Ue,n=e.clientEntrySrc??Le,i=e.mountHelperId??je,s=e.extraDocuments??[],o={root:"",renames:{},inputPaths:[],transaction:!1,wrote:!1};return{name:"tbox-mpa-pages",config(u,y){if(y.command!=="build"||process.env.VITEST)return;let g=_.resolve(u.root??process.cwd());o.root=g;let h=e.routesModule??_.join(g,"src/business/routes.json"),f=e.publicDir===!1?!1:e.publicDir??_.join(g,"public"),a=Me(h,f,s,g);if(!a)return;for(let b of a.warnings)console.warn(`[tbox-mpa] ${b}`);let m=he({root:g,entries:a.entries,extraDocuments:s,genDirName:t,mountHelperId:i,clientEntrySrc:n,withHtml:!0});o.renames=m.renames,o.inputPaths=Object.values(m.inputs);let p=u.build?.watch,v=typeof p=="object"&&p!==null,c=u.build?.outDir??"dist",w=_.resolve(g,c),d={build:{rollupOptions:{input:m.inputs}}};if(!v&&Object.keys(m.inputs).length+1>1){let b=Be(w),R=_.relative(g,b);R.startsWith("..")||_.isAbsolute(R)?console.warn(`[tbox-mpa] outDir ${c} 位于 root 外——跳过输出事务(直写 dist)`):(o.stagingDir=b,o.distDir=w,o.transaction=!0,d.build.outDir=R)}return d},configResolved(u){if(u.command!=="build"||process.env.VITEST||o.inputPaths.length===0)return;if(u.base!=="/")throw new Error(`[tbox-mpa] MPA 文档模式要求 vite base === '/'(当前 "${u.base}")——生成文档的资产引用会随路径深度断链`);let y=u.build.rollupOptions.input,g=y===void 0?[]:typeof y=="string"||Array.isArray(y)?Array.isArray(y)?y:[y]:Object.values(y),h=new Set(g.map(f=>_.resolve(u.root,f)));for(let f of o.inputPaths)if(!h.has(f))throw new Error(`[tbox-mpa] 生成输入 ${f} 未出现在最终 rollupOptions.input——被其他配置移除(框架产物不可覆盖)`)},configureServer(u){if(process.env.VITEST)return;let y=u.config.root,g=e.routesModule??_.join(y,"src/business/routes.json"),h=e.publicDir===!1?!1:e.publicDir??_.join(y,"public"),f=Me(g,h,s,y);if(f){for(let a of f.warnings)console.warn(`[tbox-mpa] ${a}`);he({root:y,entries:f.entries,extraDocuments:s,genDirName:t,mountHelperId:i,clientEntrySrc:n,withHtml:!1})}},generateBundle:{order:"post",handler(u,y){for(let[g,h]of Object.entries(y)){if(h.type!=="asset")continue;let f=o.renames[g];f!==void 0&&(h.fileName=f)}}},writeBundle(){o.wrote=!0},closeBundle(){o.transaction&&(o.transaction=!1,o.stagingDir&&o.distDir&&(o.wrote?Ve(o.stagingDir,o.distDir):ve(o.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 i=B(n.path);i&&t.set(i,n)}return t}var M='<!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,i,s){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)),s)for(let[o,u]of Object.entries(s))t.setHeader(o,u);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 O(e,t){let n=J.resolve(e,`.${t}`);return n!==e&&!n.startsWith(e+J.sep)?null:n}function H(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:i}=e,s=e.html503??L,o=e.platformPages??[],u=e.isBuildActive??(()=>!1),y=bt.static(t,{index:!1,redirect:!1,fallthrough:!0}),g=ye(o);async function h(f,a,m){let p;try{p=await yt(m,"utf-8")}catch{T(f,a,u()?503:404,u()?s:M);return}let v=n?await n(p):p;a.statusCode=200,a.setHeader("Content-Type","text/html; charset=utf-8"),a.setHeader("Cache-Control","no-store"),a.setHeader("Content-Length",Buffer.byteLength(v)),f.method!=="HEAD"&&a.write(v),a.end()}return(f,a,m)=>{(async()=>{if(f.method!=="GET"&&f.method!=="HEAD"){a.statusCode=404,a.setHeader("Cache-Control","no-store"),a.setHeader("Content-Type","text/plain; charset=utf-8"),a.end("Not Found");return}if(!H(J.join(t,"index.html"))){i?.debug("strict_static_unready",{pathname:f.path}),T(f,a,503,s);return}let p=wt(f.url??"/");if(!p){T(f,a,404,M);return}let{decoded:v,search:c}=p,w=g.get(v);if(w){let b=O(t,`/${w.document}`);b&&H(b)?await h(f,a,b):(i?.debug("strict_static_platform_off",{pathname:v}),T(f,a,404,M));return}if(v.endsWith(".html")||v.endsWith(".htm")){let b=O(t,v);if(b&&H(b)){await h(f,a,b);return}T(f,a,u()?503:404,u()?s:M);return}if(await new Promise(b=>{y(f,a,()=>b())}),a.writableEnded)return;if(v.endsWith("/")){let b=O(t,v),R=b===null?null:J.join(b,"index.html");if(R&&H(R)){await h(f,a,R);return}}else{let b=O(t,v);if(b&&re(b)&&H(J.join(b,"index.html"))){let R=`${p.rawPathname}/${c}`,I=R.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),k=`<!doctype html><html><head><title>301</title></head><body>Redirecting to <a href="${I}">${I}</a></body></html>`;T(f,a,301,k,{Location:R});return}}let d=u()?503:404;if(ne(v)){i?.debug("strict_static_miss_asset",{pathname:v,buildActive:u()}),a.statusCode=d,a.setHeader("Content-Type","text/plain; charset=utf-8"),a.setHeader("Cache-Control","no-store"),f.method!=="HEAD"&&a.write(u()?"Service Unavailable":"Not Found"),a.end();return}i?.debug("strict_static_miss",{pathname:v,buildActive:u()}),T(f,a,d,u()?s:M)})().catch(m)}}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 kt(e,t){if(t===void 0)return{face:"static",credSource:"none",reason:"no-cred"};let n=Ze(e.url??"/"),i=Tt(e.headers.cookie),s="none";if(n!==void 0&&xe(n,t)?s="query":i!==void 0&&xe(i,t)?s="cookie":(n!==void 0||i!==void 0)&&(s="invalid"),s!=="query"&&s!=="cookie")return{face:"static",credSource:s,reason:"no-cred"};let o=e.headers["sec-fetch-site"],u=e.headers["sec-fetch-mode"];return u==="navigate"?{face:"dev",credSource:s,reason:"navigate"}:o==="same-origin"||o==="none"?{face:"dev",credSource:s,reason:"same-origin"}:o===void 0&&u===void 0?{face:"dev",credSource:s,reason:"no-sec-fetch-header"}:{face:"static",credSource:s,reason:"cross-site-subresource"}}function V(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 Nt(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 Pt(){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",s=e.tokenState.mode==="protected"?e.tokenState.token:void 0,o=!i&&s!==void 0&&e.vite.ws!==void 0,u=new WeakSet;e.vite.ws?.on("headers",(r,l)=>{if(u.has(l))for(let x=r.length-1;x>=0;x--)/^sec-websocket-protocol\s*:/i.test(r[x])&&r.splice(x,1)});let y=0,g=!1,h=Et(),f=new Set,a=e.sseKeepaliveMs??15e3,m=Dt.static(e.clientDist,{index:!1,fallthrough:!0}),p=new Set,v=e.pagePolicy,c=v!==void 0&&St(v.routesModule),w=v?.clientEntrySrc??"/src/main.tsx",d=v?.genDirName??".tbox-gen",b=v?.publicDir??C.join(e.clientRoot,"public"),R=ye(v?.platformPages??[]),I=(()=>{if(!c)return null;let r=null;return{load:()=>{try{let x=Rt(v.routesModule);if(r&&r.mtimeMs===x.mtimeMs)return r.byPath;let S=W(_t(v.routesModule,"utf-8"));if(!S.ok)return t.warn("strict_routes_invalid",{errors:S.errors.slice(0,3)}),null;let E=new Map;for(let D of S.entries)E.set(D.path,D.id);return r={mtimeMs:x.mtimeMs,byPath:E},E}catch{return null}}}})(),k=c?we({distDir:e.clientDist,...v?.platformPages?{platformPages:v.platformPages}:{},decorateHtml:r=>V(V(r,Xe),U()),isBuildActive:()=>g,html503:`${be}${Pt()}</head><body style="font-family:system-ui;padding:40px;color:#333"><h1>503</h1><p>构建进行中,页面将在就绪后自动刷新</p></body></html>`,logger:t}):null;if(c){let r=I?.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"&&s!==void 0,fsAllowNarrowed:e.fsAllowNarrowed===!0});function N(){return JSON.stringify({buildId:y,serverSessionId:h})}function U(){return`<script type="application/json" id="${Ye}">${JSON.stringify({serverSessionId:h,buildId:y})}</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: ${N()}
|
|
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
|
+
- ${f.join(`
|
|
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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),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
|
-
`),
|
|
9
|
+
`),p.add(r);let u=setInterval(()=>{r.destroyed||r.write(`: keepalive
|
|
10
10
|
|
|
11
|
-
`)},
|
|
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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");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
|
-
`),
|
|
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:
|
|
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;
|
|
@@ -187,7 +187,7 @@ Content-Length: 0\r
|
|
|
187
187
|
document.addEventListener('DOMContentLoaded', () => { ready = true; observe(); }, { once: true });
|
|
188
188
|
bind();
|
|
189
189
|
hot.dispose(() => { clearTimeout(timer); state.connected = false; state.flush = () => { }; });
|
|
190
|
-
}`;var tt="tbox:preview-report",nt="[TBOX_PREVIEW_REPORT] ",
|
|
191
|
-
`;for(;Buffer.byteLength(
|
|
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)+`
|
|
192
192
|
`}process.stdout.write(`
|
|
193
|
-
`+
|
|
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.
|
|
3
|
+
"version": "0.26.7",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"tbox-inspector-check": "bin/check-inspector.mjs"
|
|
@@ -38,12 +38,12 @@
|
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
40
|
"@ag-ui/core": "0.0.47",
|
|
41
|
-
"@tbox.cn/app-contracts": "0.13.
|
|
41
|
+
"@tbox.cn/app-contracts": "0.13.4",
|
|
42
42
|
"@tbox.cn/app-sdk-core": "0.20.5",
|
|
43
43
|
"express": "4.22.2",
|
|
44
44
|
"jose": "6.2.8",
|
|
45
45
|
"zod": "3.25.76",
|
|
46
|
-
"@tbox.cn/app-toolkit": "0.8.
|
|
46
|
+
"@tbox.cn/app-toolkit": "0.8.6"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
49
|
"@mastra/core": "1.59.0",
|
|
@@ -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.
|
|
59
|
+
"@tbox.cn/app-agent-sdk-server": "0.3.6",
|
|
60
60
|
"@tbox.cn/app-sdk-client": "0.21.4"
|
|
61
61
|
},
|
|
62
62
|
"license": "MIT",
|