@tbox.cn/app-sdk-client 0.21.4 → 1.0.0-alpha.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 +1 -1
- package/dist/app/index.d.ts +34 -0
- package/dist/app/index.js +1 -0
- package/dist/app-module-dEGAU6l2.d.ts +102 -0
- package/dist/chunk-DXL2GZRD.js +1 -0
- package/dist/client/index.d.ts +42 -91
- package/dist/client/index.js +1 -1
- package/package.json +8 -4
package/README.md
CHANGED
|
@@ -6,4 +6,4 @@ chat 引擎、状态域(zustand)、桥协议 v2、WS 客户端(keepalive /
|
|
|
6
6
|
真实外部依赖仅 react + react-dom + zustand(+ core/contracts)——client 树零 Node 内建、零 server 重依赖
|
|
7
7
|
(2026-09 三包拆分;浏览器直连 o.tbox.cn 的能力已全部收口为同源代理)。
|
|
8
8
|
|
|
9
|
-
公开入口:`.` / `./client` / `./
|
|
9
|
+
公开入口:`.` / `./client` / `./app`(startApp 启动层)/ `./platform/code-inspect`(vite 页面微调 babel plugin)。
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { ComponentType, ReactNode } from 'react';
|
|
2
|
+
import { CardComponent } from '@tbox.cn/app-contracts';
|
|
3
|
+
import { A as AppClientModule } from '../app-module-dEGAU6l2.js';
|
|
4
|
+
|
|
5
|
+
interface AppConfig {
|
|
6
|
+
/** API base;对应 VITE_API_URL。空串 = 同源。SDK 零 Vite 依赖,由组装端读取后传入。 */
|
|
7
|
+
apiBaseUrl?: string;
|
|
8
|
+
/** 渲染前钩子(主题、chat 配置快照等);抛错 → 统一启动失败兜底。 */
|
|
9
|
+
setup?: () => void | Promise<void>;
|
|
10
|
+
/** 默认 true;false 关闭 ErrorBoundary(应用自带边界时)。 */
|
|
11
|
+
errorBoundary?: boolean;
|
|
12
|
+
}
|
|
13
|
+
interface StartAppOptions {
|
|
14
|
+
config?: AppConfig;
|
|
15
|
+
/** 页面加载器;生成 entry 用动态 import 保留按路由 chunk。 */
|
|
16
|
+
page: () => Promise<{
|
|
17
|
+
default: ComponentType;
|
|
18
|
+
}>;
|
|
19
|
+
/** 客户端模块;startApp 统一注册。 */
|
|
20
|
+
modules?: readonly AppClientModule[];
|
|
21
|
+
/** 应用级卡片;startApp 统一注册。 */
|
|
22
|
+
cards?: Record<string, CardComponent>;
|
|
23
|
+
/** 通用包装钩子;agent 层用它注入 AgentAppShell。 */
|
|
24
|
+
wrap?: (page: ReactNode) => ReactNode;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* 客户端通用启动层(单一装配入口)。
|
|
28
|
+
*
|
|
29
|
+
* 固定执行序:runtime → 全局错误上报 → URL 参数日志 → config.setup →
|
|
30
|
+
* 注册卡片/模块 → 加载页面 → 渲染。幂等;启动失败渲染可见兜底。
|
|
31
|
+
*/
|
|
32
|
+
declare function startApp(options: StartAppOptions): Promise<void>;
|
|
33
|
+
|
|
34
|
+
export { type AppConfig, type StartAppOptions, startApp };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as s,e as l,f as c,s as p,t as d}from"../chunk-DXL2GZRD.js";import{StrictMode as h}from"react";import{createRoot as m}from"react-dom/client";import{createLogger as w}from"@tbox.cn/app-sdk-core";import{jsx as t,jsxs as S}from"react/jsx-runtime";var a=w("APP"),f=!1,i=null;function g(){return typeof document>"u"?null:document.getElementById("root")}function C(r){let e=g();if(e)try{i??=m(e),i.render(t(y,{message:r}))}catch(o){a.error("render startup fallback failed:",o)}}function y({message:r}){return S("main",{style:{padding:24,fontFamily:"system-ui, sans-serif"},children:[t("h1",{style:{fontSize:18},children:"页面暂时不可用"}),t("p",{style:{color:"#666"},children:r}),t("button",{type:"button",onClick:()=>window.location.reload(),children:"重新加载"})]})}var R=/^(code|token|auth_code|visitortoken|session)$/i;function u(r){let e={};return new URLSearchParams(r).forEach((o,n)=>{e[n]=R.test(n)?`${o.slice(0,6)}…(len=${o.length})`:o}),e}function A(){if(typeof window>"u")return;let r=window.location.hash.includes("?")?window.location.hash.slice(window.location.hash.indexOf("?")+1):"";a.info(`url params: ${JSON.stringify({search:u(window.location.search),hash:u(r)})}`)}async function U(r){if(f){a.warn("startApp 重复调用(已启动,忽略)");return}f=!0;try{c({apiBaseUrl:r.config?.apiBaseUrl}),s(),A(),await r.config?.setup?.(),p(r.cards),await d(r.modules??[]);let{default:e}=await r.page(),o=g();if(!o){a.error("未找到 #root,跳过挂载");return}i??=m(o);let n=r.wrap?r.wrap(t(e,{})):t(e,{});i.render(t(h,{children:r.config?.errorBoundary===!1?n:t(l,{fallback:t(y,{message:"页面渲染失败,请刷新重试"}),children:n})}))}catch(e){a.error("startup failed:",e),C(e instanceof Error?e.message:String(e))}}export{U as startApp};
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { CardComponent, TboxCardPayload, ClientSlotId, ClientSlotValueMap } from '@tbox.cn/app-contracts';
|
|
2
|
+
|
|
3
|
+
/** 内联流过滤器(域注册;复合序 = 注册序) */
|
|
4
|
+
type InlineCardFilter = (cards: readonly TboxCardPayload[]) => TboxCardPayload[];
|
|
5
|
+
/**
|
|
6
|
+
* ClientCardRegistry:客户端卡片组件注册表(cardType → CardComponent,无状态)。
|
|
7
|
+
* 模块在 clientModule.register(ctx) 内 ctx.cards.registerMap(map) 注册组件。
|
|
8
|
+
* 与 server 端 CardRegistry 对称:server 注册数据契约(CardMeta),client 注册渲染组件。
|
|
9
|
+
*
|
|
10
|
+
* 三通道(单一模板统一化):
|
|
11
|
+
* - 原始注册(registerMap):模块自有卡组件(RawCardRenderer 消费面);
|
|
12
|
+
* - 覆盖注册(registerOverride):聊天视图组合层覆盖(同 cardType 包装/替换——原始视图不受影响,
|
|
13
|
+
* 域模块包自持防嵌套语义,如 mall-core 包装 alipay-activity 的联单卡);
|
|
14
|
+
* - 内联过滤(registerInlineFilter):域声明哪些卡不进内联流(由域浮层自持;多域按注册序复合)。
|
|
15
|
+
* 应用组装端读取:`{...ctx.cards.getAll(), ...ctx.cards.getOverrides()}` 为聊天视图注册表;
|
|
16
|
+
* `ctx.cards.applyInlineFilters` 为 ChatPage filterInlineCards 注入值。
|
|
17
|
+
*/
|
|
18
|
+
declare class ClientCardRegistry {
|
|
19
|
+
private cards;
|
|
20
|
+
private overrides;
|
|
21
|
+
private inlineFilters;
|
|
22
|
+
register(cardType: string, component: CardComponent): void;
|
|
23
|
+
/**
|
|
24
|
+
* 按 map 批量注册(模块 clientModule.cards 形态;key 即 cardType)。
|
|
25
|
+
* 幂等:重复注册同一 cardType 告警并覆盖(组装端多次 registerAll 安全)。
|
|
26
|
+
*/
|
|
27
|
+
registerMap(map: Record<string, CardComponent>): void;
|
|
28
|
+
/**
|
|
29
|
+
* 聊天视图覆盖注册(组合层):同 cardType 覆盖原始注册在聊天流的渲染;
|
|
30
|
+
* 原始注册不受影响(RawCardRenderer/详情弹层仍取原始形态)。
|
|
31
|
+
* 幂等:重复覆盖告警并覆盖(组装端多次 registerAll 安全)。
|
|
32
|
+
*/
|
|
33
|
+
registerOverride(cardType: string, component: CardComponent): void;
|
|
34
|
+
getOverrides(): Record<string, CardComponent>;
|
|
35
|
+
/** 内联流过滤注册(域浮层自持卡的剥离声明;复合序 = 注册序)。 */
|
|
36
|
+
registerInlineFilter(filter: InlineCardFilter): void;
|
|
37
|
+
/** 内联流过滤复合(无注册 → 恒等返回原数组引用)。 */
|
|
38
|
+
applyInlineFilters(cards: readonly TboxCardPayload[]): TboxCardPayload[];
|
|
39
|
+
resolve(cardType: string): CardComponent | undefined;
|
|
40
|
+
getAll(): Record<string, CardComponent>;
|
|
41
|
+
has(cardType: string): boolean;
|
|
42
|
+
get size(): number;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* ClientSlotRegistry:客户端槽位注册表(slotId → 槽值,无状态)。
|
|
46
|
+
* 模块在 clientModule.register(ctx) 内注册(如 mall-core `ctx.slots.register('home', render)`);
|
|
47
|
+
* kit 壳按槽存在性派生应用形态(home 注册 = home-first 主屏;缺席 = chat 流)。
|
|
48
|
+
* 槽 id 词汇 = TIER0 contracts KNOWN_CLIENT_SLOT_IDS(封闭集);未知 id =
|
|
49
|
+
* 版本偏斜信号:warn + 照常注册(前向兼容——老壳消费新模块不炸,resolve 侧自然 miss 降级)。
|
|
50
|
+
*/
|
|
51
|
+
declare class ClientSlotRegistry {
|
|
52
|
+
private slots;
|
|
53
|
+
register<K extends ClientSlotId>(slotId: K, value: ClientSlotValueMap[K]): void;
|
|
54
|
+
resolve<K extends ClientSlotId>(slotId: K): ClientSlotValueMap[K] | undefined;
|
|
55
|
+
has(slotId: ClientSlotId): boolean;
|
|
56
|
+
get size(): number;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* ClientContext:模块 clientModule.register(ctx) 的上下文(组装端 createClientContext() 创建一次)。
|
|
60
|
+
* cards = 卡片组件注册表;slots = 壳渲染槽注册表(单一模板统一化 :应用形态派生位)。
|
|
61
|
+
*/
|
|
62
|
+
interface ClientContext {
|
|
63
|
+
/** 卡片组件注册表(cardType → CardComponent) */
|
|
64
|
+
cards: ClientCardRegistry;
|
|
65
|
+
/** 壳渲染槽注册表(槽 id 契约 = KNOWN_CLIENT_SLOT_IDS) */
|
|
66
|
+
slots: ClientSlotRegistry;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* 模块描述对象(客户端):模块包 client 入口 export 的 clientModule。
|
|
70
|
+
*
|
|
71
|
+
* - cards:卡片组件声明 map(key 约定 = cardType;数据 + 类型源,
|
|
72
|
+
* 供 `InferModuleCards` 从装配数组自动推导 app 端 CardType)。
|
|
73
|
+
* - register(ctx):注册期自注册(一期仅 ctx.cards.registerMap(cards))。
|
|
74
|
+
*
|
|
75
|
+
* 与服务端 `ServerModule` 逐行对称;组装端遍历 modules 调 register(ctx)。
|
|
76
|
+
* register 为函数签名声明:method shorthand 经 `satisfies` 检查(TS 方法 bivariance——
|
|
77
|
+
* 放行比契约更窄的参数,运行时无危害;缺字段的过宽参数会被拦截)。
|
|
78
|
+
* cards 为必填属性:无卡片模块写 `cards: {}`(keyof = never,不污染装配类型)。
|
|
79
|
+
*/
|
|
80
|
+
interface ClientModule<C extends Record<string, CardComponent> = Record<string, CardComponent>> {
|
|
81
|
+
cards: C;
|
|
82
|
+
register: (ctx: ClientContext) => void | Promise<void>;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* 创建客户端上下文(组装端调用一次,apps/client 模块加载期)。
|
|
86
|
+
*/
|
|
87
|
+
declare function createClientContext(): ClientContext;
|
|
88
|
+
|
|
89
|
+
interface AppClientModule {
|
|
90
|
+
cards?: Record<string, CardComponent>;
|
|
91
|
+
register: (ctx: ClientContext) => void | Promise<void>;
|
|
92
|
+
}
|
|
93
|
+
declare function getClientContext(): ClientContext;
|
|
94
|
+
declare function registerClientCards(cards: Record<string, CardComponent> | undefined): void;
|
|
95
|
+
/**
|
|
96
|
+
* 注册全部客户端模块。promise 锁而非布尔锁:并发页面 entry 必须等同一次完成,
|
|
97
|
+
* 失败时释放锁允许下一轮(HMR/重试)重新注册。
|
|
98
|
+
*/
|
|
99
|
+
declare function registerClientModules(modules: readonly AppClientModule[]): Promise<void>;
|
|
100
|
+
declare function getRegisteredClientCards(): Record<string, CardComponent>;
|
|
101
|
+
|
|
102
|
+
export { type AppClientModule as A, ClientCardRegistry as C, type ClientContext as a, type ClientModule as b, ClientSlotRegistry as c, createClientContext as d, getRegisteredClientCards as e, registerClientModules as f, getClientContext as g, registerClientCards as r };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createCoreLogger as S,resolveLevel as x,setLogContextProvider as I}from"@tbox.cn/app-sdk-core";var l=null;I(()=>l??void 0);function _(t){l=t?{requestId:t.runId,conversationId:t.conversationId}:null}function M(){try{if(typeof localStorage<"u")return x(localStorage.getItem("tbox:logLevel")??void 0,"info")}catch{}try{if(typeof location<"u"){let t=new URLSearchParams(location.search).get("logLevel");if(t)return x(t,"info")}}catch{}return"info"}function i(t){return S({tag:t,getLevel:M,getContext:()=>l??void 0})}var w;function j(t){w=t}function D(t){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t??i("GLOBAL"),r=new Map,o=1e4,C=n=>{let s=Date.now();for(let[R,E]of r)s-E>=o&&r.delete(R);r.has(n)||(r.set(n,s),e.error(n),w?.send("error",n))},f=n=>{C(`uncaught: ${n.message} @ ${n.filename}:${n.lineno}`)},m=n=>{let s=n.reason instanceof Error?n.reason.message:String(n.reason);C(`unhandledrejection: ${s}`)};return window.addEventListener("error",f),window.addEventListener("unhandledrejection",m),()=>{window.removeEventListener("error",f),window.removeEventListener("unhandledrejection",m)}}import{Component as P}from"react";var T=i("ErrorBoundary"),h=class extends P{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e){T.error("render error:",e)}render(){return this.state.hasError?this.props.fallback:this.props.children}};var v="";function V(t){v=(t.apiBaseUrl??"").trim().replace(/\/$/,"")}function O(){return v}function $(){let t=O();return t||(typeof window<"u"?`${window.location.protocol}//${window.location.host}`:"")}function Q(t="/ws"){return $().replace(/^http/,"ws")+t}var c=null;function k(){if(c)return c;let t={};return typeof window<"u"&&new URLSearchParams(window.location.search).forEach((r,o)=>{t[o]=r}),c=t,t}function F(t){return k()[t]}function N(){let t=F("container");return t==="alipay-miniapp"||t==="alipay"}function G(){if(typeof window>"u")return!1;let t=window.my;return!!(t&&typeof t.postMessage=="function")}function q(){return N()?"alipay-miniapp":"browser"}import{KNOWN_CLIENT_SLOT_IDS as A}from"@tbox.cn/app-contracts";var a=i("ClientCardRegistry"),y=i("ClientSlotRegistry"),p=class{cards=new Map;overrides=new Map;inlineFilters=[];register(e,r){if(!e){a.warn("register without cardType skipped");return}this.cards.has(e)&&a.warn(`overwriting existing cardType: ${e}`),this.cards.set(e,r)}registerMap(e){for(let[r,o]of Object.entries(e))this.register(r,o)}registerOverride(e,r){if(!e){a.warn("registerOverride without cardType skipped");return}this.overrides.has(e)&&a.warn(`overwriting existing override: ${e}`),this.overrides.set(e,r)}getOverrides(){return Object.fromEntries(this.overrides)}registerInlineFilter(e){this.inlineFilters.push(e)}applyInlineFilters(e){return this.inlineFilters.length===0?[...e]:this.inlineFilters.reduce((r,o)=>o(r),[...e])}resolve(e){return this.cards.get(e)}getAll(){return Object.fromEntries(this.cards)}has(e){return this.cards.has(e)}get size(){return this.cards.size}},u=class{slots=new Map;register(e,r){A.includes(e)||y.warn(`unknown slot id: ${e}(KNOWN_CLIENT_SLOT_IDS 未含——版本偏斜?照常注册)`),this.slots.has(e)&&y.warn(`overwriting existing slot: ${e}`),this.slots.set(e,r)}resolve(e){return this.slots.get(e)}has(e){return this.slots.has(e)}get size(){return this.slots.size}};function L(){return{cards:new p,slots:new u}}var b,g;function d(){return b??=L(),b}function ee(t){t&&d().cards.registerMap(t)}function te(t){return g??=(async()=>{for(let e of t)e.cards&&d().cards.registerMap(e.cards),await e.register(d())})().catch(e=>{throw g=void 0,e}),g}function re(){return d().cards.getAll()}export{_ as a,i as b,j as c,D as d,h as e,V as f,O as g,$ as h,Q as i,k as j,F as k,N as l,G as m,q as n,p as o,u as p,L as q,d as r,ee as s,te as t,re as u};
|
package/dist/client/index.d.ts
CHANGED
|
@@ -2,7 +2,8 @@ import { TboxLogger } from '@tbox.cn/app-sdk-core';
|
|
|
2
2
|
export { InferModuleCards, LogContext, LogLevel, TboxLogger, createLogger, detailForLog, sanitizeForLog, truncateForLog } from '@tbox.cn/app-sdk-core';
|
|
3
3
|
import * as React from 'react';
|
|
4
4
|
import React__default, { ReactNode, CSSProperties, Component } from 'react';
|
|
5
|
-
import { TboxCardPayload, CardComponent, UiAction
|
|
5
|
+
import { TboxCardPayload, CardComponent, UiAction } from '@tbox.cn/app-contracts';
|
|
6
|
+
export { A as AppClientModule, C as ClientCardRegistry, a as ClientContext, b as ClientModule, c as ClientSlotRegistry, d as createClientContext, g as getClientContext, e as getRegisteredClientCards, r as registerClientCards, f as registerClientModules } from '../app-module-dEGAU6l2.js';
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* 客户端日志壳:client run 上下文(req/conv 尾缀)+ 全局错误兜底 + transport 扩展点(上报预留)。
|
|
@@ -247,92 +248,6 @@ declare function closePlateKeyboard(): Promise<{
|
|
|
247
248
|
closed: boolean;
|
|
248
249
|
}>;
|
|
249
250
|
|
|
250
|
-
/** 内联流过滤器(域注册;复合序 = 注册序) */
|
|
251
|
-
type InlineCardFilter = (cards: readonly TboxCardPayload[]) => TboxCardPayload[];
|
|
252
|
-
/**
|
|
253
|
-
* ClientCardRegistry:客户端卡片组件注册表(cardType → CardComponent,无状态)。
|
|
254
|
-
* 模块在 clientModule.register(ctx) 内 ctx.cards.registerMap(map) 注册组件。
|
|
255
|
-
* 与 server 端 CardRegistry 对称:server 注册数据契约(CardMeta),client 注册渲染组件。
|
|
256
|
-
*
|
|
257
|
-
* 三通道(单一模板统一化):
|
|
258
|
-
* - 原始注册(registerMap):模块自有卡组件(RawCardRenderer 消费面);
|
|
259
|
-
* - 覆盖注册(registerOverride):聊天视图组合层覆盖(同 cardType 包装/替换——原始视图不受影响,
|
|
260
|
-
* 域模块包自持防嵌套语义,如 mall-core 包装 alipay-activity 的联单卡);
|
|
261
|
-
* - 内联过滤(registerInlineFilter):域声明哪些卡不进内联流(由域浮层自持;多域按注册序复合)。
|
|
262
|
-
* 应用组装端读取:`{...ctx.cards.getAll(), ...ctx.cards.getOverrides()}` 为聊天视图注册表;
|
|
263
|
-
* `ctx.cards.applyInlineFilters` 为 ChatPage filterInlineCards 注入值。
|
|
264
|
-
*/
|
|
265
|
-
declare class ClientCardRegistry {
|
|
266
|
-
private cards;
|
|
267
|
-
private overrides;
|
|
268
|
-
private inlineFilters;
|
|
269
|
-
register(cardType: string, component: CardComponent): void;
|
|
270
|
-
/**
|
|
271
|
-
* 按 map 批量注册(模块 clientModule.cards 形态;key 即 cardType)。
|
|
272
|
-
* 幂等:重复注册同一 cardType 告警并覆盖(组装端多次 registerAll 安全)。
|
|
273
|
-
*/
|
|
274
|
-
registerMap(map: Record<string, CardComponent>): void;
|
|
275
|
-
/**
|
|
276
|
-
* 聊天视图覆盖注册(组合层):同 cardType 覆盖原始注册在聊天流的渲染;
|
|
277
|
-
* 原始注册不受影响(RawCardRenderer/详情弹层仍取原始形态)。
|
|
278
|
-
* 幂等:重复覆盖告警并覆盖(组装端多次 registerAll 安全)。
|
|
279
|
-
*/
|
|
280
|
-
registerOverride(cardType: string, component: CardComponent): void;
|
|
281
|
-
getOverrides(): Record<string, CardComponent>;
|
|
282
|
-
/** 内联流过滤注册(域浮层自持卡的剥离声明;复合序 = 注册序)。 */
|
|
283
|
-
registerInlineFilter(filter: InlineCardFilter): void;
|
|
284
|
-
/** 内联流过滤复合(无注册 → 恒等返回原数组引用)。 */
|
|
285
|
-
applyInlineFilters(cards: readonly TboxCardPayload[]): TboxCardPayload[];
|
|
286
|
-
resolve(cardType: string): CardComponent | undefined;
|
|
287
|
-
getAll(): Record<string, CardComponent>;
|
|
288
|
-
has(cardType: string): boolean;
|
|
289
|
-
get size(): number;
|
|
290
|
-
}
|
|
291
|
-
/**
|
|
292
|
-
* ClientSlotRegistry:客户端槽位注册表(slotId → 槽值,无状态)。
|
|
293
|
-
* 模块在 clientModule.register(ctx) 内注册(如 mall-core `ctx.slots.register('home', render)`);
|
|
294
|
-
* kit 壳按槽存在性派生应用形态(home 注册 = home-first 主屏;缺席 = chat 流)。
|
|
295
|
-
* 槽 id 词汇 = TIER0 contracts KNOWN_CLIENT_SLOT_IDS(封闭集);未知 id =
|
|
296
|
-
* 版本偏斜信号:warn + 照常注册(前向兼容——老壳消费新模块不炸,resolve 侧自然 miss 降级)。
|
|
297
|
-
*/
|
|
298
|
-
declare class ClientSlotRegistry {
|
|
299
|
-
private slots;
|
|
300
|
-
register<K extends ClientSlotId>(slotId: K, value: ClientSlotValueMap[K]): void;
|
|
301
|
-
resolve<K extends ClientSlotId>(slotId: K): ClientSlotValueMap[K] | undefined;
|
|
302
|
-
has(slotId: ClientSlotId): boolean;
|
|
303
|
-
get size(): number;
|
|
304
|
-
}
|
|
305
|
-
/**
|
|
306
|
-
* ClientContext:模块 clientModule.register(ctx) 的上下文(组装端 createClientContext() 创建一次)。
|
|
307
|
-
* cards = 卡片组件注册表;slots = 壳渲染槽注册表(单一模板统一化 :应用形态派生位)。
|
|
308
|
-
*/
|
|
309
|
-
interface ClientContext {
|
|
310
|
-
/** 卡片组件注册表(cardType → CardComponent) */
|
|
311
|
-
cards: ClientCardRegistry;
|
|
312
|
-
/** 壳渲染槽注册表(槽 id 契约 = KNOWN_CLIENT_SLOT_IDS) */
|
|
313
|
-
slots: ClientSlotRegistry;
|
|
314
|
-
}
|
|
315
|
-
/**
|
|
316
|
-
* 模块描述对象(客户端):模块包 client 入口 export 的 clientModule。
|
|
317
|
-
*
|
|
318
|
-
* - cards:卡片组件声明 map(key 约定 = cardType;数据 + 类型源,
|
|
319
|
-
* 供 `InferModuleCards` 从装配数组自动推导 app 端 CardType)。
|
|
320
|
-
* - register(ctx):注册期自注册(一期仅 ctx.cards.registerMap(cards))。
|
|
321
|
-
*
|
|
322
|
-
* 与服务端 `ServerModule` 逐行对称;组装端遍历 modules 调 register(ctx)。
|
|
323
|
-
* register 为函数签名声明:method shorthand 经 `satisfies` 检查(TS 方法 bivariance——
|
|
324
|
-
* 放行比契约更窄的参数,运行时无危害;缺字段的过宽参数会被拦截)。
|
|
325
|
-
* cards 为必填属性:无卡片模块写 `cards: {}`(keyof = never,不污染装配类型)。
|
|
326
|
-
*/
|
|
327
|
-
interface ClientModule<C extends Record<string, CardComponent> = Record<string, CardComponent>> {
|
|
328
|
-
cards: C;
|
|
329
|
-
register: (ctx: ClientContext) => void | Promise<void>;
|
|
330
|
-
}
|
|
331
|
-
/**
|
|
332
|
-
* 创建客户端上下文(组装端调用一次,apps/client 模块加载期)。
|
|
333
|
-
*/
|
|
334
|
-
declare function createClientContext(): ClientContext;
|
|
335
|
-
|
|
336
251
|
/**
|
|
337
252
|
* 运行环境识别 + API/WS 地址推导 + 启动参数读取(client 平台轴)。
|
|
338
253
|
*
|
|
@@ -400,14 +315,33 @@ type AlipayNavigation = {
|
|
|
400
315
|
*/
|
|
401
316
|
declare function resolveAlipayNavigation(url: string, hostMiniAppId?: string): AlipayNavigation | undefined;
|
|
402
317
|
|
|
318
|
+
type QueryValue = string | number | boolean | null | undefined;
|
|
319
|
+
type Query = Record<string, QueryValue | QueryValue[]>;
|
|
403
320
|
interface RequestOptions {
|
|
404
|
-
|
|
321
|
+
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
322
|
+
query?: Query;
|
|
323
|
+
body?: unknown;
|
|
405
324
|
headers?: Record<string, string>;
|
|
406
|
-
/** 取消信号 */
|
|
407
325
|
signal?: AbortSignal;
|
|
408
|
-
|
|
326
|
+
responseType?: 'json' | 'text' | 'response';
|
|
327
|
+
auth?: boolean;
|
|
328
|
+
timeoutMs?: number;
|
|
409
329
|
cache?: RequestCache;
|
|
410
330
|
}
|
|
331
|
+
declare class RequestError extends Error {
|
|
332
|
+
readonly status: number;
|
|
333
|
+
readonly code: string;
|
|
334
|
+
readonly body: unknown;
|
|
335
|
+
constructor(status: number, code: string, message: string, body?: unknown);
|
|
336
|
+
}
|
|
337
|
+
type TokenGetter = () => string | null;
|
|
338
|
+
type RefreshHandler = () => Promise<unknown>;
|
|
339
|
+
declare function configureRequestAuth(options: {
|
|
340
|
+
getToken?: TokenGetter;
|
|
341
|
+
refresh?: RefreshHandler;
|
|
342
|
+
}): void;
|
|
343
|
+
declare function request<T = unknown>(path: string, options?: RequestOptions): Promise<T>;
|
|
344
|
+
|
|
411
345
|
interface HttpResult<T> {
|
|
412
346
|
status: number;
|
|
413
347
|
data: T;
|
|
@@ -445,6 +379,23 @@ declare const httpGet: <T = any>(path: string, opts?: RequestOptions) => Promise
|
|
|
445
379
|
declare const httpPost: <T = any>(path: string, body?: unknown, opts?: RequestOptions) => Promise<HttpResult<T>>;
|
|
446
380
|
declare const httpPostBinary: <T = any>(path: string, body: Blob, opts?: RequestOptions) => Promise<HttpResult<T>>;
|
|
447
381
|
|
|
382
|
+
interface UseRequestOptions {
|
|
383
|
+
immediate?: boolean;
|
|
384
|
+
}
|
|
385
|
+
interface UseRequestResult<T, Input> {
|
|
386
|
+
data: T | undefined;
|
|
387
|
+
error: Error | undefined;
|
|
388
|
+
loading: boolean;
|
|
389
|
+
run: (input: Input) => Promise<T | undefined>;
|
|
390
|
+
refresh: () => Promise<T | undefined>;
|
|
391
|
+
}
|
|
392
|
+
declare function useRequest<T, Input = void>(fn: (input: Input) => Promise<T>, deps?: readonly unknown[], options?: UseRequestOptions): UseRequestResult<T, Input>;
|
|
393
|
+
|
|
394
|
+
interface PageMeta {
|
|
395
|
+
title: string;
|
|
396
|
+
meta?: Record<string, unknown>;
|
|
397
|
+
}
|
|
398
|
+
|
|
448
399
|
declare global {
|
|
449
400
|
interface Window {
|
|
450
401
|
my?: AlipayWebViewMy;
|
|
@@ -462,4 +413,4 @@ interface AlipayWebViewMy {
|
|
|
462
413
|
*/
|
|
463
414
|
declare function ensureAlipayJSSDK(): Promise<AlipayWebViewMy | null>;
|
|
464
415
|
|
|
465
|
-
export { type AlipayNavigation, type AlipayWebViewMy, BRIDGE_NAME, BRIDGE_VERSION, type BridgeMediaFile, type BridgeReceipt, type BridgeRequest, CardCarousel, type CardComponentWithFlag, CardFrame, CardRenderer,
|
|
416
|
+
export { type AlipayNavigation, type AlipayWebViewMy, BRIDGE_NAME, BRIDGE_VERSION, type BridgeMediaFile, type BridgeReceipt, type BridgeRequest, CardCarousel, type CardComponentWithFlag, CardFrame, CardRenderer, type ClientLogTransport, type CreateServiceOptions, ErrorBoundary, type HttpResult, type JsapiMode, type LoginGateReceipt, MY_ACTION, MY_CALL_ACTION, type PageMeta, type PlateKeyboardOptions, type PlateKeyboardResult, type Query, type QueryValue, RequestError, type RequestOptions, type RuntimeContainer, type ServiceClient, StatusPill, type StatusPillTone, TBOX_ACTION, type UseRequestOptions, type UseRequestResult, ValueText, callCapability, callJsapi, chooseImage, chooseVideo, closePlateKeyboard, configureAuthErrorHandler, configureAuthToken, configureRequestAuth, configureRuntime, createClientLogger, createService, defaultService, ensureAlipayJSSDK, getApiBaseUrl, getApiOrigin, getAuthCode, getContainer, getLocation, getLoginState, getQueryParam, getRuntimeQuery, getWsUrl, hasAlipayBridge, httpGet, httpPost, httpPostBinary, installGlobalErrorReporting, isBridgeReceipt, isInAlipayShell, markSelfRendering, navigateToAlipayPage, openPlateKeyboard, request, requestPayment, resolveAlipayNavigation, setClientLogTransport, setClientRunContext, useRequest };
|
package/dist/client/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger as Ht}from"@tbox.cn/app-sdk-core";import{createCoreLogger as be,resolveLevel as X,setLogContextProvider as Ce}from"@tbox.cn/app-sdk-core";var N=null;Ce(()=>N??void 0);function he(e){N=e?{requestId:e.runId,conversationId:e.conversationId}:null}function ve(){try{if(typeof localStorage<"u")return X(localStorage.getItem("tbox:logLevel")??void 0,"info")}catch{}try{if(typeof location<"u"){let e=new URLSearchParams(location.search).get("logLevel");if(e)return X(e,"info")}}catch{}return"info"}function g(e){return be({tag:e,getLevel:ve,getContext:()=>N??void 0})}var Y;function we(e){Y=e}function Re(e){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let t=e??g("GLOBAL"),r=new Map,o=1e4,s=a=>{let n=Date.now();for(let[u,l]of r)n-l>=o&&r.delete(u);r.has(a)||(r.set(a,n),t.error(a),Y?.send("error",a))},i=a=>{s(`uncaught: ${a.message} @ ${a.filename}:${a.lineno}`)},d=a=>{let n=a.reason instanceof Error?a.reason.message:String(a.reason);s(`unhandledrejection: ${n}`)};return window.addEventListener("error",i),window.addEventListener("unhandledrejection",d),()=>{window.removeEventListener("error",i),window.removeEventListener("unhandledrejection",d)}}import{Component as Te}from"react";var Se=g("ErrorBoundary"),h=class extends Te{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){Se.error("render error:",t)}render(){return this.state.hasError?this.props.fallback:this.props.children}};import{jsx as m,jsxs as Ie}from"react/jsx-runtime";var R={info:{bg:"rgba(22,119,255,0.08)",color:"#1677ff"},warning:{bg:"rgba(250,140,22,0.10)",color:"#d46b08"},error:{bg:"rgba(255,77,79,0.08)",color:"#ff4d4f"}};function Ae({notices:e}){return e.length?m("div",{style:{display:"flex",flexDirection:"column",gap:4,marginBottom:8},children:e.map(t=>m("div",{style:{fontSize:12,lineHeight:"18px",padding:"4px 10px",borderRadius:8,background:R[t.level]?.bg??R.info.bg,color:R[t.level]?.color??R.info.color},children:t.message},`${t.code}:${t.message}`))}):null}function Pe({card:e,registry:t,onAction:r}){let o=e.status!=="error"?t[e.cardType]:void 0,s=e.status==="error"||!o,i=o?.selfRendersActions===!0,d=!e.isHistory&&!i&&e.actions?.length?e.actions:[],a=typeof e.expiresAt=="number"&&Date.now()>=e.expiresAt;return Ie("div",{className:`tbox-card${s?" tbox-card--fallback":""}${a?" tbox-card--stale":""}`,style:a?{opacity:.55,filter:"grayscale(1)"}:void 0,children:[m(Ae,{notices:e.notices??[]}),e.status==="error"?`卡片渲染失败${e.error?`:${e.error}`:""}`:o?m(h,{fallback:"卡片渲染出错",children:m(o,{data:e.data,cardId:e.id,isHistory:!!e.isHistory,actionTokens:e.actionTokens})}):`未知卡片类型:${e.cardType}`,d.length>0&&m("div",{style:{display:"flex",gap:8,marginTop:8,flexWrap:"wrap"},children:d.map(n=>{let u=!n.kind||n.kind==="moduleAction",l=u?e.actionTokens?.[n.actionId]:void 0,p=n.enabled===!1,c=p||!r||u&&!l,f=()=>n.kind==="sendMessage"?{type:"sendMessage",value:n.value??n.label??n.actionId,visible:n.visible??!0}:n.kind==="openLink"?{type:"openLink",url:n.url??""}:{type:"moduleAction",actionId:n.actionId,contextToken:l??""},O=()=>n.style==="primary"?{fontSize:13,padding:"6px 14px",borderRadius:18,border:"1px solid var(--tbox-primary, #1677ff)",color:"#fff",background:"var(--tbox-primary, #1677ff)"}:n.style==="link"?{fontSize:13,padding:"6px 4px",borderRadius:4,border:"none",color:"var(--tbox-primary, #1677ff)",background:"transparent",textDecoration:"underline"}:{fontSize:13,padding:"6px 14px",borderRadius:18,border:"1px solid var(--tbox-primary, #1677ff)",color:"var(--tbox-primary, #1677ff)",background:"transparent"};return m("button",{type:"button",disabled:c,title:p?n.disabledReason:void 0,onClick:()=>!c&&r?.(f()),style:{...O(),cursor:c?"not-allowed":"pointer",opacity:c?.5:1},children:n.label??n.actionId},n.actionId)})})]})}import{Fragment as Ee,jsx as q}from"react/jsx-runtime";function ke({cards:e,renderItem:t,className:r}){if(e.length<=1)return q(Ee,{children:e.length===1?t(e[0]):null});let o=["tbox-card-stack",r].filter(Boolean).join(" ");return q("div",{className:o,style:{display:"flex",flexDirection:"column"},children:e.map(s=>q("div",{children:t(s)},s.id))})}import{jsx as v,jsxs as _}from"react/jsx-runtime";var x=(e,t)=>`var(--${e}, ${t})`;function Le(e){return e.selfRendersActions=!0,e}function Be(e){return _("div",{style:{borderRadius:12,background:x("tbox-card-bg","#ffffff"),padding:"12px 16px",boxShadow:`0 1px 4px ${x("tbox-shadow","rgba(0,0,0,0.06)")}`,...e.style},children:[(e.title||e.subtitle)&&_("div",{style:{marginBottom:8},children:[e.title&&v("div",{style:{fontSize:15,fontWeight:600,color:x("tbox-text-primary","#1a1a1a"),lineHeight:"20px"},children:e.title}),e.subtitle&&v("div",{style:{fontSize:12,color:x("tbox-text-secondary","#888888"),marginTop:2},children:e.subtitle})]}),e.children]})}function Oe(e){return _("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"4px 0",gap:12},children:[v("span",{style:{fontSize:13,color:x("tbox-text-secondary","#888888"),flexShrink:0},children:e.label}),v("span",{style:{fontSize:13,color:x("tbox-text-primary","#1a1a1a"),textAlign:"right",wordBreak:"break-all",...e.valueStyle},children:e.value})]})}var Me={success:{fg:"#0f8a5f",bg:"#e6f7f0"},warning:{fg:"#b26a00",bg:"#fff4e0"},neutral:{fg:"#666666",bg:"#f2f3f5"}};function Ne(e){let t=Me[e.tone];return v("span",{style:{display:"inline-block",fontSize:11,lineHeight:"18px",padding:"0 8px",borderRadius:9,color:t.fg,background:t.bg,whiteSpace:"nowrap"},children:e.text})}var Q="";function qe(e){Q=(e.apiBaseUrl??"").trim().replace(/\/$/,"")}function T(){return Q}function Z(){let e=T();return e||(typeof window<"u"?`${window.location.protocol}//${window.location.host}`:"")}function _e(e="/ws"){return Z().replace(/^http/,"ws")+e}var $=null;function ee(){if($)return $;let e={};return typeof window<"u"&&new URLSearchParams(window.location.search).forEach((r,o)=>{e[o]=r}),$=e,e}function te(e){return ee()[e]}function S(){let e=te("container");return e==="alipay-miniapp"||e==="alipay"}function $e(){if(typeof window>"u")return!1;let e=window.my;return!!(e&&typeof e.postMessage=="function")}function De(){return S()?"alipay-miniapp":"browser"}var re=g("bridge"),D="https://appx/web-view.min.js",b=null;function ne(){return typeof window>"u"?null:window.my&&typeof window.my.postMessage=="function"?window.my:null}function W(){if(typeof window>"u")return Promise.resolve(null);let e=ne();return e?Promise.resolve(e):S()?b||(b=new Promise(t=>{let r=!1,o=null,s=null,i=()=>{o&&clearInterval(o),s&&clearTimeout(s),document.removeEventListener("AlipayJSBridgeReady",a)},d=u=>{r||(r=!0,i(),t(u))},a=()=>{let u=ne();u&&d(u)};document.addEventListener("AlipayJSBridgeReady",a);let n=document.querySelector(`script[src="${D}"]`);n||(n=document.createElement("script"),n.src=D,document.head.appendChild(n)),n.addEventListener("load",a,{once:!0}),n.addEventListener("error",()=>{re.warn("加载支付宝 JSSDK 失败:",D),n?.remove(),d(null)},{once:!0}),o=setInterval(a,50),s=setTimeout(()=>{re.warn("支付宝 JSSDK 已加载,但 my.postMessage 未就绪"),d(null)},5e3),a()}),b.then(t=>{t||(b=null)}),b):Promise.resolve(null)}import{detailForLog as H}from"@tbox.cn/app-sdk-core";var A="open-mini-webview-bridge",We="1.0.0",F="my",K="my.call",V="tbox";function P(e){return!!e&&typeof e=="object"&&e.bridge===A&&typeof e.requestId=="string"}var C=g("bridge"),I=new Map,oe=0,ie=!1,se=300*1e3;function Fe(){return oe+=1,`h5_${Date.now()}_${oe}`}function Ke(e){if(P(e)){ae(e);return}let t=e,r=e;if(r&&typeof r=="object"&&(r.detail!==void 0?t=r.detail:r.data!==void 0&&(t=r.data)),typeof t=="string")try{t=JSON.parse(t)}catch{return}P(t)&&ae(t)}function ae(e){let t=I.get(e.requestId);if(!t){C.debug(`收到无 pending 回执 req=${e.requestId} action=${e.action}`);return}clearTimeout(t.timer),I.delete(e.requestId);let r=Date.now()-t.startedAt;e.success?(C.info(`← ${t.apiName} ok ${r}ms req=${e.requestId}`),t.resolve(e.data)):(C.warn(`← ${t.apiName} fail code=${e.code||"BRIDGE_ERROR"} ${r}ms params=${H(t.params)} req=${e.requestId}`),t.reject({code:e.code||"BRIDGE_ERROR",errorMessage:e.errorMessage||"桥调用失败"}))}async function le(){let e=await W();return e&&!ie&&(e.onMessage=Ke,ie=!0),e}function de(e,t,r,o,s){let i=Fe();return new Promise((d,a)=>{let n=setTimeout(()=>{I.delete(i),C.warn(`← ${r} fail code=BRIDGE_TIMEOUT ${s}ms params=${H(o)} req=${i}`),a({code:"BRIDGE_TIMEOUT",errorMessage:`桥调用超时: ${r}`})},s);I.set(i,{resolve:d,reject:a,timer:n,apiName:r,params:o,startedAt:Date.now()}),C.info(`→ ${t} ${r} req=${i}`),C.debug(`params=${H(o)} req=${i}`),e.postMessage({bridge:A,action:t,apiName:r,params:o,requestId:i})})}async function y(e,t={},r="invoke",o=se){let s=await le();if(!s)throw{code:"BRIDGE_UNAVAILABLE",errorMessage:"支付宝 WebView 桥未就绪"};return de(s,r==="call"?K:"my",e,t,o)}async function w(e,t={},r=se){let o=await le();if(!o)throw{code:"BRIDGE_UNAVAILABLE",errorMessage:"支付宝 WebView 桥未就绪"};return de(o,V,e,t,r)}var G=/^[A-Za-z0-9._-]{1,80}$/u,pe=/[\u0000-\u001F\u007F]/u,ce=/^[A-Za-z][A-Za-z0-9+.-]*:/u;function Ve(e,t){if(!t||!G.test(t))return;let r;try{r=ue(e)}catch{return}if(r.protocol!=="alipays"&&r.protocol!=="alipayrisk"||r.host!=="platformapi"||r.path!=="/startapp")return;let o=(r.appId||r.query.appId||"").trim(),s=(r.query.page||"").trim(),i=(r.query.query||"").trim()||void 0,d=s.replace(/^\/+/,"");if(!(!G.test(o)||!d||pe.test(d)||ce.test(d)||d.split("/").includes(".."))){if(o===t){let a=d.includes("?")?"&":"?";return{apiName:"navigateTo",params:{url:`/${d}${i?`${a}${i}`:""}`}}}return{apiName:"navigateToMiniProgram",params:{appId:o,path:d,...i?{query:i}:{}}}}}function U(e){try{return decodeURIComponent(e)}catch{return e}}function ue(e){if(!e||typeof e!="string")throw new Error("Invalid URL");let t={protocol:"",host:"",path:"",query:{page:"",appId:""},appId:"",page:{path:"",query:{}}},r=e.match(/^([a-zA-Z]+):\/\//),o=e;r&&(t.protocol=r[1],o=o.slice(r[0].length));let s=o.indexOf("?"),i=s===-1?o:o.slice(0,s),d=s===-1?"":o.slice(s+1),a=i.indexOf("/");if(a>0?(t.host=i.slice(0,a),t.path=i.slice(a)):t.host=i,d){let n="",u={};for(let l of d.split("&")){if(l.startsWith("page=")){n=l.slice(5);continue}let p=l.indexOf("="),c=p>=0?l.slice(0,p):l;if(!c)continue;let f=p>=0?l.slice(p+1):"";u[c]=U(f)}if(t.query=u,n){t.query.page=U(n),t.query.appId&&(t.appId=t.query.appId);let l=n.indexOf("?"),p=l>=0?n.slice(0,l):n;t.page.path=U(p)}}return t}function ge(e){if(typeof e!="string")return;let t;try{t=ue(e)}catch{return}if(t.protocol!=="alipays"&&t.protocol!=="alipayrisk"||t.host!=="platformapi"||t.path!=="/startapp")return;let r=(t.appId||t.query.appId||"").trim(),o=(t.query.page||"").trim(),s=(t.query.query||"").trim()||void 0,i=o.replace(/^\/+/,"");if(!G.test(r)||!i||pe.test(i)||ce.test(i)||i.split("/").includes(".."))return;let d=i.includes("?")?"&":"?";return{appId:r,url:`/${i}${s?`${d}${s}`:""}`}}function He(e=9,t){return y("chooseImage",t?{count:e,sourceType:t}:{count:e},"invoke")}function Ue(){return y("chooseVideo",{},"invoke")}async function Ge(){let e=await y("getLocation",{type:0});return{...e,longitude:Number(e.longitude),latitude:Number(e.latitude)}}function Je(e=["auth_base"]){return y("getAuthCode",{scopes:e})}function ze(e){return y("tradePay",{tradeNO:e,orderStr:e})}function je(e){let t=ge(e);return t?y("navigateTo",{url:t.url}):Promise.reject({code:"INVALID_PARAMS",errorMessage:"支付宝小程序跳转链接无效"})}function Xe(e,t=300*1e3){return w("getLoginState",e??{},t)}function Ye(e={}){return w("openPlateKeyboard",{...e})}function Qe(){return w("closePlateKeyboard")}import{KNOWN_CLIENT_SLOT_IDS as Ze}from"@tbox.cn/app-contracts";var k=g("ClientCardRegistry"),fe=g("ClientSlotRegistry"),E=class{cards=new Map;overrides=new Map;inlineFilters=[];register(t,r){if(!t){k.warn("register without cardType skipped");return}this.cards.has(t)&&k.warn(`overwriting existing cardType: ${t}`),this.cards.set(t,r)}registerMap(t){for(let[r,o]of Object.entries(t))this.register(r,o)}registerOverride(t,r){if(!t){k.warn("registerOverride without cardType skipped");return}this.overrides.has(t)&&k.warn(`overwriting existing override: ${t}`),this.overrides.set(t,r)}getOverrides(){return Object.fromEntries(this.overrides)}registerInlineFilter(t){this.inlineFilters.push(t)}applyInlineFilters(t){return this.inlineFilters.length===0?[...t]:this.inlineFilters.reduce((r,o)=>o(r),[...t])}resolve(t){return this.cards.get(t)}getAll(){return Object.fromEntries(this.cards)}has(t){return this.cards.has(t)}get size(){return this.cards.size}},L=class{slots=new Map;register(t,r){Ze.includes(t)||fe.warn(`unknown slot id: ${t}(KNOWN_CLIENT_SLOT_IDS 未含——版本偏斜?照常注册)`),this.slots.has(t)&&fe.warn(`overwriting existing slot: ${t}`),this.slots.set(t,r)}resolve(t){return this.slots.get(t)}has(t){return this.slots.has(t)}get size(){return this.slots.size}};function et(){return{cards:new E,slots:new L}}var tt=g("HTTP"),J=null;function rt(e){J=e}var z=null;function nt(e){z=e}function ot(e,t){if(e!==401)return!1;let r=t?.code;return r==="AUTH_UNAUTHORIZED"||r==="AUTH_TOKEN_EXPIRED"}function it(e){return e.startsWith("/api/auth/")}function ye(e="",t,r={}){let o=e.replace(/\/$/,""),s=r.auth??!1,i=r.dynamicBase??!1,d=l=>({...t?.headers,...l?.headers});function a(){return i?T():o}function n(l){let p=d(l);if(s){let c=J?J():null;c&&!p.Authorization&&(p.Authorization=`Bearer ${c}`)}return p}async function u(l,p,c,f,O=0){let me=l==="POST"&&c instanceof Blob?n(f):l==="POST"?{"Content-Type":"application/json",...n(f)}:n(f),M=await fetch(a()+p,{method:l,headers:me,body:l==="POST"&&c!==void 0?c instanceof Blob?c:JSON.stringify(c):void 0,signal:f?.signal,cache:f?.cache}),j=await M.json().catch(()=>null);if(s&&O===0&&!it(p)&&ot(M.status,j)&&z){try{await z()}catch(xe){tt.warn("401 refresh failed:",xe.message)}return u(l,p,c,f,1)}return{status:M.status,data:j}}return{get:(l,p)=>u("GET",l,void 0,p),post:(l,p,c)=>u("POST",l,p,c),postBinary:(l,p,c)=>u("POST",l,p,c)}}var B=ye("",void 0,{auth:!0,dynamicBase:!0}),at=B.get,st=B.post,lt=B.postBinary;import{sanitizeForLog as ar,detailForLog as sr,truncateForLog as lr}from"@tbox.cn/app-sdk-core";export{A as BRIDGE_NAME,We as BRIDGE_VERSION,ke as CardCarousel,Be as CardFrame,Pe as CardRenderer,E as ClientCardRegistry,L as ClientSlotRegistry,h as ErrorBoundary,F as MY_ACTION,K as MY_CALL_ACTION,Ne as StatusPill,V as TBOX_ACTION,Oe as ValueText,w as callCapability,y as callJsapi,He as chooseImage,Ue as chooseVideo,Qe as closePlateKeyboard,nt as configureAuthErrorHandler,rt as configureAuthToken,qe as configureRuntime,et as createClientContext,g as createClientLogger,Ht as createLogger,ye as createService,B as defaultService,sr as detailForLog,W as ensureAlipayJSSDK,T as getApiBaseUrl,Z as getApiOrigin,Je as getAuthCode,De as getContainer,Ge as getLocation,Xe as getLoginState,te as getQueryParam,ee as getRuntimeQuery,_e as getWsUrl,$e as hasAlipayBridge,at as httpGet,st as httpPost,lt as httpPostBinary,Re as installGlobalErrorReporting,P as isBridgeReceipt,S as isInAlipayShell,Le as markSelfRendering,je as navigateToAlipayPage,Ye as openPlateKeyboard,ze as requestPayment,Ve as resolveAlipayNavigation,ar as sanitizeForLog,we as setClientLogTransport,he as setClientRunContext,lr as truncateForLog};
|
|
1
|
+
import{a as ye,b as R,c as me,d as be,e as L,f as xe,g as v,h as Re,i as he,j as Te,k as Ae,l as N,m as we,n as ve,o as Ce,p as Pe,q as Se,r as Ee,s as ke,t as Ie,u as qe}from"../chunk-DXL2GZRD.js";import{createLogger as Wt}from"@tbox.cn/app-sdk-core";import{jsx as h,jsxs as Me}from"react/jsx-runtime";var k={info:{bg:"rgba(22,119,255,0.08)",color:"#1677ff"},warning:{bg:"rgba(250,140,22,0.10)",color:"#d46b08"},error:{bg:"rgba(255,77,79,0.08)",color:"#ff4d4f"}};function Oe({notices:e}){return e.length?h("div",{style:{display:"flex",flexDirection:"column",gap:4,marginBottom:8},children:e.map(t=>h("div",{style:{fontSize:12,lineHeight:"18px",padding:"4px 10px",borderRadius:8,background:k[t.level]?.bg??k.info.bg,color:k[t.level]?.color??k.info.color},children:t.message},`${t.code}:${t.message}`))}):null}function Be({card:e,registry:t,onAction:r}){let n=e.status!=="error"?t[e.cardType]:void 0,s=e.status==="error"||!n,a=n?.selfRendersActions===!0,l=!e.isHistory&&!a&&e.actions?.length?e.actions:[],c=typeof e.expiresAt=="number"&&Date.now()>=e.expiresAt;return Me("div",{className:`tbox-card${s?" tbox-card--fallback":""}${c?" tbox-card--stale":""}`,style:c?{opacity:.55,filter:"grayscale(1)"}:void 0,children:[h(Oe,{notices:e.notices??[]}),e.status==="error"?`卡片渲染失败${e.error?`:${e.error}`:""}`:n?h(L,{fallback:"卡片渲染出错",children:h(n,{data:e.data,cardId:e.id,isHistory:!!e.isHistory,actionTokens:e.actionTokens})}):`未知卡片类型:${e.cardType}`,l.length>0&&h("div",{style:{display:"flex",gap:8,marginTop:8,flexWrap:"wrap"},children:l.map(i=>{let p=!i.kind||i.kind==="moduleAction",u=p?e.actionTokens?.[i.actionId]:void 0,o=i.enabled===!1,d=o||!r||p&&!u,f=()=>i.kind==="sendMessage"?{type:"sendMessage",value:i.value??i.label??i.actionId,visible:i.visible??!0}:i.kind==="openLink"?{type:"openLink",url:i.url??""}:{type:"moduleAction",actionId:i.actionId,contextToken:u??""},g=()=>i.style==="primary"?{fontSize:13,padding:"6px 14px",borderRadius:18,border:"1px solid var(--tbox-primary, #1677ff)",color:"#fff",background:"var(--tbox-primary, #1677ff)"}:i.style==="link"?{fontSize:13,padding:"6px 4px",borderRadius:4,border:"none",color:"var(--tbox-primary, #1677ff)",background:"transparent",textDecoration:"underline"}:{fontSize:13,padding:"6px 14px",borderRadius:18,border:"1px solid var(--tbox-primary, #1677ff)",color:"var(--tbox-primary, #1677ff)",background:"transparent"};return h("button",{type:"button",disabled:d,title:o?i.disabledReason:void 0,onClick:()=>!d&&r?.(f()),style:{...g(),cursor:d?"not-allowed":"pointer",opacity:d?.5:1},children:i.label??i.actionId},i.actionId)})})]})}import{Fragment as Ne,jsx as $}from"react/jsx-runtime";function Le({cards:e,renderItem:t,className:r}){if(e.length<=1)return $(Ne,{children:e.length===1?t(e[0]):null});let n=["tbox-card-stack",r].filter(Boolean).join(" ");return $("div",{className:n,style:{display:"flex",flexDirection:"column"},children:e.map(s=>$("div",{children:t(s)},s.id))})}import{jsx as C,jsxs as _}from"react/jsx-runtime";var T=(e,t)=>`var(--${e}, ${t})`;function $e(e){return e.selfRendersActions=!0,e}function _e(e){return _("div",{style:{borderRadius:12,background:T("tbox-card-bg","#ffffff"),padding:"12px 16px",boxShadow:`0 1px 4px ${T("tbox-shadow","rgba(0,0,0,0.06)")}`,...e.style},children:[(e.title||e.subtitle)&&_("div",{style:{marginBottom:8},children:[e.title&&C("div",{style:{fontSize:15,fontWeight:600,color:T("tbox-text-primary","#1a1a1a"),lineHeight:"20px"},children:e.title}),e.subtitle&&C("div",{style:{fontSize:12,color:T("tbox-text-secondary","#888888"),marginTop:2},children:e.subtitle})]}),e.children]})}function De(e){return _("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"4px 0",gap:12},children:[C("span",{style:{fontSize:13,color:T("tbox-text-secondary","#888888"),flexShrink:0},children:e.label}),C("span",{style:{fontSize:13,color:T("tbox-text-primary","#1a1a1a"),textAlign:"right",wordBreak:"break-all",...e.valueStyle},children:e.value})]})}var He={success:{fg:"#0f8a5f",bg:"#e6f7f0"},warning:{fg:"#b26a00",bg:"#fff4e0"},neutral:{fg:"#666666",bg:"#f2f3f5"}};function Ue(e){let t=He[e.tone];return C("span",{style:{display:"inline-block",fontSize:11,lineHeight:"18px",padding:"0 8px",borderRadius:9,color:t.fg,background:t.bg,whiteSpace:"nowrap"},children:e.text})}var Z=R("bridge"),D="https://appx/web-view.min.js",A=null;function ee(){return typeof window>"u"?null:window.my&&typeof window.my.postMessage=="function"?window.my:null}function H(){if(typeof window>"u")return Promise.resolve(null);let e=ee();return e?Promise.resolve(e):N()?A||(A=new Promise(t=>{let r=!1,n=null,s=null,a=()=>{n&&clearInterval(n),s&&clearTimeout(s),document.removeEventListener("AlipayJSBridgeReady",c)},l=p=>{r||(r=!0,a(),t(p))},c=()=>{let p=ee();p&&l(p)};document.addEventListener("AlipayJSBridgeReady",c);let i=document.querySelector(`script[src="${D}"]`);i||(i=document.createElement("script"),i.src=D,document.head.appendChild(i)),i.addEventListener("load",c,{once:!0}),i.addEventListener("error",()=>{Z.warn("加载支付宝 JSSDK 失败:",D),i?.remove(),l(null)},{once:!0}),n=setInterval(c,50),s=setTimeout(()=>{Z.warn("支付宝 JSSDK 已加载,但 my.postMessage 未就绪"),l(null)},5e3),c()}),A.then(t=>{t||(A=null)}),A):Promise.resolve(null)}import{detailForLog as W}from"@tbox.cn/app-sdk-core";var I="open-mini-webview-bridge",Ge="1.0.0",U="my",G="my.call",V="tbox";function q(e){return!!e&&typeof e=="object"&&e.bridge===I&&typeof e.requestId=="string"}var w=R("bridge"),O=new Map,te=0,re=!1,oe=300*1e3;function Ve(){return te+=1,`h5_${Date.now()}_${te}`}function We(e){if(q(e)){ne(e);return}let t=e,r=e;if(r&&typeof r=="object"&&(r.detail!==void 0?t=r.detail:r.data!==void 0&&(t=r.data)),typeof t=="string")try{t=JSON.parse(t)}catch{return}q(t)&&ne(t)}function ne(e){let t=O.get(e.requestId);if(!t){w.debug(`收到无 pending 回执 req=${e.requestId} action=${e.action}`);return}clearTimeout(t.timer),O.delete(e.requestId);let r=Date.now()-t.startedAt;e.success?(w.info(`← ${t.apiName} ok ${r}ms req=${e.requestId}`),t.resolve(e.data)):(w.warn(`← ${t.apiName} fail code=${e.code||"BRIDGE_ERROR"} ${r}ms params=${W(t.params)} req=${e.requestId}`),t.reject({code:e.code||"BRIDGE_ERROR",errorMessage:e.errorMessage||"桥调用失败"}))}async function ie(){let e=await H();return e&&!re&&(e.onMessage=We,re=!0),e}function ae(e,t,r,n,s){let a=Ve();return new Promise((l,c)=>{let i=setTimeout(()=>{O.delete(a),w.warn(`← ${r} fail code=BRIDGE_TIMEOUT ${s}ms params=${W(n)} req=${a}`),c({code:"BRIDGE_TIMEOUT",errorMessage:`桥调用超时: ${r}`})},s);O.set(a,{resolve:l,reject:c,timer:i,apiName:r,params:n,startedAt:Date.now()}),w.info(`→ ${t} ${r} req=${a}`),w.debug(`params=${W(n)} req=${a}`),e.postMessage({bridge:I,action:t,apiName:r,params:n,requestId:a})})}async function y(e,t={},r="invoke",n=oe){let s=await ie();if(!s)throw{code:"BRIDGE_UNAVAILABLE",errorMessage:"支付宝 WebView 桥未就绪"};return ae(s,r==="call"?G:"my",e,t,n)}async function P(e,t={},r=oe){let n=await ie();if(!n)throw{code:"BRIDGE_UNAVAILABLE",errorMessage:"支付宝 WebView 桥未就绪"};return ae(n,V,e,t,r)}var F=/^[A-Za-z0-9._-]{1,80}$/u,se=/[\u0000-\u001F\u007F]/u,ue=/^[A-Za-z][A-Za-z0-9+.-]*:/u;function Je(e,t){if(!t||!F.test(t))return;let r;try{r=le(e)}catch{return}if(r.protocol!=="alipays"&&r.protocol!=="alipayrisk"||r.host!=="platformapi"||r.path!=="/startapp")return;let n=(r.appId||r.query.appId||"").trim(),s=(r.query.page||"").trim(),a=(r.query.query||"").trim()||void 0,l=s.replace(/^\/+/,"");if(!(!F.test(n)||!l||se.test(l)||ue.test(l)||l.split("/").includes(".."))){if(n===t){let c=l.includes("?")?"&":"?";return{apiName:"navigateTo",params:{url:`/${l}${a?`${c}${a}`:""}`}}}return{apiName:"navigateToMiniProgram",params:{appId:n,path:l,...a?{query:a}:{}}}}}function J(e){try{return decodeURIComponent(e)}catch{return e}}function le(e){if(!e||typeof e!="string")throw new Error("Invalid URL");let t={protocol:"",host:"",path:"",query:{page:"",appId:""},appId:"",page:{path:"",query:{}}},r=e.match(/^([a-zA-Z]+):\/\//),n=e;r&&(t.protocol=r[1],n=n.slice(r[0].length));let s=n.indexOf("?"),a=s===-1?n:n.slice(0,s),l=s===-1?"":n.slice(s+1),c=a.indexOf("/");if(c>0?(t.host=a.slice(0,c),t.path=a.slice(c)):t.host=a,l){let i="",p={};for(let u of l.split("&")){if(u.startsWith("page=")){i=u.slice(5);continue}let o=u.indexOf("="),d=o>=0?u.slice(0,o):u;if(!d)continue;let f=o>=0?u.slice(o+1):"";p[d]=J(f)}if(t.query=p,i){t.query.page=J(i),t.query.appId&&(t.appId=t.query.appId);let u=i.indexOf("?"),o=u>=0?i.slice(0,u):i;t.page.path=J(o)}}return t}function de(e){if(typeof e!="string")return;let t;try{t=le(e)}catch{return}if(t.protocol!=="alipays"&&t.protocol!=="alipayrisk"||t.host!=="platformapi"||t.path!=="/startapp")return;let r=(t.appId||t.query.appId||"").trim(),n=(t.query.page||"").trim(),s=(t.query.query||"").trim()||void 0,a=n.replace(/^\/+/,"");if(!F.test(r)||!a||se.test(a)||ue.test(a)||a.split("/").includes(".."))return;let l=a.includes("?")?"&":"?";return{appId:r,url:`/${a}${s?`${l}${s}`:""}`}}function Fe(e=9,t){return y("chooseImage",t?{count:e,sourceType:t}:{count:e},"invoke")}function Ke(){return y("chooseVideo",{},"invoke")}async function ze(){let e=await y("getLocation",{type:0});return{...e,longitude:Number(e.longitude),latitude:Number(e.latitude)}}function Qe(e=["auth_base"]){return y("getAuthCode",{scopes:e})}function je(e){return y("tradePay",{tradeNO:e,orderStr:e})}function Ye(e){let t=de(e);return t?y("navigateTo",{url:t.url}):Promise.reject({code:"INVALID_PARAMS",errorMessage:"支付宝小程序跳转链接无效"})}function Xe(e,t=300*1e3){return P("getLoginState",e??{},t)}function Ze(e={}){return P("openPlateKeyboard",{...e})}function et(){return P("closePlateKeyboard")}var m=class extends Error{status;code;body;constructor(t,r,n,s){super(n),this.name="RequestError",this.status=t,this.code=r,this.body=s}},K=null,z=null;function B(e){e.getToken&&(K=e.getToken),e.refresh&&(z=e.refresh)}function tt(e,t){if(!t)return e;let r=new URLSearchParams;for(let[s,a]of Object.entries(t))if(a!=null)if(Array.isArray(a))for(let l of a)l!=null&&r.append(s,String(l));else r.append(s,String(a));let n=r.toString();return n?`${e}${e.includes("?")?"&":"?"}${n}`:e}function rt(e){return/^https?:\/\//.test(e)?e:`${v().replace(/\/$/,"")}${e.startsWith("/")?e:`/${e}`}`}async function nt(e,t){if(e.status===204)return;if(t==="response")return e;if(t==="text")return e.text();let r=await e.text();if(r)try{return JSON.parse(r)}catch{return r}}async function ot(e,t={}){let r=t.method??"GET";if((r==="GET"||r==="DELETE")&&t.body!==void 0)throw new m(0,"REQUEST_BODY_NOT_ALLOWED",`${r} 请求不能携带 body`);let n={...t.headers},s=t.body===void 0?void 0:JSON.stringify(t.body);s!==void 0&&!n["Content-Type"]&&(n["Content-Type"]="application/json");let a=t.auth??!0;if(a&&K){let o=K();o&&!n.Authorization&&(n.Authorization=`Bearer ${o}`)}let l=new AbortController,c=t.timeoutMs??3e4,i=c>0?setTimeout(()=>l.abort(new Error("REQUEST_TIMEOUT")),c):void 0,p=()=>l.abort(t.signal?.reason);t.signal?.addEventListener("abort",p,{once:!0});let u=async()=>fetch(tt(rt(e),t.query),{method:r,headers:n,body:s,signal:l.signal,credentials:a?"include":"same-origin",cache:t.cache});try{let o=await u();if(o.status===401&&a&&z){try{await z()}catch{}o=await u()}let d=t.responseType??"json",f=await nt(o,d);if(!o.ok){let g=f&&typeof f=="object"?f.error:void 0;throw new m(o.status,g?.code??`HTTP_${o.status}`,g?.message??`请求失败(HTTP ${o.status})`,f)}return f}catch(o){throw o instanceof m?o:o.name==="AbortError"?new m(0,"REQUEST_ABORTED","请求已取消",o):new m(0,"REQUEST_FAILED",o.message,o)}finally{i&&clearTimeout(i),t.signal?.removeEventListener("abort",p)}}var it=R("HTTP"),Q=null;function at(e){Q=e,B({getToken:e})}var j=null;function st(e){j=e,B({refresh:e})}function ut(e,t){if(e!==401)return!1;let r=t?.code;return r==="AUTH_UNAUTHORIZED"||r==="AUTH_TOKEN_EXPIRED"}function lt(e){return e.startsWith("/api/auth/")}function ce(e="",t,r={}){let n=e.replace(/\/$/,""),s=r.auth??!1,a=r.dynamicBase??!1,l=u=>({...t?.headers,...u?.headers});function c(){return a?v():n}function i(u){let o=l(u);if(s){let d=Q?Q():null;d&&!o.Authorization&&(o.Authorization=`Bearer ${d}`)}return o}async function p(u,o,d,f,g=0){let E=u==="POST"&&d instanceof Blob?i(f):u==="POST"?{"Content-Type":"application/json",...i(f)}:i(f),b=await fetch(c()+o,{method:u,headers:E,body:u==="POST"&&d!==void 0?d instanceof Blob?d:JSON.stringify(d):void 0,signal:f?.signal,cache:f?.cache}),x=await b.json().catch(()=>null);if(s&&g===0&&!lt(o)&&ut(b.status,x)&&j){try{await j()}catch(ge){it.warn("401 refresh failed:",ge.message)}return p(u,o,d,f,1)}return{status:b.status,data:x}}return{get:(u,o)=>p("GET",u,void 0,o),post:(u,o,d)=>p("POST",u,o,d),postBinary:(u,o,d)=>p("POST",u,o,d)}}var M=ce("",void 0,{auth:!0,dynamicBase:!0}),dt=M.get,ct=M.post,pt=M.postBinary;import{useCallback as pe,useEffect as fe,useRef as S,useState as Y}from"react";function ft(e,t=[],r={}){let[n,s]=Y(void 0),[a,l]=Y(void 0),[c,i]=Y(!1),p=S(void 0),u=S(!1),o=S(!0),d=S(0),f=S(e);f.current=e,fe(()=>(o.current=!0,()=>{o.current=!1,d.current+=1}),[]);let g=pe(async E=>{p.current=E,u.current=!0;let b=++d.current;i(!0),l(void 0);try{let x=await f.current(E);return o.current&&d.current===b&&s(x),x}catch(x){o.current&&d.current===b&&l(x);return}finally{o.current&&d.current===b&&i(!1)}},[]),X=pe(async()=>{if(u.current)return g(p.current)},[g]);return fe(()=>{r.immediate===!1||u.current||g(void 0)},t),{data:n,error:a,loading:c,run:g,refresh:X}}import{sanitizeForLog as lr,detailForLog as dr,truncateForLog as cr}from"@tbox.cn/app-sdk-core";export{I as BRIDGE_NAME,Ge as BRIDGE_VERSION,Le as CardCarousel,_e as CardFrame,Be as CardRenderer,Ce as ClientCardRegistry,Pe as ClientSlotRegistry,L as ErrorBoundary,U as MY_ACTION,G as MY_CALL_ACTION,m as RequestError,Ue as StatusPill,V as TBOX_ACTION,De as ValueText,P as callCapability,y as callJsapi,Fe as chooseImage,Ke as chooseVideo,et as closePlateKeyboard,st as configureAuthErrorHandler,at as configureAuthToken,B as configureRequestAuth,xe as configureRuntime,Se as createClientContext,R as createClientLogger,Wt as createLogger,ce as createService,M as defaultService,dr as detailForLog,H as ensureAlipayJSSDK,v as getApiBaseUrl,Re as getApiOrigin,Qe as getAuthCode,Ee as getClientContext,ve as getContainer,ze as getLocation,Xe as getLoginState,Ae as getQueryParam,qe as getRegisteredClientCards,Te as getRuntimeQuery,he as getWsUrl,we as hasAlipayBridge,dt as httpGet,ct as httpPost,pt as httpPostBinary,be as installGlobalErrorReporting,q as isBridgeReceipt,N as isInAlipayShell,$e as markSelfRendering,Ye as navigateToAlipayPage,Ze as openPlateKeyboard,ke as registerClientCards,Ie as registerClientModules,ot as request,je as requestPayment,Je as resolveAlipayNavigation,lr as sanitizeForLog,me as setClientLogTransport,ye as setClientRunContext,cr as truncateForLog,ft as useRequest};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tbox.cn/app-sdk-client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0-alpha.6",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "tbox 应用平台 SDK client 轴:runtime/http/logger/error-boundary、桥接(支付宝 web-view)、client-context、卡片渲染基元。agent 前端运行时在 @tbox.cn/app-agent-sdk-client。",
|
|
6
6
|
"exports": {
|
|
@@ -12,6 +12,10 @@
|
|
|
12
12
|
"types": "./dist/client/index.d.ts",
|
|
13
13
|
"import": "./dist/client/index.js"
|
|
14
14
|
},
|
|
15
|
+
"./app": {
|
|
16
|
+
"types": "./dist/app/index.d.ts",
|
|
17
|
+
"import": "./dist/app/index.js"
|
|
18
|
+
},
|
|
15
19
|
"./platform/code-inspect": {
|
|
16
20
|
"types": "./platform/code-inspect.d.cts",
|
|
17
21
|
"default": "./platform/code-inspect.cjs"
|
|
@@ -30,10 +34,10 @@
|
|
|
30
34
|
"access": "public"
|
|
31
35
|
},
|
|
32
36
|
"dependencies": {
|
|
33
|
-
"@tbox.cn/app-contracts": "0.13.3",
|
|
34
|
-
"@tbox.cn/app-sdk-core": "0.20.5",
|
|
35
37
|
"react": "18.3.1",
|
|
36
|
-
"react-dom": "18.3.1"
|
|
38
|
+
"react-dom": "18.3.1",
|
|
39
|
+
"@tbox.cn/app-contracts": "1.0.0-alpha.6",
|
|
40
|
+
"@tbox.cn/app-sdk-core": "1.0.0-alpha.6"
|
|
37
41
|
},
|
|
38
42
|
"devDependencies": {
|
|
39
43
|
"@types/node": "24.13.3",
|