@tbox.cn/app-sdk-client 0.21.2 → 0.21.4
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/client/index.js +1 -1
- package/package.json +3 -3
package/dist/client/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger as Vt}from"@tbox.cn/app-sdk-core";import{createCoreLogger as be,resolveLevel as j,setLogContextProvider as Ce}from"@tbox.cn/app-sdk-core";var M=null;Ce(()=>M??void 0);function he(e){M=e?{requestId:e.runId,conversationId:e.conversationId}:null}function ve(){try{if(typeof localStorage<"u")return j(localStorage.getItem("tbox:logLevel")??void 0,"info")}catch{}try{if(typeof location<"u"){let e=new URLSearchParams(location.search).get("logLevel");if(e)return j(e,"info")}}catch{}return"info"}function u(e){return be({tag:e,getLevel:ve,getContext:()=>M??void 0})}var X;function we(e){X=e}function Re(e){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let t=e??u("GLOBAL"),r=new Map,n=1e4,l=a=>{let o=Date.now();for(let[g,s]of r)o-s>=n&&r.delete(g);r.has(a)||(r.set(a,o),t.error(a),X?.send("error",a))},i=a=>{l(`uncaught: ${a.message} @ ${a.filename}:${a.lineno}`)},d=a=>{let o=a.reason instanceof Error?a.reason.message:String(a.reason);l(`unhandledrejection: ${o}`)};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=u("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 n=e.status!=="error"?t[e.cardType]:void 0,l=e.status==="error"||!n,i=n?.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${l?" 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}`:""}`:n?m(h,{fallback:"卡片渲染出错",children:m(n,{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(o=>{let g=!o.kind||o.kind==="moduleAction",s=g?e.actionTokens?.[o.actionId]:void 0,p=o.enabled===!1,c=p||!r||g&&!s,f=()=>o.kind==="sendMessage"?{type:"sendMessage",value:o.value??o.label??o.actionId,visible:o.visible??!0}:o.kind==="openLink"?{type:"openLink",url:o.url??""}:{type:"moduleAction",actionId:o.actionId,contextToken:s??""},B=()=>o.style==="primary"?{fontSize:13,padding:"6px 14px",borderRadius:18,border:"1px solid var(--tbox-primary, #1677ff)",color:"#fff",background:"var(--tbox-primary, #1677ff)"}:o.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?o.disabledReason:void 0,onClick:()=>!c&&r?.(f()),style:{...B(),cursor:c?"not-allowed":"pointer",opacity:c?.5:1},children:o.label??o.actionId},o.actionId)})})]})}import{Fragment as Ee,jsx as N}from"react/jsx-runtime";function ke({cards:e,renderItem:t,className:r}){if(e.length<=1)return N(Ee,{children:e.length===1?t(e[0]):null});let n=["tbox-card-stack",r].filter(Boolean).join(" ");return N("div",{className:n,style:{display:"flex",flexDirection:"column"},children:e.map(l=>N("div",{children:t(l)},l.id))})}import{jsx as v,jsxs as q}from"react/jsx-runtime";var x=(e,t)=>`var(--${e}, ${t})`;function Le(e){return e.selfRendersActions=!0,e}function Be(e){return q("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)&&q("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 q("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 Y=u("bridge"),_="https://appx/web-view.min.js",b=null;function Q(){return typeof window>"u"?null:window.my&&typeof window.my.postMessage=="function"?window.my:null}function $(){if(typeof window<"u"){let e=Q();if(e)return Promise.resolve(e)}return b||(b=new Promise(e=>{if(typeof window>"u"){e(null);return}let t=!1,r=null,n=null,l=()=>{r&&clearInterval(r),n&&clearTimeout(n),document.removeEventListener("AlipayJSBridgeReady",d)},i=o=>{t||(t=!0,l(),e(o))},d=()=>{let o=Q();o&&i(o)};document.addEventListener("AlipayJSBridgeReady",d);let a=document.querySelector(`script[src="${_}"]`);a||(a=document.createElement("script"),a.src=_,document.head.appendChild(a)),a.addEventListener("load",d,{once:!0}),a.addEventListener("error",()=>{Y.warn("加载支付宝 JSSDK 失败:",_),a?.remove(),i(null)},{once:!0}),r=setInterval(d,50),n=setTimeout(()=>{Y.warn("支付宝 JSSDK 已加载,但 my.postMessage 未就绪"),i(null)},5e3),d()}),b.then(e=>{e||(b=null)}),b)}import{detailForLog as K}from"@tbox.cn/app-sdk-core";var T="open-mini-webview-bridge",qe="1.0.0",D="my",W="my.call",F="tbox";function S(e){return!!e&&typeof e=="object"&&e.bridge===T&&typeof e.requestId=="string"}var C=u("bridge"),A=new Map,Z=0,ee=!1,re=300*1e3;function _e(){return Z+=1,`h5_${Date.now()}_${Z}`}function $e(e){if(S(e)){te(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}S(t)&&te(t)}function te(e){let t=A.get(e.requestId);if(!t){C.debug(`收到无 pending 回执 req=${e.requestId} action=${e.action}`);return}clearTimeout(t.timer),A.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=${K(t.params)} req=${e.requestId}`),t.reject({code:e.code||"BRIDGE_ERROR",errorMessage:e.errorMessage||"桥调用失败"}))}async function ne(){let e=await $();return e&&!ee&&(e.onMessage=$e,ee=!0),e}function oe(e,t,r,n,l){let i=_e();return new Promise((d,a)=>{let o=setTimeout(()=>{A.delete(i),C.warn(`← ${r} fail code=BRIDGE_TIMEOUT ${l}ms params=${K(n)} req=${i}`),a({code:"BRIDGE_TIMEOUT",errorMessage:`桥调用超时: ${r}`})},l);A.set(i,{resolve:d,reject:a,timer:o,apiName:r,params:n,startedAt:Date.now()}),C.info(`→ ${t} ${r} req=${i}`),C.debug(`params=${K(n)} req=${i}`),e.postMessage({bridge:T,action:t,apiName:r,params:n,requestId:i})})}async function y(e,t={},r="invoke",n=re){let l=await ne();if(!l)throw{code:"BRIDGE_UNAVAILABLE",errorMessage:"支付宝 WebView 桥未就绪"};return oe(l,r==="call"?W:"my",e,t,n)}async function w(e,t={},r=re){let n=await ne();if(!n)throw{code:"BRIDGE_UNAVAILABLE",errorMessage:"支付宝 WebView 桥未就绪"};return oe(n,F,e,t,r)}var H=/^[A-Za-z0-9._-]{1,80}$/u,ie=/[\u0000-\u001F\u007F]/u,ae=/^[A-Za-z][A-Za-z0-9+.-]*:/u;function De(e,t){if(!t||!H.test(t))return;let r;try{r=se(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(),l=(r.query.page||"").trim(),i=(r.query.query||"").trim()||void 0,d=l.replace(/^\/+/,"");if(!(!H.test(n)||!d||ie.test(d)||ae.test(d)||d.split("/").includes(".."))){if(n===t){let a=d.includes("?")?"&":"?";return{apiName:"navigateTo",params:{url:`/${d}${i?`${a}${i}`:""}`}}}return{apiName:"navigateToMiniProgram",params:{appId:n,path:d,...i?{query:i}:{}}}}}function V(e){try{return decodeURIComponent(e)}catch{return e}}function se(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 l=n.indexOf("?"),i=l===-1?n:n.slice(0,l),d=l===-1?"":n.slice(l+1),a=i.indexOf("/");if(a>0?(t.host=i.slice(0,a),t.path=i.slice(a)):t.host=i,d){let o="",g={};for(let s of d.split("&")){if(s.startsWith("page=")){o=s.slice(5);continue}let p=s.indexOf("="),c=p>=0?s.slice(0,p):s;if(!c)continue;let f=p>=0?s.slice(p+1):"";g[c]=V(f)}if(t.query=g,o){t.query.page=V(o),t.query.appId&&(t.appId=t.query.appId);let s=o.indexOf("?"),p=s>=0?o.slice(0,s):o;t.page.path=V(p)}}return t}function le(e){if(typeof e!="string")return;let t;try{t=se(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(),l=(t.query.query||"").trim()||void 0,i=n.replace(/^\/+/,"");if(!H.test(r)||!i||ie.test(i)||ae.test(i)||i.split("/").includes(".."))return;let d=i.includes("?")?"&":"?";return{appId:r,url:`/${i}${l?`${d}${l}`:""}`}}function We(e=9,t){return y("chooseImage",t?{count:e,sourceType:t}:{count:e},"invoke")}function Fe(){return y("chooseVideo",{},"invoke")}async function Ke(){let e=await y("getLocation",{type:0});return{...e,longitude:Number(e.longitude),latitude:Number(e.latitude)}}function Ve(e=["auth_base"]){return y("getAuthCode",{scopes:e})}function He(e){return y("tradePay",{tradeNO:e,orderStr:e})}function Ue(e){let t=le(e);return t?y("navigateTo",{url:t.url}):Promise.reject({code:"INVALID_PARAMS",errorMessage:"支付宝小程序跳转链接无效"})}function Ge(e,t=300*1e3){return w("getLoginState",e??{},t)}function Je(e={}){return w("openPlateKeyboard",{...e})}function ze(){return w("closePlateKeyboard")}import{KNOWN_CLIENT_SLOT_IDS as je}from"@tbox.cn/app-contracts";var P=u("ClientCardRegistry"),de=u("ClientSlotRegistry"),I=class{cards=new Map;overrides=new Map;inlineFilters=[];register(t,r){if(!t){P.warn("register without cardType skipped");return}this.cards.has(t)&&P.warn(`overwriting existing cardType: ${t}`),this.cards.set(t,r)}registerMap(t){for(let[r,n]of Object.entries(t))this.register(r,n)}registerOverride(t,r){if(!t){P.warn("registerOverride without cardType skipped");return}this.overrides.has(t)&&P.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,n)=>n(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}},k=class{slots=new Map;register(t,r){je.includes(t)||de.warn(`unknown slot id: ${t}(KNOWN_CLIENT_SLOT_IDS 未含——版本偏斜?照常注册)`),this.slots.has(t)&&de.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 Xe(){return{cards:new I,slots:new k}}var pe="";function Ye(e){pe=(e.apiBaseUrl??"").trim().replace(/\/$/,"")}function E(){return pe}function ce(){let e=E();return e||(typeof window<"u"?`${window.location.protocol}//${window.location.host}`:"")}function Qe(e="/ws"){return ce().replace(/^http/,"ws")+e}var U=null;function ue(){if(U)return U;let e={};return typeof window<"u"&&new URLSearchParams(window.location.search).forEach((r,n)=>{e[n]=r}),U=e,e}function ge(e){return ue()[e]}function fe(){let e=ge("container");return e==="alipay-miniapp"||e==="alipay"}function Ze(){if(typeof window>"u")return!1;let e=window.my;return!!(e&&typeof e.postMessage=="function")}function et(){return fe()?"alipay-miniapp":"browser"}var tt=u("HTTP"),G=null;function rt(e){G=e}var J=null;function nt(e){J=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 n=e.replace(/\/$/,""),l=r.auth??!1,i=r.dynamicBase??!1,d=s=>({...t?.headers,...s?.headers});function a(){return i?E():n}function o(s){let p=d(s);if(l){let c=G?G():null;c&&!p.Authorization&&(p.Authorization=`Bearer ${c}`)}return p}async function g(s,p,c,f,B=0){let me=s==="POST"&&c instanceof Blob?o(f):s==="POST"?{"Content-Type":"application/json",...o(f)}:o(f),O=await fetch(a()+p,{method:s,headers:me,body:s==="POST"&&c!==void 0?c instanceof Blob?c:JSON.stringify(c):void 0,signal:f?.signal,cache:f?.cache}),z=await O.json().catch(()=>null);if(l&&B===0&&!it(p)&&ot(O.status,z)&&J){try{await J()}catch(xe){tt.warn("401 refresh failed:",xe.message)}return g(s,p,c,f,1)}return{status:O.status,data:z}}return{get:(s,p)=>g("GET",s,void 0,p),post:(s,p,c)=>g("POST",s,p,c),postBinary:(s,p,c)=>g("POST",s,p,c)}}var L=ye("",void 0,{auth:!0,dynamicBase:!0}),at=L.get,st=L.post,lt=L.postBinary;import{sanitizeForLog as ir,detailForLog as ar,truncateForLog as sr}from"@tbox.cn/app-sdk-core";export{T as BRIDGE_NAME,qe as BRIDGE_VERSION,ke as CardCarousel,Be as CardFrame,Pe as CardRenderer,I as ClientCardRegistry,k as ClientSlotRegistry,h as ErrorBoundary,D as MY_ACTION,W as MY_CALL_ACTION,Ne as StatusPill,F as TBOX_ACTION,Oe as ValueText,w as callCapability,y as callJsapi,We as chooseImage,Fe as chooseVideo,ze as closePlateKeyboard,nt as configureAuthErrorHandler,rt as configureAuthToken,Ye as configureRuntime,Xe as createClientContext,u as createClientLogger,Vt as createLogger,ye as createService,L as defaultService,ar as detailForLog,$ as ensureAlipayJSSDK,E as getApiBaseUrl,ce as getApiOrigin,Ve as getAuthCode,et as getContainer,Ke as getLocation,Ge as getLoginState,ge as getQueryParam,ue as getRuntimeQuery,Qe as getWsUrl,Ze as hasAlipayBridge,at as httpGet,st as httpPost,lt as httpPostBinary,Re as installGlobalErrorReporting,S as isBridgeReceipt,fe as isInAlipayShell,Le as markSelfRendering,Ue as navigateToAlipayPage,Je as openPlateKeyboard,He as requestPayment,De as resolveAlipayNavigation,ir as sanitizeForLog,we as setClientLogTransport,he as setClientRunContext,sr as truncateForLog};
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tbox.cn/app-sdk-client",
|
|
3
|
-
"version": "0.21.
|
|
3
|
+
"version": "0.21.4",
|
|
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": {
|
|
@@ -30,8 +30,8 @@
|
|
|
30
30
|
"access": "public"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@tbox.cn/app-contracts": "0.
|
|
34
|
-
"@tbox.cn/app-sdk-core": "0.20.
|
|
33
|
+
"@tbox.cn/app-contracts": "0.13.3",
|
|
34
|
+
"@tbox.cn/app-sdk-core": "0.20.5",
|
|
35
35
|
"react": "18.3.1",
|
|
36
36
|
"react-dom": "18.3.1"
|
|
37
37
|
},
|