@tbox.cn/app-sdk-server 0.21.2 → 0.22.1
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 +64 -2
- package/dist/platform/index.js +11 -1
- package/package.json +4 -4
package/dist/platform/index.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import { Express } from 'express';
|
|
1
|
+
import { Express, RequestHandler } from 'express';
|
|
2
|
+
import { IncomingMessage, Server } from 'node:http';
|
|
3
|
+
import { Duplex } from 'node:stream';
|
|
2
4
|
|
|
3
5
|
declare const RUNTIME_PATH = "/__vs_inspector__.js";
|
|
4
6
|
declare const SCRIPT_TAG = "<script src=\"/__vs_inspector__.js\" defer></script>";
|
|
@@ -6,4 +8,64 @@ declare function injectScript(html: string): string;
|
|
|
6
8
|
declare function isReady(): boolean;
|
|
7
9
|
declare function installInspector(app: Express): void;
|
|
8
10
|
|
|
9
|
-
|
|
11
|
+
/** dev 凭据 env 名(box 注入;本地缺省 = classic 模式) */
|
|
12
|
+
declare const DEV_TOKEN_ENV = "TBOX_DEV_TOKEN";
|
|
13
|
+
/** query/cookie 凭据参数名(box 302 盖戳与应用侧判定共用常量) */
|
|
14
|
+
declare const DEV_TOKEN_NAME = "tbox_dev_token";
|
|
15
|
+
/** 构建通知 SSE 端点(static 面刷新通道;跨仓常量,不得改名) */
|
|
16
|
+
declare const DEV_SSE_PATH = "/__tbox_dev_hot_reload";
|
|
17
|
+
type DevFace = "dev" | "static";
|
|
18
|
+
/** env 解析三态:classic(缺席/空);protected+token(合规);protected 无 token(形状不合规 → fail-closed 全 static) */
|
|
19
|
+
type DevTokenResolution = {
|
|
20
|
+
mode: "classic";
|
|
21
|
+
} | {
|
|
22
|
+
mode: "protected";
|
|
23
|
+
token?: string;
|
|
24
|
+
};
|
|
25
|
+
interface DevRuntimeLogger {
|
|
26
|
+
debug(msg: string, ctx?: Record<string, unknown>): void;
|
|
27
|
+
info(msg: string, ctx?: Record<string, unknown>): void;
|
|
28
|
+
warn(msg: string, ctx?: Record<string, unknown>): void;
|
|
29
|
+
}
|
|
30
|
+
interface DevRuntimeOptions {
|
|
31
|
+
/** vite 能力面(structural 注入——本文件零 vite import) */
|
|
32
|
+
vite: {
|
|
33
|
+
middlewares: RequestHandler;
|
|
34
|
+
transformIndexHtml: (url: string, html: string) => Promise<string>;
|
|
35
|
+
};
|
|
36
|
+
/** 模板创建的 HMR WS hub(永不 listen 的纯事件载体;runtime 仅 emit('upgrade')) */
|
|
37
|
+
hmrHub: Server;
|
|
38
|
+
/** HMR 认领路径(模板从 posix.join(vite.config.base, '/__vite_hmr') 派生传入——恒等无漂移) */
|
|
39
|
+
hmrPath: string;
|
|
40
|
+
/** env 解析结果(createTboxDevRuntime 前经 resolveDevTokenFromEnv 求值) */
|
|
41
|
+
tokenState: DevTokenResolution;
|
|
42
|
+
/** client 源根(dev HTML 源) */
|
|
43
|
+
clientRoot: string;
|
|
44
|
+
/** client 构建产物目录(static 面根) */
|
|
45
|
+
clientDist: string;
|
|
46
|
+
/** SPA fallback 排除前缀(业务 straggler parity;agent/support = ['/api','/ws'],h5 = ['/api']) */
|
|
47
|
+
spaExcludePrefixes: readonly string[];
|
|
48
|
+
/** HTML 收尾钩子(runtime 注入先行、钩子后行;模板用于 inspector injectScript) */
|
|
49
|
+
decorateHtml?: (html: string, face: DevFace) => string;
|
|
50
|
+
/** 日志(缺省 no-op;模板传 createLogger 实例,TBOX_LOG_LEVEL=debug 开 debug 族) */
|
|
51
|
+
logger?: DevRuntimeLogger;
|
|
52
|
+
/** 纯观测标记:模板是否收窄 fs.allow(仅进 dev_guard_mode 启动日志) */
|
|
53
|
+
fsAllowNarrowed?: boolean;
|
|
54
|
+
/** SSE 心跳间隔 ms(默认 15000;smoke 经 TBOX_DEV_SSE_KEEPALIVE_MS 覆盖) */
|
|
55
|
+
sseKeepaliveMs?: number;
|
|
56
|
+
}
|
|
57
|
+
interface DevRuntime {
|
|
58
|
+
/** pathless 挂载:app.use(runtime.gate())——SSE 端点 + 面裁决 */
|
|
59
|
+
gate: RequestHandler;
|
|
60
|
+
/** pathless 挂载:app.use(runtime.final())——HTML 兜底 / dist 静态,位于自由区之后 */
|
|
61
|
+
final: RequestHandler;
|
|
62
|
+
/** 唯一 WS 入口:返回 true = 已认领(含 401 拒绝),false = 回落业务升级路由 */
|
|
63
|
+
handleUpgrade: (req: IncomingMessage, socket: Duplex, head: Buffer) => boolean;
|
|
64
|
+
/** watch 构建完成回调(模板 BUNDLE_END 时调用 → SSE 广播 → static 面刷新) */
|
|
65
|
+
notifyBuildEnd: () => void;
|
|
66
|
+
}
|
|
67
|
+
/** env 三态解析:缺席/空串 → classic;形状合规 → protected+token;在场不合规 → protected 无 token(fail-closed) */
|
|
68
|
+
declare function resolveDevTokenFromEnv(env: NodeJS.ProcessEnv): DevTokenResolution;
|
|
69
|
+
declare function createTboxDevRuntime(opts: DevRuntimeOptions): DevRuntime;
|
|
70
|
+
|
|
71
|
+
export { DEV_SSE_PATH, DEV_TOKEN_ENV, DEV_TOKEN_NAME, type DevFace, type DevRuntime, type DevRuntimeLogger, type DevRuntimeOptions, type DevTokenResolution, RUNTIME_PATH, SCRIPT_TAG, createTboxDevRuntime, injectScript, installInspector, isReady, resolveDevTokenFromEnv };
|
package/dist/platform/index.js
CHANGED
|
@@ -1 +1,11 @@
|
|
|
1
|
-
var
|
|
1
|
+
var j="https://env-00jx4e7pq1un-static.normal.cloudstatic.cn/asset/codingbox/inspector.umd.js",y="/__vs_inspector__.js",b=`<script src="${y}" defer></script>`,x="",w=!1;async function A(e=3){for(let o=0;o<e;o++)try{let n=await fetch(j);if(!n.ok)throw new Error(`HTTP ${n.status}`);x=await n.text(),w=!0,console.log(`[inspector] runtime loaded (${x.length} bytes)`);return}catch(n){console.warn(`[inspector] fetch failed (attempt ${o+1}/${e}):`,n.message),o<e-1&&await new Promise(s=>setTimeout(s,1e3*(o+1)))}console.error("[inspector] runtime unavailable; inspector script will be skipped")}function D(e){if(e.includes(y))return e;let o=e.search(/<\/head\s*>/i);if(o!==-1)return e.slice(0,o)+b+e.slice(o);let n=e.search(/<body[\s>]/i);return n!==-1?e.slice(0,n)+b+e.slice(n):e}function L(){return w}function W(e){A(),e.get(y,(o,n)=>{if(!x){n.status(503).type("application/javascript").send("// inspector runtime not ready");return}n.type("application/javascript").set("Cache-Control","no-cache").send(x)}),e.use((o,n,s)=>{if(!w)return s();let i=[],l=n.write.bind(n),u=n.end.bind(n),m=!1,v=()=>{let c=String(n.getHeader("content-type")||""),p=String(n.getHeader("content-encoding")||"");return c.includes("text/html")&&!p};n.write=((c,...p)=>(!m&&!i.length&&(m=v()),m&&c?(i.push(Buffer.isBuffer(c)?c:Buffer.from(c)),!0):l(c,...p))),n.end=((c,...p)=>{if(!m&&!i.length&&(m=v()),m){c&&i.push(Buffer.isBuffer(c)?c:Buffer.from(c));try{let g=Buffer.concat(i).toString("utf8"),_=D(g);return n.setHeader("Content-Length",Buffer.byteLength(_)),u(_,...p)}catch(g){return console.warn("[inspector] inject failed, fallback to original:",g.message),u(Buffer.concat(i),...p)}}return u(c,...p)}),s()})}import{createHash as k,timingSafeEqual as M}from"crypto";import{readFile as C}from"fs/promises";import $ from"express";import O from"path";var N="TBOX_DEV_TOKEN",h="tbox_dev_token",T="/__tbox_dev_hot_reload",S=/^[A-Za-z0-9_-]{20,128}$/,U={debug(){},info(){},warn(){}};function V(e){let o=e[N];return o===void 0||o===""?{mode:"classic"}:S.test(o)?{mode:"protected",token:o}:{mode:"protected",token:void 0}}function E(e,o){if(!e||!o||!S.test(e)||!S.test(o))return!1;let n=k("sha256").update(e).digest(),s=k("sha256").update(o).digest();return M(n,s)}function I(e){try{return new URL(e,"http://tbox.local").searchParams.get(h)??void 0}catch{return}}function K(e){if(e)for(let o of e.split(";")){let n=o.trim();if(n.startsWith(`${h}=`))return n.slice(h.length+1)}}function G(e,o){if(o===void 0)return{face:"static",credSource:"none",reason:"no-cred"};let n=I(e.url??"/"),s=K(e.headers.cookie),i="none";if(n!==void 0&&E(n,o)?i="query":s!==void 0&&E(s,o)?i="cookie":(n!==void 0||s!==void 0)&&(i="invalid"),i!=="query"&&i!=="cookie")return{face:"static",credSource:i,reason:"no-cred"};let l=e.headers["sec-fetch-site"],u=e.headers["sec-fetch-mode"];return u==="navigate"?{face:"dev",credSource:i,reason:"navigate"}:l==="same-origin"||l==="none"?{face:"dev",credSource:i,reason:"same-origin"}:l===void 0&&u===void 0?{face:"dev",credSource:i,reason:"no-sec-fetch-header"}:{face:"static",credSource:i,reason:"cross-site-subresource"}}function P(e,o){let n=/<head[^>]*>/i.exec(e);if(!n)return e;let s=n.index+n[0].length;return e.slice(0,s)+o+e.slice(s)}function J(e,o){return o.some(n=>e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))}function z(e){return`<script>window.__TBOX_DEV_TOKEN__='${e}';(function(){var OW=window.WebSocket;function PW(url,protocols){if(typeof url==='string'&&url.indexOf('/__vite_hmr')!==-1){url+=(url.indexOf('?')===-1?'?':'&')+'${h}='+encodeURIComponent(window.__TBOX_DEV_TOKEN__);}return protocols===undefined?new OW(url):new OW(url,protocols);}PW.prototype=OW.prototype;Object.setPrototypeOf(PW,OW);window.WebSocket=PW;})();</script>`}var X=`<script>(function(){var es=new EventSource('${T}');var last=null;es.onmessage=function(e){try{var id=JSON.parse(e.data).buildId;if(last===null){last=id;return;}if(id!==last){location.reload();}last=id;}catch(err){}};})();</script>`;function Q(e){let o=e.logger??U,n=Symbol("tboxDevFace"),s=e.tokenState.mode==="classic",i=e.tokenState.mode==="protected"?e.tokenState.token:void 0,l=0,u=new Set,m=e.sseKeepaliveMs??15e3,v=$.static(e.clientDist,{index:!1,fallthrough:!0}),c=new Set;o.info("dev_guard_mode",{mode:e.tokenState.mode,tokenShapeOk:e.tokenState.mode==="protected"&&i!==void 0,fsAllowNarrowed:e.fsAllowNarrowed===!0});function p(t){t.setHeader("Content-Type","text/event-stream; charset=utf-8"),t.setHeader("Cache-Control","no-store"),t.setHeader("X-Accel-Buffering","no"),t.flushHeaders(),t.write(`data: ${JSON.stringify({buildId:l})}
|
|
2
|
+
|
|
3
|
+
`),u.add(t);let r=setInterval(()=>{t.destroyed||t.write(`: keepalive
|
|
4
|
+
|
|
5
|
+
`)},m);t.on("close",()=>{clearInterval(r),u.delete(t),o.debug("dev_sse_close",{subscriberCount:u.size})}),o.debug("dev_sse_conn",{subscriberCount:u.size})}let g=(t,r,f)=>{if(s){e.vite.middlewares(t,r,f);return}if(t.method==="GET"&&t.path===T){p(r);return}let d=G(t,i);t[n]=d.face,o.debug("dev_face_decision",{face:d.face,credSource:d.credSource,reason:d.reason,method:t.method,pathname:t.path,secFetchSite:t.headers["sec-fetch-site"]??null,secFetchMode:t.headers["sec-fetch-mode"]??null,requestId:t.headers["x-request-id"]??null,reqIdSource:"header"}),d.face==="dev"?e.vite.middlewares(t,r,f):f()},_=(t,r,f)=>{F(t,r,f)};async function F(t,r,f){if(J(t.path??"/",e.spaExcludePrefixes)){f();return}let d=s?"classic":t[n]??"static";if(d!=="static"){try{let a=await C(O.join(e.clientRoot,"index.html"),"utf-8");a=await e.vite.transformIndexHtml(t.originalUrl??"/",a),d==="dev"&&(a=P(a,z(i))),a=e.decorateHtml?e.decorateHtml(a,"dev"):a,r.statusCode=200,r.setHeader("Content-Type","text/html; charset=utf-8"),d==="dev"&&r.setHeader("Cache-Control","no-store"),r.end(a),c.has("dev")||(c.add("dev"),o.info("dev_html_face",{face:"dev",pathname:t.path,source:"clientRoot"}))}catch(a){f(a)}return}v(t,r,()=>{if(!(/text\/html/.test(String(t.headers.accept??""))||t.method==="HEAD")){r.statusCode=404,r.setHeader("Cache-Control","no-store"),r.end("Not Found");return}C(O.join(e.clientDist,"index.html"),"utf-8").then(R=>{let H=P(R,X),B=e.decorateHtml?e.decorateHtml(H,"static"):H;r.statusCode=200,r.setHeader("Content-Type","text/html; charset=utf-8"),r.setHeader("Cache-Control","no-store"),r.end(B),o.debug("dev_spa_fallback_hit",{face:"static",pathname:t.path,acceptHtml:!0,distReady:!0})}).catch(()=>{r.statusCode=404,r.setHeader("Cache-Control","no-store"),r.end("Not Found"),o.debug("dev_spa_fallback_hit",{face:"static",pathname:t.path,acceptHtml:!0,distReady:!1})})})}return{gate:g,final:_,handleUpgrade:(t,r,f)=>{let d;try{d=new URL(t.url||"/","http://localhost").pathname}catch{return!1}if(d!==e.hmrPath)return!1;let a=t.headers["sec-websocket-protocol"];if(!a)t.headers["sec-websocket-protocol"]="vite-hmr";else if(a!=="vite-hmr"&&a!=="vite-ping")return!1;if(!s){let R=I(t.url??"/");if(i===void 0||!E(R,i))return r.write(`HTTP/1.1 401 Unauthorized\r
|
|
6
|
+
Connection: close\r
|
|
7
|
+
Content-Length: 0\r
|
|
8
|
+
\r
|
|
9
|
+
`),r.end(()=>{r.destroyed||r.destroy()}),o.info("dev_hmr_upgrade",{outcome:"rejected-401",pathname:d,protocol:t.headers["sec-websocket-protocol"]}),!0}return e.hmrHub.emit("upgrade",t,r,f),o.info("dev_hmr_upgrade",{outcome:"claimed",pathname:d,protocol:t.headers["sec-websocket-protocol"]}),!0},notifyBuildEnd:()=>{l+=1;for(let t of u)t.destroyed||t.write(`data: ${JSON.stringify({buildId:l})}
|
|
10
|
+
|
|
11
|
+
`);o.info("dev_build_end",{buildId:l})}}}export{T as DEV_SSE_PATH,N as DEV_TOKEN_ENV,h as DEV_TOKEN_NAME,y as RUNTIME_PATH,b as SCRIPT_TAG,Q as createTboxDevRuntime,D as injectScript,W as installInspector,L as isReady,V as resolveDevTokenFromEnv};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tbox.cn/app-sdk-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.22.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"tbox-inspector-check": "bin/check-inspector.mjs"
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"express": "4.22.2",
|
|
40
40
|
"jose": "6.2.8",
|
|
41
41
|
"zod": "3.25.76",
|
|
42
|
-
"@tbox.cn/app-toolkit": "0.7.
|
|
42
|
+
"@tbox.cn/app-toolkit": "0.7.3"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
45
|
"@mastra/core": "1.59.0",
|
|
@@ -51,8 +51,8 @@
|
|
|
51
51
|
"tsup": "8.5.1",
|
|
52
52
|
"typescript": "5.9.3",
|
|
53
53
|
"vitest": "4.1.10",
|
|
54
|
-
"@tbox.cn/app-sdk-
|
|
55
|
-
"@tbox.cn/app-
|
|
54
|
+
"@tbox.cn/app-agent-sdk-server": "0.1.6",
|
|
55
|
+
"@tbox.cn/app-sdk-client": "0.21.1"
|
|
56
56
|
},
|
|
57
57
|
"license": "MIT",
|
|
58
58
|
"scripts": {
|