@lark-base-open/base-database-app-sdk 0.0.1-alpha.2 → 0.2.0
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/CHANGELOG.md +12 -0
- package/README.md +8 -8
- package/capabilities.json +1 -1
- package/dist/chunk-Q7AAUQ7T.js +1 -0
- package/dist/codegen.cjs +11 -9
- package/dist/codegen.d.cts +2 -0
- package/dist/codegen.d.ts +2 -0
- package/dist/codegen.js +12 -10
- package/dist/components.d.ts +1 -1
- package/dist/components.js +1 -1
- package/dist/{index-64557073.d.ts → index-1e1bba93.d.ts} +14 -2
- package/dist/page.d.ts +2 -2
- package/dist/page.js +1 -1
- package/docs/codegen.md +4 -2
- package/docs/compat.md +5 -2
- package/docs/exports.md +1 -1
- package/examples/compat.ts +4 -1
- package/package.json +2 -1
- package/dist/chunk-5XIFZ4AH.js +0 -1
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.2.0 - 2026-10-16
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- `invokeDatabaseFunction` 现在按 Function ID 推断 `data` 类型。SQL Function 的 `data` 是 `{ rows: Row[] }`,而不是行数组;无可信行 Schema 时 `Row` 为 `unknown`。
|
|
8
|
+
- 未生成输出映射的 Function ID 在类型检查时被拒绝。FaaS 或 Mutation 没有输出 Schema 时,`data` 为 `unknown`,调用方不能再使用 `invokeDatabaseFunction<MyType>` 自行指定返回类型。
|
|
9
|
+
|
|
10
|
+
### Migration
|
|
11
|
+
|
|
12
|
+
升级已有工程的 SDK 后,先运行 `base-database-cli contracts generate` 更新生成类型,再删除直接调用时手写的返回泛型。SQL 调用读取 `result.data.rows`;FaaS/Mutation 对未知的业务结果先进行运行时校验或显式断言。旧 CLI 若未向输入类型生成流程传递 `functionType`,应升级配套 CLI 后再生成契约;只升级 CLI 而保留工程内的旧 SDK 不会启用新类型。
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
用于开发以飞书多维表格为数据后端的 Base Database 应用,提供页面与服务端运行时、平台组件、版本化能力查询与测试工具。
|
|
4
4
|
|
|
5
|
-
安装:`npm install @lark-base-open/base-database-app-sdk@0.0.1
|
|
5
|
+
安装:`npm install @lark-base-open/base-database-app-sdk@0.2.0`。从 0.1.0 升级前请阅读 [变更与迁移说明](CHANGELOG.md)。
|
|
6
6
|
|
|
7
7
|
运行环境需支持 ES2022;页面 API 需要 Base Database 页面宿主,服务端 API 用于 Node.js / FaaS。组件需要 React 与 React DOM 19.2,页面查询能力使用 @tanstack/react-query 5.104.1;npm 会安装声明的依赖与必需 peer。底层通信依赖 base-site-channel 0.1.6。
|
|
8
8
|
|
|
@@ -34,9 +34,9 @@ SDK 文档说明本版本 API、组件、兼容语义与可编译示例。业务
|
|
|
34
34
|
|
|
35
35
|
## npm 发布
|
|
36
36
|
|
|
37
|
-
SDK 0.0
|
|
37
|
+
SDK 0.2.0 依赖已发布的 channel 0.1.6,锁文件必须解析到 `registry.npmjs.org` 的制品。AI Function 调用需要后端与宿主支持 `functions/:key/invoke`。
|
|
38
38
|
|
|
39
|
-
|
|
39
|
+
本版本发布到 `latest`。契约生成使用工程安装的 SDK `./codegen` 入口;已安装旧 SDK 的工程不会因为单独升级 CLI 而自动切换到 0.2.0。0.2.0 对显式 Function 返回泛型有编译期破坏性变化,见 [迁移说明](CHANGELOG.md#020---2026-10-16)。
|
|
40
40
|
|
|
41
41
|
在本 SDK 目录按顺序执行以下发布前检查(`npm test` 包含构建、公开文档与包边界检查、类型和组件测试):
|
|
42
42
|
|
|
@@ -46,15 +46,15 @@ SDK 0.0.1-alpha.2 依赖已发布的 channel 0.1.6(`next`),锁文件必须
|
|
|
46
46
|
- `node scripts/sync-capabilities.mjs --check`
|
|
47
47
|
- `npm run docs:exports`
|
|
48
48
|
- `npm pack --dry-run --json`
|
|
49
|
-
- `npm publish --dry-run --tag
|
|
49
|
+
- `npm publish --dry-run --tag latest --registry=https://registry.npmjs.org/`
|
|
50
50
|
|
|
51
|
-
核对打包清单包含 dist、docs、examples、README、LICENSE、capabilities.json 与 development-pairing.json,以及所有 exports 指向的文件;不得包含测试、私有源码或本地配置。SDK 不提供根入口。
|
|
51
|
+
核对打包清单包含 dist、docs、examples、README、CHANGELOG、LICENSE、capabilities.json 与 development-pairing.json,以及所有 exports 指向的文件;不得包含测试、私有源码或本地配置。SDK 不提供根入口。
|
|
52
52
|
|
|
53
53
|
检查通过后,由有发布权限的用户本人执行;先确认 `npm whoami` 返回预期账号:
|
|
54
54
|
|
|
55
55
|
- `npm whoami --registry=https://registry.npmjs.org/`
|
|
56
|
-
- `npm publish --tag
|
|
57
|
-
- `npm view @lark-base-open/base-database-app-sdk@0.0
|
|
56
|
+
- `npm publish --tag latest --registry=https://registry.npmjs.org/`
|
|
57
|
+
- `npm view @lark-base-open/base-database-app-sdk@0.2.0 version dist --json --registry=https://registry.npmjs.org/`
|
|
58
58
|
- `npm view @lark-base-open/base-database-app-sdk dist-tags versions --json --registry=https://registry.npmjs.org/`
|
|
59
59
|
|
|
60
|
-
回读应确认 `
|
|
60
|
+
回读应确认 `latest` 为 `0.2.0`。
|
package/capabilities.json
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as Me,b as Q,c as Oe}from"./chunk-ZKBZAK4L.js";import{a as pe}from"./chunk-3JX3FIBG.js";import{a as F}from"./chunk-OHPYKFCM.js";import{createContext as Ht,useContext as Xe}from"react";import{createContext as Lt,useContext as Mt,useEffect as Ot,useSyncExternalStore as Ft}from"react";import{capabilityNames as Rt}from"@lark-base-open/base-site-channel/capabilities";import*as S from"@lark-base-open/base-site-channel/runtime";import{SITE_RUNTIME_PROTOCOL_VERSION as En,SiteRuntimeApi as ne,SiteRuntimeEvent as Un,SiteRuntimeFunction as Sn,SiteRuntimeErrorCode as Pn,readSiteAITextDelta as xn,isValidSiteFunctionName as kn}from"@lark-base-open/base-site-channel/runtime-contract";var V=()=>{throw new pe(Q.ContextInvalid,"\u5BBF\u4E3B\u80FD\u529B\u5B57\u6BB5\u65E0\u6548")};function me(e){if(!e||typeof e!="object")return V();if(e.capabilities===void 0)return Object.fromEntries(Object.entries(Me).filter(([,o])=>o.baseline).map(([o])=>[o,{version:1}]));let t=e.capabilities;if(!t||typeof t!="object"||Array.isArray(t))return V();let n=Object.entries(t);return n.some(([,o])=>!o||typeof o!="object"||Array.isArray(o)||!Number.isSafeInteger(o.version)||o.version<=0)?V():Object.fromEntries(n.map(([o,r])=>[o,{version:r.version}]))}function wt(e,t,n=1){if(!Number.isSafeInteger(n)||n<1)return V();let o=me(e);return Object.prototype.hasOwnProperty.call(o,t)&&o[t].version>=n}async function vt(e=E){return me(await e.getRuntimeContext())}var _n=vt;async function Ct(e,t=1,n=E){let o=await n.getRuntimeContext(),r=me(o),s=wt(o,e,t),a=o.capabilityUnavailable;if(a!==void 0&&(!a||typeof a!="object"||Array.isArray(a)))return V();let i=a&&Object.prototype.hasOwnProperty.call(a,e)?a[e]:void 0;return i!==void 0&&(!i||typeof i!="object"||!["permission-denied","region-unavailable","temporarily-unavailable"].includes(i.reason)||typeof i.retryable!="boolean")?V():{name:e,requiredVersion:t,version:Object.prototype.hasOwnProperty.call(r,e)?r[e].version:null,supported:s,source:o.capabilities===void 0?"host-baseline":"advertised",availability:s?i?.reason??"unknown":"unsupported"}}async function Fe(e,t=1,n=E){let o=await n.getRuntimeContext(),r=await Ct(e,t,{getRuntimeContext:async()=>o});if(!r.supported)throw new Oe(e,t);let s={"permission-denied":Q.PermissionDenied,"region-unavailable":Q.RegionUnavailable,"temporarily-unavailable":Q.TemporarilyUnavailable};if(r.availability in s)throw new pe(s[r.availability],"\u5BBF\u4E3B\u660E\u786E\u62D2\u7EDD\u6B64\u80FD\u529B",void 0,o.capabilityUnavailable?.[e]?.retryable)}function Ne(e,t){let n,o=!1,r,s=new Promise(a=>{r=a});return e.registerApi(F.pairApi,async a=>{if(!a||!/^[A-Za-z0-9_-]{43}$/.test(a.challenge))throw new Error("INVALID_PAIRING_CHALLENGE");n=a.challenge;let i=n;o&&(o=!1,s=new Promise(u=>{r=u}));let c=await t(F.endpoint,{method:"POST",credentials:"omit",cache:"no-store",redirect:"error",headers:{"Content-Type":"application/json"},body:JSON.stringify({challenge:i})});if(!c.ok)throw new Error("DEVELOPMENT_PAIRING_FAILED");let d=await c.json();if(!/^[A-Za-z0-9_-]{43}$/.test(d.proof))throw new Error("INVALID_PAIRING_PROOF");return{proof:d.proof}}),e.subscribeEvent(F.pairedEvent,a=>{n&&a?.challenge===n&&(o=!0,r())}),{reset:()=>{n=void 0,o&&(o=!1,s=new Promise(a=>{r=a}))},wait:async()=>{let a;do a=s,await a;while(a!==s)}}}var je=typeof window<"u"&&window.location.protocol==="http:"&&window.location.hostname===F.host&&Number(window.location.port)>=F.portMin&&Number(window.location.port)<=F.portMax;var $e=S.siteRuntime,T=$e.getChannel?.()??$e.channel,Et=je&&typeof window<"u"&&window.parent!==window?Ne(T,globalThis.fetch.bind(globalThis)):void 0;function Be(e,t=async()=>{}){let n=new Map,o=async(r,s)=>{await t();for(let a of Rt(r,s))try{await Fe(a,1,{getRuntimeContext:()=>e.invokeApi(ne.RuntimeContext,void 0)})}catch(i){throw i instanceof Error&&"code"in i?Object.assign(new S.SiteRuntimeInvocationError(String(i.code),i.message),i):i}};return{subscribeEvent:(r,s)=>e.subscribeEvent(r,s),emitEvent:async(r,s)=>(await o(r,s),e.emitEvent(r,s)),invokeApi:async(r,s,a)=>{let i=s?.requestId??s?.subscriptionId??s?.uploadId,c=r===ne.HttpRequestCancel||r===ne.AttachmentUploadCancel||r.endsWith(".close");if(c&&i&&n.has(i)){n.get(i).canceled=!0;return}let d={canceled:!1};!c&&i&&n.set(i,d);try{if(await o(r,s),d.canceled)throw new DOMException("The operation was aborted","AbortError");return i&&n.delete(i),await e.invokeApi(r,s,a)}finally{i&&n.get(i)===d&&n.delete(i)}}}}var Ut={invokeApi:T.invokeApi.bind(T),emitEvent:T.emitEvent.bind(T),subscribeEvent:T.subscribeEvent.bind(T)},ge=Be(Ut,async()=>{if(typeof window<"u"&&window.parent===window)throw new S.SiteRuntimeInvocationError("CHANNEL_UNAVAILABLE","\u9875\u9762\u672A\u8FDE\u63A5\u5BBF\u4E3B channel");await Et?.wait()});T.invokeApi=ge.invokeApi;T.emitEvent=ge.emitEvent;var fe=class extends S.SiteRuntimeClient{constructor(t){super(t?Be(t):ge)}},jn=e=>new fe(e),E=S.siteRuntime,{invokeHttp:oe,invokeApi:$n,getCurrentUser:Y,logout:he,requestEdit:St,uploadAttachment:Bn,openLink:re}=E,Pt=(e=E,t)=>S.createSiteRuntimeFetch(e,t),I=Pt();var xt=oe,kt=/^\/?(preview\/)?app\/([^/]+)(\/|$)/,He=/^[A-Za-z0-9_-]+$/,ze="/space/api/bitable/site/v1",At="/space/api/box/file/temporary_download_url",G="preview",W=null;function Tt(){let t=(typeof globalThis.location>"u"?void 0:globalThis.location)?.ancestorOrigins?.[0];if(t)return t;let n=typeof globalThis.document>"u"?"":globalThis.document.referrer;if(!n)return"";try{return new URL(n).origin}catch{return""}}function be(){let e=typeof globalThis.location>"u"?"":globalThis.location.pathname,t=kt.exec(e),n=Tt();return t?{env:t[1]?G:"prod",gatewayOrigin:n,token:decodeURIComponent(t[2]??"")}:{env:"prod",gatewayOrigin:n,token:""}}function Z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _t(e){return e===G||e==="prod"}function It(e){if(!Z(e))return{};let t=typeof e.siteToken=="string"?e.siteToken.trim():"";return{...t?{token:t}:{},..._t(e.env)?{env:e.env}:{}}}async function N(){return W||(W=(async()=>{let e=be(),t={};try{t=It(await E.getRuntimeContext())}catch(o){console.warn("Could not read the host Runtime context; inferring it from the artifact path",o)}let n={env:t.env??e.env,gatewayOrigin:e.gatewayOrigin,token:t.token??e.token};return n.token||console.error("Cannot determine the app token: the host did not provide siteToken and the current path does not match an artifact path"),n})().catch(e=>{throw W=null,e}),W)}function ye(e){return!!(e.tableId.trim()&&e.fieldId.trim()&&e.recordId.trim()&&e.fileToken.trim())}function qe(e,t){return JSON.stringify({bitablePerm:{tableId:t.tableId,attachments:{[t.fieldId]:{[t.recordId]:[t.fileToken]}},siteToken:e.token,siteEnv:e.env}})}function Ve(e,t){if(t instanceof Error)return t;let n=Z(t)?t.code:void 0,o=typeof n=="string"||typeof n=="number"?String(n):"",r=o==="REQUEST_TIMEOUT"||o==="10005"?`${e} timed out`:`${e} failed`;return Object.assign(new Error(`${r}${o?` (code ${o})`:""}`),{cause:t,...o?{code:o}:{}})}async function Ge(e,t=360,n={}){if(n.signal?.throwIfAborted(),!ye(e)||!Number.isFinite(t)||t<=0)throw new Error("Attachment location or image size is invalid");let o=await N();if(n.signal?.throwIfAborted(),!o.token)throw new Error("Cannot load the attachment image without an app token");let r=[120,360,720,1280].find(c=>c>=t)??1280,s=new URLSearchParams({extra:qe(o,e),width:String(r),height:String(r),policy:"allow_up",fallback_source:"1"}),a=await xt({url:`/space/api/box/stream/download/v2/cover/${encodeURIComponent(e.fileToken)}?${s}`,init:{method:"GET",responseType:"arrayBuffer",timeoutMs:45e3},signal:n.signal}).catch(c=>{throw Ve("Attachment image request",c)});if(!a.ok){let c=a.headers.get("x-tt-logid");throw new Error(`Failed to load attachment image: HTTP ${a.status}${c?`, LogID ${c}`:""}`)}let i=await a.blob();if(!i.size||!i.type.startsWith("image/"))throw new Error("The host did not return a valid image");return i}async function Dt(e,t){if(!e.token)throw new Error("Cannot get an attachment download URL without an app token");if(!ye(t))throw new Error("Cannot get an attachment download URL: the attachment location is incomplete");let n=await I(At,{body:JSON.stringify({extra:qe(e,t),file_token:t.fileToken}),headers:{"content-type":"application/json"},method:"POST"}).catch(i=>{throw Ve("Attachment download URL request",i)}),o=n.headers?.get("x-tt-logid")?.trim(),r;try{r=await n.json()}catch{throw new Error(n.ok?`Attachment download URL response is not valid JSON${o?`, LogID ${o}`:""}`:`Failed to get attachment download URL: HTTP ${n.status}${o?`, LogID ${o}`:""}`)}let s=Z(r)?r.code:void 0;if(typeof s=="number"&&s!==0||typeof s=="string"&&s.trim()!==""&&s.trim()!=="0"){let i=new Error(`Attachment service could not provide a download URL (code ${String(s)}${o?`, LogID ${o}`:""})`);throw Object.assign(i,{code:String(s),cause:r})}if(!n.ok)throw new Error(`Failed to get attachment download URL: HTTP ${n.status}${o?`, LogID ${o}`:""}`);let a=Z(r)&&Z(r.data)&&typeof r.data.url=="string"?r.data.url.trim():"";if(!a)throw new Error(`Attachment download URL response is missing data.url${o?`, LogID ${o}`:""}`);return a}function Je(e){let t=new URLSearchParams;e.env===G&&t.set("env",G);let n=t.toString(),o=`${ze}/${encodeURIComponent(e.token)}/invoke_get`;return n?`${o}?${n}`:o}function Ke(e,t){if(!He.test(t))throw new TypeError(`functionId ${t} does not match the required pattern ${String(He)}`);let n=`${ze}/${encodeURIComponent(e.token)}/functions/${encodeURIComponent(t)}/invoke`;return e.env===G?`${n}?env=${encodeURIComponent(G)}`:n}async function qn(e,t){let n=await N();if(!n.token)throw new Error(`Cannot invoke Function ${e} without an app token`);let o=await oe({url:Ke(n,e),init:{body:JSON.stringify({params:t}),headers:{"content-type":"application/json"},method:"POST"}});if(!o.ok)throw new Error(`Function ${e} request failed: HTTP ${o.status}`);return await o.json()}async function Vn(e,t){if(!Array.isArray(t)||t.length<1||t.length>200||t.some(r=>r===null||typeof r!="object"||Array.isArray(r)))throw new TypeError("Mutation batch requires 1 to 200 named parameter objects");let n=await N();if(!n.token)throw new Error("\u5E94\u7528 token \u672A\u786E\u5B9A\uFF0C\u65E0\u6CD5\u8C03\u7528 Mutation");let o=await oe({url:Ke(n,e),init:{body:JSON.stringify({batch:t.map(r=>({params:r}))}),headers:{"content-type":"application/json"},method:"POST"}});if(!o.ok)throw new Error(`Mutation \u8C03\u7528\u5931\u8D25\uFF1AHTTP ${o.status}`);return await o.json()}async function Gn(e,t){let n=await Dt(e,t);if(!(await re(n)).opened)throw new Error("The host did not open the attachment download link")}function Jn(e,t,n=360){if(!e.gatewayOrigin||!e.token||!ye(t))return"";let o=[120,360,720,1280].find(s=>s>=n)??1280,r=new URLSearchParams({extra:JSON.stringify({bitablePerm:{tableId:t.tableId,attachments:{[t.fieldId]:{[t.recordId]:[t.fileToken]}},baseAppToken:e.token}}),width:String(o),height:String(o),policy:"allow_up",fallback_source:"1"});return`${e.gatewayOrigin}/space/api/box/stream/download/v2/cover/${encodeURIComponent(t.fileToken)}?${r.toString()}`}var Re=Lt(void 0),Ye=[{id:"en",locale:"en-US",match:/^en(?:-|$)/},{id:"zh",locale:"zh-CN",match:/^zh(?:-|$)/},{id:"ja",locale:"ja-JP",match:/^ja(?:-|$)/}],ve=new Set,We,we=null;function Ce(e){if(typeof e!="string")return;let t=e.trim().replace(/_/g,"-").toLowerCase();return Ye.find(({match:n})=>n.test(t))?.id}function Nt(){return typeof navigator>"u"?void 0:navigator.language}function jt(e,t){return Ce(e)??Ce(t)??"en"}function j(){return We??jt(void 0,Nt())}function Ee(e=j()){return Ye.find(({id:t})=>t===e)?.locale??"en-US"}function $t(e){return ve.add(e),()=>ve.delete(e)}function Qe(e){We=Ce(e);let t=j();Ze(t);for(let n of ve)n();return t}function Ze(e){typeof document<"u"&&(document.documentElement.lang=Ee(e))}function Bt(){return we||(Ze(j()),we=E.getRuntimeContext().then(e=>Qe(e?.locale)).catch(()=>Qe(void 0))),we}function P(){let e=Mt(Re),t=Ft($t,j,()=>"en");return Ot(()=>{e||Bt()},[e]),e??t}import{jsx as Ue}from"react/jsx-runtime";var Se=Ht(null);function no({children:e,...t}){return Ue(Se.Provider,{value:t,children:Ue(Re.Provider,{value:t.locale,children:Ue("div",{className:"base-app-platform","data-theme":t.theme,children:e})})})}function oo(){let e=Xe(Se);if(!e)throw new Error("BASE_APP_PROVIDER_REQUIRED");return e}function ae(){return Xe(Se)}import{useState as X,useEffect as nt}from"react";import{QueryClient as zt}from"@tanstack/react-query";var Pe=new zt({defaultOptions:{queries:{retry:!1,staleTime:3e4,gcTime:3e4}}});function ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function se(e,t){let n=e[t];return typeof n=="string"?n.trim():""}function qt(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function $(){return{baseBindings:[],name:"",description:"",isOwner:!1,allowEdit:!1,organization:""}}function Vt(){let e=document.querySelector('meta[name="description"]');return e instanceof HTMLMetaElement?e:null}function Gt(e){if(e.name&&(document.title=e.name),e.description){let t=Vt();t&&(t.content=e.description)}}function Jt(e){return Array.isArray(e)?e.reduce((t,n)=>{if(!ie(n))return t;let o=se(n,"baseToken");return o&&t.push({baseToken:o,tableIds:qt(n.tableIds)}),t},[]):[]}function Kt(e){if(!ie(e)||e.code!==0)return $();let t=e.data;if(!ie(t))return $();let n=t.site;return ie(n)?{baseBindings:Jt(n.baseBindings),description:se(n,"description"),name:se(n,"name"),isOwner:t.isOwner===!0,allowEdit:n.allowEdit===void 0?t.isOwner===!0:n.allowEdit===!0,organization:se(n,"organization")}:$()}async function et(e){try{let t=await I(Je(e),{method:"GET"});if(!t.ok)return $();let n=await t.json(),o=Kt(n);return Gt(o),o}catch{return $()}}async function J(){let e=await N();if(!e.token)return $();let t=await Y().catch(()=>null);return t?.userId?Pe.fetchQuery({queryKey:["project-meta",e.token,e.env,t.userId],queryFn:()=>et(e)}):et(e)}var Qt="https://feishu.cn/base/site/detail/overview";async function tt(){try{await E.requestEdit();return}catch{let{token:e}=await N(),t=new URL(Qt);if(t.searchParams.set("token",e),!(await re(t.toString())).opened)throw new Error("Management page was not opened")}}import{jsx as B,jsxs as ot}from"react/jsx-runtime";var Yt={en:{openFailed:"Unable to open the management page. Please try again.",editSite:"Edit and manage your apps",hidePanel:"Hide until next visit",hiddenConfirmation:"Edit button hidden until you reopen the app",dismissNotification:"Dismiss notification"},zh:{openFailed:"\u65E0\u6CD5\u6253\u5F00\u7BA1\u7406\u9875\u9762\uFF0C\u8BF7\u91CD\u8BD5",editSite:"\u7F16\u8F91\u4E0E\u7BA1\u7406\u5E94\u7528",hidePanel:"\u9690\u85CF\u9762\u677F",hiddenConfirmation:"\u7F16\u8F91\u6309\u94AE\u5DF2\u9690\u85CF\uFF0C\u76F4\u81F3\u4E0B\u6B21\u91CD\u65B0\u6253\u5F00\u5E94\u7528",dismissNotification:"\u5173\u95ED\u63D0\u793A"},ja:{openFailed:"\u7BA1\u7406\u30DA\u30FC\u30B8\u3092\u958B\u3051\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u3082\u3046\u4E00\u5EA6\u304A\u8A66\u3057\u304F\u3060\u3055\u3044\u3002",editSite:"\u30A2\u30D7\u30EA\u3092\u7DE8\u96C6\u30FB\u7BA1\u7406",hidePanel:"\u6B21\u56DE\u306E\u30A2\u30AF\u30BB\u30B9\u307E\u3067\u975E\u8868\u793A",hiddenConfirmation:"\u7DE8\u96C6\u30DC\u30BF\u30F3\u3092\u975E\u8868\u793A\u306B\u3057\u307E\u3057\u305F\u3002\u30A2\u30D7\u30EA\u3092\u518D\u5EA6\u958B\u304F\u3068\u8868\u793A\u3055\u308C\u307E\u3059",dismissNotification:"\u901A\u77E5\u3092\u9589\u3058\u308B"}};function vo({position:e="bottom-right",className:t="",slots:n={}}){let o=Yt[P()],[r,s]=X(!1),[a,i]=X(!1),[c,d]=X(!1),[u,p]=X(!1),[g,f]=X(!1);nt(()=>{let b=!0;return J().then(M=>{b&&s(M.allowEdit&&be().env==="prod")}).catch(()=>{}),()=>{b=!1}},[]),nt(()=>{if(!c)return;let b=setTimeout(()=>d(!1),3e3);return()=>clearTimeout(b)},[c]);let m=n.trigger,v=n.tooltip;return r?a?c?ot("div",{className:"base-app-platform base-app-notice",role:"status",children:[o.hiddenConfirmation,B("button",{"aria-label":o.dismissNotification,onClick:()=>d(!1),children:"\xD7"})]}):null:ot("div",{className:`base-app-platform base-app-floating ${t}`,"data-position":e,children:[u?B("div",{role:"alert",children:o.openFailed}):null,g?B("div",{role:"tooltip",children:v?B(v,{text:o.editSite}):o.editSite}):null,B("button",{"aria-label":o.editSite,onFocus:()=>f(!0),onBlur:()=>f(!1),onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),onClick:()=>{p(!1),tt().catch(()=>p(!0))},children:m?B(m,{}):"\u270E"}),B("button",{"aria-label":o.hidePanel,onClick:()=>{i(!0),d(!0)},children:"\xD7"})]}):null}var xe=new Set;function rt(e){return xe.add(e),()=>{xe.delete(e)}}function at(){for(let e of xe)e()}import{useEffect as Wt,useState as st}from"react";import*as D from"@radix-ui/react-popover";async function it(){try{let e=await Y();if(typeof e?.name=="string"&&e.name)return{name:e.name,avatarUrl:typeof e.avatarUrl=="string"?e.avatarUrl:"",tenantName:""}}catch{}try{let e=await I("/space/api/user/",{headers:{accept:"application/json"}});if(!e.ok)return null;let n=(await e.json()).data;return!n||typeof n.name!="string"||!n.name?null:{name:n.name,avatarUrl:typeof n.avatar_url=="string"?n.avatar_url:"",tenantName:typeof n.tenant_name=="string"?n.tenant_name:""}}catch{return null}}import{Fragment as Xt,jsx as x,jsxs as ke}from"react/jsx-runtime";var Zt={en:{account:"Account",logout:"Log out"},zh:{account:"\u8D26\u53F7",logout:"\u9000\u51FA\u767B\u5F55"},ja:{account:"\u30A2\u30AB\u30A6\u30F3\u30C8",logout:"\u30ED\u30B0\u30A2\u30A6\u30C8"}};function Lo({audience:e="enterprise",align:t="right",side:n="down",showName:o=!0,className:r="",slots:s={}}){let[a,i]=st(null),[c,d]=st(""),u=ae(),p=Zt[P()];if(Wt(()=>{if(e!=="enterprise")return;let m=!0;return Promise.all([it(),J().catch(()=>null)]).then(([v,b])=>{m&&(i(v),d(v?.tenantName||b?.organization||""))}),()=>{m=!1}},[e]),e!=="enterprise"||!a)return null;let g=s.trigger,f=s.organization;return ke(D.Root,{children:[x(D.Trigger,{asChild:!0,children:x("button",{className:`base-app-platform base-app-user-menu ${r}`,"aria-label":p.account,children:g?x(g,{user:a}):ke(Xt,{children:[a.avatarUrl?x("img",{src:a.avatarUrl,alt:"",referrerPolicy:"no-referrer"}):x("span",{children:a.name.slice(0,1)}),o?a.name:null]})})}),x(D.Portal,{children:ke(D.Content,{"data-theme":u?.theme,className:"base-app-platform base-app-popover",align:t==="right"?"end":"start",side:n==="up"?"top":"bottom",sideOffset:8,collisionPadding:8,children:[x("strong",{children:a.name}),f?x(f,{name:c}):x("p",{children:c}),x("button",{onClick:()=>{at(),Pe.clear(),he().catch(()=>{for(let m of["base-site-session","session","sl_session"])document.cookie=`${m}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;window.location.reload()})},children:p.logout})]})})]})}import{useEffect as ce,useRef as dt,useState as z}from"react";import{Command as ee}from"cmdk";import{QueryClient as dn,useQuery as pn}from"@tanstack/react-query";var en="/space/api/mention/recommend.v2/",tn="8",nn="4",on="0",rn=20,ct={en:{businessError:e=>`Could not search members (error code ${e})`,httpError:e=>`Member search request failed: HTTP ${e}`,invalidResponse:"Member search response has an invalid structure",noBoundBase:"Cannot search members: the application is not bound to a Base"},zh:{businessError:e=>`\u641C\u7D22\u6210\u5458\u5931\u8D25\uFF08\u9519\u8BEF\u7801 ${e}\uFF09`,httpError:e=>`\u641C\u7D22\u6210\u5458\u8BF7\u6C42\u5931\u8D25\uFF1AHTTP ${e}`,invalidResponse:"\u6210\u5458\u641C\u7D22\u54CD\u5E94\u7ED3\u6784\u65E0\u6548",noBoundBase:"\u65E0\u6CD5\u641C\u7D22\u6210\u5458\uFF1A\u5E94\u7528\u5C1A\u672A\u7ED1\u5B9A\u591A\u7EF4\u8868\u683C"},ja:{businessError:e=>`\u30E1\u30F3\u30D0\u30FC\u3092\u691C\u7D22\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08\u30A8\u30E9\u30FC\u30B3\u30FC\u30C9 ${e}\uFF09`,httpError:e=>`\u30E1\u30F3\u30D0\u30FC\u691C\u7D22\u306E\u30EA\u30AF\u30A8\u30B9\u30C8\u306B\u5931\u6557\u3057\u307E\u3057\u305F\uFF1AHTTP ${e}`,invalidResponse:"\u30E1\u30F3\u30D0\u30FC\u691C\u7D22\u306E\u5FDC\u7B54\u5F62\u5F0F\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093",noBoundBase:"\u30E1\u30F3\u30D0\u30FC\u3092\u691C\u7D22\u3067\u304D\u307E\u305B\u3093\uFF1A\u30A2\u30D7\u30EA\u306BBase\u304C\u95A2\u9023\u4ED8\u3051\u3089\u308C\u3066\u3044\u307E\u305B\u3093"}};async function lt(e,t,n){let o=t??j(),r=ct[o],a=(await J()).baseBindings[0]?.baseToken;if(!a)throw new Error(r.noBoundBase);let i=new URLSearchParams({config_source:"0",obj_type:tn,source:nn,token:a,type:on,user_type:"0",content:e.trim().slice(0,50)}).toString(),c=await I(en,{signal:n,body:i,headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST"});if(!c.ok)throw new Error(r.httpError(c.status));let d=await c.json();return{code:0,msg:"ok",data:an(d,o)}}function an(e,t=j()){let n=Ee(t),o=ct[t],r=sn(e,o);if(!r)throw new Error(o.invalidResponse);let s=r.entities,a=H(s)?s.users:void 0;if(!H(a)||!Array.isArray(r.result_list))throw new Error(o.invalidResponse);let i=[],c=new Set;for(let d of r.result_list){if(!H(d)||Number(d.type)!==0)continue;let u=h(d.token);if(!u)continue;let p=a[u];if(!H(p))continue;let g=h(p.user_id)||h(p.id)||u,f=cn(p,n);if(!g||!f||c.has(g))continue;c.add(g);let m=h(p.avatar_url),v=h(p.open_id);if(i.push({avatar:{avatar_72:m,avatar_240:m,avatar_640:m,avatar_origin:m},department_ids:un(p.department_ids),description:ln(p,n),is_external:p.is_external===!0,name:f,user_id:g,...v?{open_id:v}:{}}),i.length>=rn)break}return{users:i}}function sn(e,t){if(H(e)){if(typeof e.code=="number"&&e.code!==0){let n=h(e.msg);throw Object.assign(new Error(n||t.businessError(e.code)),{code:String(e.code),cause:e})}return"entities"in e&&"result_list"in e?e:H(e.data)?e.data:void 0}}function cn(e,t){return ut(e.display_name,t)||(t.toLowerCase().startsWith("zh")?h(e.cn_name):h(e.en_name))||h(e.name)||h(e.en_name)||h(e.cn_name)}function ln(e,t){let n=e.is_external===!0?e.i18n_tenant:e.i18n_department;return ut(n,t)||h(e.department)}function ut(e,t){if(typeof e=="string")return e.trim();if(!H(e))return"";let n=t.toLowerCase().replace("-","_"),o=n.split("_")[0]??"",r=o==="zh"?h(e.zh_cn)||h(e.en_us):h(e.en_us)||h(e.zh_cn);return h(e[n])||h(e[o])||r}function h(e){return typeof e=="string"?e.trim():""}function un(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{Fragment as mt,jsx as R,jsxs as Ae}from"react/jsx-runtime";var ft={en:{invalidResponse:"Member search response has an invalid structure",loading:"Loading...",memberList:"Member list",noMatches:"No matching members. Try another search term.",noRecommendations:"No recommended members yet",recordCreator:"Add the person who created this record",searchFailed:"Member search failed",searchFailedCode:e=>`Could not search members (error code ${e})`,searchMembers:"Search members"},zh:{invalidResponse:"\u6210\u5458\u641C\u7D22\u54CD\u5E94\u7ED3\u6784\u65E0\u6548",loading:"\u52A0\u8F7D\u4E2D...",memberList:"\u6210\u5458\u5217\u8868",noMatches:"\u6CA1\u6709\u5339\u914D\u7684\u6210\u5458\uFF0C\u8BF7\u6362\u4E2A\u5173\u952E\u8BCD",noRecommendations:"\u6682\u65E0\u63A8\u8350\u6210\u5458",recordCreator:"\u6DFB\u52A0\u6B64\u8BB0\u5F55\u7684\u4EBA\u5458",searchFailed:"\u641C\u7D22\u6210\u5458\u5931\u8D25",searchFailedCode:e=>`\u641C\u7D22\u6210\u5458\u5931\u8D25\uFF08\u9519\u8BEF\u7801 ${e}\uFF09`,searchMembers:"\u641C\u7D22\u6210\u5458"},ja:{invalidResponse:"\u30E1\u30F3\u30D0\u30FC\u691C\u7D22\u306E\u5FDC\u7B54\u5F62\u5F0F\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093",loading:"\u8AAD\u307F\u8FBC\u307F\u4E2D...",memberList:"\u30E1\u30F3\u30D0\u30FC\u4E00\u89A7",noMatches:"\u4E00\u81F4\u3059\u308B\u30E1\u30F3\u30D0\u30FC\u304C\u3044\u307E\u305B\u3093\u3002\u5225\u306E\u30AD\u30FC\u30EF\u30FC\u30C9\u3067\u691C\u7D22\u3057\u3066\u304F\u3060\u3055\u3044\u3002",noRecommendations:"\u304A\u3059\u3059\u3081\u306E\u30E1\u30F3\u30D0\u30FC\u304C\u3044\u307E\u305B\u3093",recordCreator:"\u3053\u306E\u30EC\u30B3\u30FC\u30C9\u306E\u4F5C\u6210\u8005\u3092\u8FFD\u52A0",searchFailed:"\u30E1\u30F3\u30D0\u30FC\u306E\u691C\u7D22\u306B\u5931\u6557\u3057\u307E\u3057\u305F",searchFailedCode:e=>`\u30E1\u30F3\u30D0\u30FC\u3092\u691C\u7D22\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08\u30A8\u30E9\u30FC\u30B3\u30FC\u30C9 ${e}\uFF09`,searchMembers:"\u30E1\u30F3\u30D0\u30FC\u3092\u691C\u7D22"}};function le(e){let[t,n]=z(!1),[o,r]=z(!1);ce(()=>r(!0),[]);let s=P(),a=ft[s],[i]=z(()=>new dn({defaultOptions:{queries:{retry:!1,staleTime:3e4,gcTime:3e4}}}));ce(()=>{let l=rt(()=>{n(!0),i.clear()});return()=>{l(),i.clear()}},[i]);let c=Object.prototype.hasOwnProperty.call(e,"value"),d=dt(c);ce(()=>{c!==d.current&&console.warn("UserSelectorPanel controlled mode changed")},[c]);let[u,p]=z(e.defaultValue),g=c?e.value:u,f=Array.isArray(g)?g:g?[g]:[],[m,v]=z(""),[b,M]=z(""),[k,K]=z(!1),O=dt(!1);ce(()=>{if(k)return;let l=setTimeout(()=>M(m.trim()),m.trim()?400:0);return()=>clearTimeout(l)},[m,k]);let y=pn({queryKey:["members",s,b],queryFn:async({signal:l})=>{let C=await lt(b,s,l);return mn(C,s)},enabled:!t&&o&&!k&&m.trim()===b},i),w=e.loading||y.isFetching||m.trim()!==b,A=!t&&!w&&!y.error&&y.data?[...y.data.users,...f.filter(l=>!y.data.users.some(C=>C.user_id===l.user_id))]:[],U=(l,C)=>{v(l),e.onSearch?.(l,{action:C})},ue=()=>{U("","AutoClear"),e.onClose?.()},yt=l=>{if(O.current)return;let C=f.some(de=>de.user_id===l.user_id),te=e.mode==="multiple"?C?f.filter(de=>de.user_id!==l.user_id):[...f,l]:C?void 0:l;c||p(te),e.onChange?.(te,{option:l,action:C?"Remove":"Select"}),C||e.onSelect?.(l,{option:l}),e.mode==="multiple"?U("","AutoClear"):ue()},_e=e.slots?.empty,Ie=e.slots?.loading,De=e.slots?.option,Le=e.slots?.footer;return Ae(ee,{shouldFilter:!1,loop:!0,className:`base-app-platform base-app-selector ${e.className??""}`,label:a.memberList,children:[R(ee.Input,{autoFocus:!0,placeholder:a.searchMembers,"aria-label":a.searchMembers,value:m,onValueChange:l=>U(l,"Input"),onCompositionStart:()=>{O.current=!0,K(!0)},onCompositionEnd:()=>{O.current=!1,K(!1)},onKeyDown:l=>{if(e.onKeyDown?.(l),l.defaultPrevented){l.stopPropagation();return}if(O.current||fn(l)){l.stopPropagation();return}l.key==="Escape"&&(l.preventDefault(),ue())}}),R(ee.List,{"aria-label":a.memberList,"aria-multiselectable":e.mode==="multiple"||void 0,children:w?R("div",{role:"status",children:Ie?R(Ie,{}):a.loading}):y.error?R("div",{role:"alert",children:a.searchFailed}):Ae(mt,{children:[e.onSelectRecordCreator?R(ee.Item,{value:"record-creator",onSelect:()=>{e.onSelectRecordCreator?.(),ue()},children:a.recordCreator}):null,A.map(l=>{let C=f.some(te=>te.user_id===l.user_id);return R(ee.Item,{value:l.user_id,onSelect:()=>yt(l),"data-checked":C,children:De?R(De,{user:l,selected:C}):Ae(mt,{children:[R("span",{children:l.name}),R("small",{children:e.getUserDescription?.(l)??l.description}),C?R("span",{"aria-label":"selected",children:"\u2713"}):null]})},l.user_id)}),!A.length&&!e.onSelectRecordCreator?R("div",{role:"status",children:_e?R(_e,{}):m.trim()?a.noMatches:a.noRecommendations}):null]})}),Le?R(Le,{}):null]})}function mn(e,t){let n=ft[t];if(!pt(e)||typeof e.code!="number")throw new Error(n.invalidResponse);if(e.code!==0){let o=typeof e.msg=="string"?e.msg.trim():"";throw Object.assign(new Error(o||n.searchFailedCode(e.code)),{code:String(e.code),cause:e})}if(!pt(e.data)||!Array.isArray(e.data.users))throw new Error(n.invalidResponse);return{users:e.data.users}}function pt(e){return typeof e=="object"&&e!==null}function fn(e){return e.nativeEvent?.isComposing===!0||e.keyCode===229}import{useState as gn,useRef as hn}from"react";import*as L from"@radix-ui/react-popover";import{jsx as _,jsxs as gt}from"react/jsx-runtime";var bn={en:{clearSelected:"Clear selected members",removeMember:e=>`Remove member ${e}`,selectMembers:"Select members"},zh:{clearSelected:"\u6E05\u9664\u5DF2\u9009\u6210\u5458",removeMember:e=>`\u79FB\u9664\u6210\u5458 ${e}`,selectMembers:"\u9009\u62E9\u6210\u5458"},ja:{clearSelected:"\u9078\u629E\u3057\u305F\u30E1\u30F3\u30D0\u30FC\u3092\u30AF\u30EA\u30A2",removeMember:e=>`\u30E1\u30F3\u30D0\u30FC ${e} \u3092\u524A\u9664`,selectMembers:"\u30E1\u30F3\u30D0\u30FC\u3092\u9078\u629E"}};function ht(e){let t=hn(null),n=ae(),o=bn[P()],[r,s]=gn(!1),a=Array.isArray(e.value)?e.value:e.value?[e.value]:[],i=u=>{s(u),u!==r&&e.onDropdownVisibleChange?.(u)},c=e.slots?.trigger,d=e.slots?.chip;return gt(L.Root,{open:r,onOpenChange:i,children:[gt("div",{ref:t,className:`base-app-platform base-app-editor ${e.className??""}`,onClickCapture:u=>{u.target.closest("[data-base-app-trigger]")&&e.onClick?.(u)},children:[_(L.Trigger,{asChild:!0,children:_("button",{type:"button","data-base-app-trigger":"","aria-label":o.selectMembers,onFocus:e.onFocus,onBlur:e.onBlur,children:c?_(c,{value:e.value}):a.length?a.map(u=>_("span",{children:d?_(d,{user:u}):u.name},u.user_id)):o.selectMembers})}),a.map(u=>_("button",{type:"button","aria-label":e.mode==="multiple"?o.removeMember(u.name):o.clearSelected,onClick:p=>{p.stopPropagation(),e.onChange?.(e.mode==="multiple"?a.filter(g=>g.user_id!==u.user_id):void 0),e.mode==="multiple"?e.onRemove?.(u):e.onClear?.()},children:"\xD7"},u.user_id))]}),_(L.Portal,{container:e.portalContainer??t.current?.closest("dialog")??void 0,children:_(L.Content,{"data-theme":n?.theme,className:"base-app-platform base-app-popover",sideOffset:4,collisionPadding:8,children:_(le,{...e,slots:void 0,onChange:(u,p)=>{e.onChange?.(u),p.action==="Remove"&&p.option&&e.onRemove?.(p.option)},onClose:()=>i(!1)})})})]})}import{useEffect as bt,useRef as yn,useState as Te}from"react";import{jsx as q,jsxs as vn}from"react/jsx-runtime";var wn={en:{decodeFailed:"Image could not be decoded",loadFailed:"Failed to load image",loading:"Loading image",retry:"Retry image"},zh:{decodeFailed:"\u56FE\u7247\u65E0\u6CD5\u89E3\u7801",loadFailed:"\u56FE\u7247\u52A0\u8F7D\u5931\u8D25",loading:"\u56FE\u7247\u52A0\u8F7D\u4E2D",retry:"\u91CD\u8BD5\u56FE\u7247"},ja:{decodeFailed:"\u753B\u50CF\u3092\u8868\u793A\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F",loadFailed:"\u753B\u50CF\u3092\u8AAD\u307F\u8FBC\u3081\u307E\u305B\u3093\u3067\u3057\u305F",loading:"\u753B\u50CF\u3092\u8AAD\u307F\u8FBC\u307F\u4E2D",retry:"\u753B\u50CF\u3092\u518D\u8AAD\u307F\u8FBC\u307F"}};function ir({attachment:e,size:t=360,alt:n,className:o,slots:r={}}){let s=P(),a=wn[s],i=yn(null),[c,d]=Te(!1),[u,p]=Te(0),[g,f]=Te({key:"",url:"",error:""}),{tableId:m,fieldId:v,recordId:b,fileToken:M}=e,k=JSON.stringify([m,v,b,M,t,u]);bt(()=>{if(typeof IntersectionObserver>"u"){d(!0);return}let w=new IntersectionObserver(A=>{A.some(U=>U.isIntersecting)&&(d(!0),w.disconnect())},{rootMargin:"200px"});return i.current&&w.observe(i.current),()=>w.disconnect()},[]),bt(()=>{if(!c)return;let w=new AbortController,A="";return Ge({tableId:m,fieldId:v,recordId:b,fileToken:M},t,{signal:w.signal}).then(U=>{w.signal.aborted||(A=URL.createObjectURL(U),f({key:k,url:A,error:""}))}).catch(U=>{w.signal.aborted||f({key:k,url:"",error:U instanceof Error?U.message:"",localError:U instanceof Error?void 0:"loadFailed"})}),()=>{w.abort(),A&&URL.revokeObjectURL(A)}},[c,k,m,v,b,M,t]);let K=r.loading,O=r.error,y=g.key===k?g:void 0;return q("span",{ref:i,className:`base-app-platform base-app-attachment ${o??""}`,"aria-busy":!y,children:y?.url?q("img",{src:y.url,alt:n,onError:()=>f({key:k,url:"",error:"",localError:"decodeFailed"})}):y?.error||y?.localError?O?q(O,{code:"ATTACHMENT_LOAD_FAILED",retry:()=>p(w=>w+1)}):vn("span",{children:[q("span",{role:"status",children:y.localError?a[y.localError]:y.error}),q("button",{type:"button",onClick:()=>p(w=>w+1),children:a.retry})]}):q("span",{role:"status",children:K?q(K,{}):a.loading})})}export{En as a,ne as b,Un as c,Sn as d,Pn as e,xn as f,kn as g,Be as h,ge as i,fe as j,jn as k,E as l,oe as m,$n as n,Y as o,he as p,St as q,Bn as r,re as s,Pt as t,I as u,me as v,wt as w,vt as x,_n as y,Ct as z,Fe as A,be as B,N as C,Ge as D,Dt as E,Je as F,Ke as G,qn as H,Vn as I,Gn as J,Jn as K,Re as L,jt as M,j as N,Ee as O,Bt as P,P as Q,no as R,oo as S,ae as T,Pe as U,vo as V,Lo as W,le as X,ht as Y,ir as Z};
|
package/dist/codegen.cjs
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var A=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var E=(n,e)=>{for(var o in e)A(n,o,{get:e[o],enumerable:!0})},_=(n,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of R(e))!x.call(n,t)&&t!==o&&A(n,t,{get:()=>e[t],enumerable:!(r=C(e,t))||r.enumerable});return n};var D=n=>_(A({},"__esModule",{value:!0}),n);var V={};E(V,{CodegenError:()=>m,SUPPORTED_CONTRACT_FORMAT_VERSIONS:()=>U,generateFunctionClients:()=>L,validateContractData:()=>F});module.exports=D(V);var T=require("json-schema-to-typescript");function p(n,e){if(!n||typeof n!="object"||Array.isArray(n))return;let o=n;e(o);for(let t of["properties","patternProperties","$defs","definitions","dependentSchemas"]){let s=o[t];if(s&&typeof s=="object"&&!Array.isArray(s))for(let a of Object.values(s))p(a,e)}for(let t of["items","additionalItems","additionalProperties","unevaluatedProperties","unevaluatedItems","contains","propertyNames","not","if","then","else"]){let s=o[t];Array.isArray(s)?s.forEach(a=>p(a,e)):p(s,e)}for(let t of["allOf","anyOf","oneOf","prefixItems"])Array.isArray(o[t])&&o[t].forEach(s=>p(s,e));let r=o.dependencies;if(r&&typeof r=="object"&&!Array.isArray(r))for(let t of Object.values(r))Array.isArray(t)||p(t,e)}function l(n){if(!n||typeof n!="object"||Array.isArray(n)||Buffer.byteLength(JSON.stringify(n))>32768)throw new Error("CONTRACT_SCHEMA_BUDGET");let e=0,o=(r,t)=>{if(!(!r||typeof r!="object")){if(++e>256||t>16)throw new Error("CONTRACT_SCHEMA_BUDGET");Object.values(r).forEach(s=>o(s,t+1))}};o(n,0),p(n,r=>{if(Object.hasOwn(r,"$ref")&&(typeof r.$ref!="string"||!r.$ref.startsWith("#/")))throw new Error("CONTRACT_EXTERNAL_REF");if(["$id","$dynamicRef","$recursiveRef","tsType","tsEnumNames"].some(t=>Object.hasOwn(r,t)))throw new Error("CONTRACT_EXTERNAL_REF")})}var y="@lark-base-open/base-database-app-sdk/page",b=`/* Generated by base-database-cli. Do not edit. */
|
|
2
2
|
import type { DatabaseFunctionInputMap as GeneratedInputMap } from './database-function-inputs.generated';
|
|
3
|
-
import '${
|
|
4
|
-
declare module '${
|
|
3
|
+
import '${y}';
|
|
4
|
+
declare module '${y}' { interface FunctionInputMap extends GeneratedInputMap {} }
|
|
5
5
|
`,O=`/* Generated by base-database-cli. Map is declared in ../generated/functions. */
|
|
6
6
|
export {};
|
|
7
|
-
`;async function
|
|
8
|
-
export type ${
|
|
9
|
-
|
|
7
|
+
`;async function h(n,e){l(n);try{return await(0,T.compile)(P(n,e),e,{bannerComment:"",customName:(o,r)=>o.title===e?e:o.title||r?`${e}_${o.title||r}`:void 0,unknownAny:!0,additionalProperties:!0,$refOptions:{resolve:{http:!1,file:!1}}})}catch{return`// Schema could not be represented; no precision is claimed.
|
|
8
|
+
export type ${e} = unknown;`}}function j(n){if(!n||n.type!=="object")return;let e=n.properties;if(!e||typeof e!="object"||Array.isArray(e))return;let o=e.rows;if(!o||typeof o!="object"||Array.isArray(o))return;let r=o,t=r.items;return r.type==="array"&&t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}async function N(n,e){let o=new Map(n.map(a=>[a.functionId,a]));for(let a of e)!o.has(a.functionId)&&a.functionType!==void 0&&o.set(a.functionId,{functionId:a.functionId,functionType:a.functionType});let r=[...o.values()],t=["/* Generated by base-database-cli from Function metadata. Do not edit. */",...r.some(a=>a.functionType===1)?[`import type { DatabaseQueryResult } from '${y}';`]:[]],s=[];for(let[a,i]of r.sort((c,u)=>c.functionId.localeCompare(u.functionId)).entries()){let c=`Function${a}Output`;if(i.functionType===1){let u=j(i.output);if(u){let g=`Function${a}Row`;t.push(await h(u,g)),t.push(`export type ${c} = DatabaseQueryResult<${g}>;`)}else t.push(`export type ${c} = DatabaseQueryResult<unknown>;`)}else i.output?t.push(await h(i.output,c)):t.push(`export type ${c} = unknown;`);s.push(` ${JSON.stringify(i.functionId)}: ${c};`)}return t.push("export type DatabaseFunctionOutputMap = {",...s,"};",`declare module '${y}' { interface FunctionOutputMap extends DatabaseFunctionOutputMap {} }`,""),t.join(`
|
|
9
|
+
`)}async function $(n,e,o="../lib/database-function-inputs.generated"){let r=["/* Generated by base-database-cli. Runtime validation remains authoritative. */",`import { invokeDatabaseFunction } from '${y}';`,"import { SDKError } from '@lark-base-open/base-database-app-sdk/shared';",`import type { DatabaseFunctionInputMap as GeneratedFunctionInputs } from ${JSON.stringify(o)};`,`import type { DatabaseFunctionOutputMap as GeneratedFunctionOutputs } from ${JSON.stringify(o)};`,`export const contract = ${JSON.stringify({version:1,schemaHash:e,remoteContractMatch:"unknown"})} as const;`],t=[];for(let[s,a]of[...n].sort((i,c)=>i.functionId.localeCompare(c.functionId)).entries()){let i=`Function${s}Input`,c=`Function${s}Output`;r.push(`export type ${i} = GeneratedFunctionInputs[${JSON.stringify(a.functionId)}];`),r.push(`export type ${c} = GeneratedFunctionOutputs[${JSON.stringify(a.functionId)}];`),t.push(` [${JSON.stringify(a.functionId)}]: async (input: ${i}): Promise<${c}> => {
|
|
10
|
+
const response = await invokeDatabaseFunction(${JSON.stringify(a.functionId)}, input);
|
|
10
11
|
if (!response || !Number.isSafeInteger(response.code)) throw new SDKError('FUNCTION_RESPONSE_INVALID', 'Invalid Function response', {outcome:'unknown'});
|
|
11
12
|
if (response.code !== 0) throw new SDKError('FUNCTION_INVOKE_FAILED', 'Function invocation failed', String(response.code));
|
|
12
13
|
return response.data as ${c};
|
|
13
|
-
},`)}return r.push(`declare module '${
|
|
14
|
-
`)}function P(n,e){let o=structuredClone(n);return p(o,r=>{Array.isArray(r.prefixItems)&&(r.additionalItems=r.items??r.maxItems!==r.prefixItems.length,r.items=r.prefixItems,delete r.prefixItems)}),o.title=e,o}function f(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function
|
|
15
|
-
`)}var
|
|
14
|
+
},`)}return r.push(`declare module '${y}' { interface FunctionInputMap extends GeneratedFunctionInputs {} }`,"export const functions = {",...t,"};",""),r.join(`
|
|
15
|
+
`)}function P(n,e){let o=structuredClone(n);return p(o,r=>{Array.isArray(r.prefixItems)&&(r.additionalItems=r.items??r.maxItems!==r.prefixItems.length,r.items=r.prefixItems,delete r.prefixItems)}),o.title=e,o}function f(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function w(n){return n===null?"null":typeof n=="string"||typeof n=="boolean"?JSON.stringify(n):typeof n=="number"&&Number.isFinite(n)?Object.is(n,-0)?"-0":String(n):Array.isArray(n)?`[${n.map(w).join(", ")}]`:f(n)?`{ ${Object.entries(n).map(([e,o])=>`${JSON.stringify(e)}: ${w(o)}`).join("; ")} }`:"never"}function M(n,e){switch(e){case"string":return typeof n=="string";case"integer":return typeof n=="number"&&Number.isInteger(n);case"number":return typeof n=="number"&&Number.isFinite(n);case"boolean":return typeof n=="boolean";case"null":return n===null;case"array":return Array.isArray(n);case"object":return f(n);default:return!1}}function G(n){return typeof n.type=="string"?[n.type]:Array.isArray(n.type)?n.type.filter(e=>typeof e=="string"):[]}function J(n,e){switch(e){case"string":return"string";case"integer":case"number":return"number";case"boolean":return"boolean";case"null":return"null";case"array":{let o=n.prefixItems,r=Array.isArray(o),t=r?o.filter(f):[];if(r&&n.minItems===t.length&&n.maxItems===t.length)return`[${t.map(d).join(", ")}]`;let s=f(n.items)?d(n.items):"unknown";return t.length===0?`Array<${s}>`:`[${[...t.map(i=>`${d(i)}?`),`...Array<${s}>`].join(", ")}]`}case"object":{let o=f(n.properties)?n.properties:{},r=new Set(Array.isArray(n.required)?n.required.filter(u=>typeof u=="string"):[]),t=Object.entries(o).filter(u=>f(u[1])),s=new Set(t.map(([u])=>u)),a=[...r].filter(u=>!s.has(u));if(a.length>0&&n.additionalProperties===!1)return"never";let i=t.map(([u,g])=>`${JSON.stringify(u)}${r.has(u)?"":"?"}: ${d(g)}`);i.push(...a.map(u=>`${JSON.stringify(u)}: unknown`));let c=`{ ${i.join("; ")} }`;return n.additionalProperties===!1?i.length===0?"Record<string, never>":c:`${c} & Record<string, unknown>`}default:return"unknown"}}function d(n){let e=["anyOf","oneOf","allOf"].filter(t=>Array.isArray(n[t]));if(e.length){let t={...n};for(let i of e)delete t[i];let s=e.map(i=>{let c=n[i].filter(f).map(d);return c.length?c.map(u=>`(${u})`).join(i==="allOf"?" & ":" | "):"never"}),a=d(t);return a!=="unknown"&&s.unshift(a),s.map(i=>`(${i})`).join(" & ")}if(Object.hasOwn(n,"const"))return w(n.const);let o=G(n);if(Array.isArray(n.enum)&&n.enum.length>0){let t=n.enum.filter(s=>o.length===0||o.some(a=>M(s,a)));return t.length===0?"never":t.map(w).join(" | ")}let r=[...new Set(o.map(t=>J(n,t)))];return r.length===0?"unknown":r.join(" | ")}function k(n){let e=[...n].sort((t,s)=>t.functionId<s.functionId?-1:t.functionId>s.functionId?1:0),o=e.map(t=>` ${JSON.stringify(t.functionId)}: ${d(t.inputSchema)}`),r=e.flatMap(t=>{let s=Object.entries(t.parameterOptions??{});return s.length===0?[]:[` ${JSON.stringify(t.functionId)}: {`,...s.map(([a,i])=>` ${JSON.stringify(a)}: ${JSON.stringify(i)},`)," },"]});return["/* Generated by base-database-cli from Function metadata. Do not edit. */","// prettier-ignore","export type DatabaseFunctionInputMap = {",...o,"}",...r.length?["","/** Fixed options declared as enum, keyed by Function ID and parameter name; the Agent-facing schema uses the same values. */","// prettier-ignore","export const DatabaseFunctionParameterOptions = {",...r,"} as const"]:[],""].join(`
|
|
16
|
+
`)}var U=[1],m=class extends Error{constructor(o,r){super(r);this.code=o;this.name="CodegenError"}toJSON(){return{code:this.code,message:this.message}}},S=b.replace("./database-function-inputs.generated","../generated/function-inputs"),I=n=>!!n&&typeof n=="object"&&!Array.isArray(n);function F(n){if(!I(n)||n.contractFormatVersion!==1)throw new m("CONTRACT_FORMAT_UNSUPPORTED","Supported contractFormatVersion: 1");let e=()=>{throw new m("CONTRACT_DATA_INVALID","Invalid contract format 1 data")};(!["workspace","classic"].includes(String(n.layout))||typeof n.schemaHash!="string"||typeof n.client!="boolean"||!["none","compat","client"].includes(String(n.augmentation))||n.previousAugmentation!==void 0&&typeof n.previousAugmentation!="string")&&e();let o;try{o=JSON.stringify(n)}catch{return e()}Buffer.byteLength(o)>4*1024*1024&&e();for(let t of["functions","inputs"]){let s=n[t];if(!Array.isArray(s)||s.length>1e3)return e();let a=new Set;for(let i of s){if(!I(i)||typeof i.functionId!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(i.functionId)||a.has(i.functionId))return e();a.add(i.functionId),t==="functions"&&(typeof i.functionType!="number"||![1,2,5].includes(i.functionType))&&e(),t==="inputs"&&!I(i.inputSchema)&&e(),t==="inputs"&&i.functionType!==void 0&&(typeof i.functionType!="number"||![1,2,5].includes(i.functionType))&&e();for(let c of t==="inputs"?["inputSchema"]:["input","output"])if(i[c]!==void 0)try{l(i[c])}catch{e()}i.parameterOptions!==void 0&&(!I(i.parameterOptions)||!Object.values(i.parameterOptions).every(Array.isArray))&&e()}}let r=new Set(n.inputs.map(t=>t.functionId));n.functions.some(t=>!r.has(t.functionId))&&e()}async function L(n){if(F(n),n.previousAugmentation!==void 0&&![b,O,S].includes(n.previousAugmentation))throw new m("CONTRACT_INPUT_MAP_CONFLICT","Unrecognized FunctionInputMap augmentation; review before replacing");let e=[{path:n.layout==="workspace"?"page/src/generated/function-inputs.ts":"page/src/lib/database-function-inputs.generated.ts",content:`${await N(n.functions,n.inputs)}
|
|
17
|
+
${k(n.inputs)}`}];return n.client&&e.push({path:"page/src/generated/functions.ts",content:await $(n.functions,n.schemaHash,n.layout==="workspace"?"./function-inputs":"../lib/database-function-inputs.generated")}),n.augmentation!=="none"&&e.push({path:"page/src/lib/function-input-map.generated.ts",content:n.augmentation==="compat"?n.layout==="workspace"?S:b:O}),e}0&&(module.exports={CodegenError,SUPPORTED_CONTRACT_FORMAT_VERSIONS,generateFunctionClients,validateContractData});
|
package/dist/codegen.d.cts
CHANGED
|
@@ -8,6 +8,8 @@ interface ClientContract {
|
|
|
8
8
|
declare const SUPPORTED_CONTRACT_FORMAT_VERSIONS: readonly [1];
|
|
9
9
|
interface FunctionInputContract {
|
|
10
10
|
functionId: string;
|
|
11
|
+
/** CLI also supplies the type when regenerating a legacy helper without client contracts. */
|
|
12
|
+
functionType?: 1 | 2 | 5;
|
|
11
13
|
inputSchema: Record<string, unknown>;
|
|
12
14
|
parameterOptions?: Record<string, unknown[]>;
|
|
13
15
|
}
|
package/dist/codegen.d.ts
CHANGED
|
@@ -8,6 +8,8 @@ interface ClientContract {
|
|
|
8
8
|
declare const SUPPORTED_CONTRACT_FORMAT_VERSIONS: readonly [1];
|
|
9
9
|
interface FunctionInputContract {
|
|
10
10
|
functionId: string;
|
|
11
|
+
/** CLI also supplies the type when regenerating a legacy helper without client contracts. */
|
|
12
|
+
functionType?: 1 | 2 | 5;
|
|
11
13
|
inputSchema: Record<string, unknown>;
|
|
12
14
|
parameterOptions?: Record<string, unknown[]>;
|
|
13
15
|
}
|
package/dist/codegen.js
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
|
-
import{compile as
|
|
1
|
+
import{compile as k}from"json-schema-to-typescript";function p(n,e){if(!n||typeof n!="object"||Array.isArray(n))return;let o=n;e(o);for(let t of["properties","patternProperties","$defs","definitions","dependentSchemas"]){let s=o[t];if(s&&typeof s=="object"&&!Array.isArray(s))for(let a of Object.values(s))p(a,e)}for(let t of["items","additionalItems","additionalProperties","unevaluatedProperties","unevaluatedItems","contains","propertyNames","not","if","then","else"]){let s=o[t];Array.isArray(s)?s.forEach(a=>p(a,e)):p(s,e)}for(let t of["allOf","anyOf","oneOf","prefixItems"])Array.isArray(o[t])&&o[t].forEach(s=>p(s,e));let r=o.dependencies;if(r&&typeof r=="object"&&!Array.isArray(r))for(let t of Object.values(r))Array.isArray(t)||p(t,e)}function l(n){if(!n||typeof n!="object"||Array.isArray(n)||Buffer.byteLength(JSON.stringify(n))>32768)throw new Error("CONTRACT_SCHEMA_BUDGET");let e=0,o=(r,t)=>{if(!(!r||typeof r!="object")){if(++e>256||t>16)throw new Error("CONTRACT_SCHEMA_BUDGET");Object.values(r).forEach(s=>o(s,t+1))}};o(n,0),p(n,r=>{if(Object.hasOwn(r,"$ref")&&(typeof r.$ref!="string"||!r.$ref.startsWith("#/")))throw new Error("CONTRACT_EXTERNAL_REF");if(["$id","$dynamicRef","$recursiveRef","tsType","tsEnumNames"].some(t=>Object.hasOwn(r,t)))throw new Error("CONTRACT_EXTERNAL_REF")})}var y="@lark-base-open/base-database-app-sdk/page",b=`/* Generated by base-database-cli. Do not edit. */
|
|
2
2
|
import type { DatabaseFunctionInputMap as GeneratedInputMap } from './database-function-inputs.generated';
|
|
3
|
-
import '${
|
|
4
|
-
declare module '${
|
|
5
|
-
`,
|
|
3
|
+
import '${y}';
|
|
4
|
+
declare module '${y}' { interface FunctionInputMap extends GeneratedInputMap {} }
|
|
5
|
+
`,A=`/* Generated by base-database-cli. Map is declared in ../generated/functions. */
|
|
6
6
|
export {};
|
|
7
|
-
`;async function
|
|
8
|
-
export type ${
|
|
9
|
-
|
|
7
|
+
`;async function O(n,e){l(n);try{return await k(F(n,e),e,{bannerComment:"",customName:(o,r)=>o.title===e?e:o.title||r?`${e}_${o.title||r}`:void 0,unknownAny:!0,additionalProperties:!0,$refOptions:{resolve:{http:!1,file:!1}}})}catch{return`// Schema could not be represented; no precision is claimed.
|
|
8
|
+
export type ${e} = unknown;`}}function S(n){if(!n||n.type!=="object")return;let e=n.properties;if(!e||typeof e!="object"||Array.isArray(e))return;let o=e.rows;if(!o||typeof o!="object"||Array.isArray(o))return;let r=o,t=r.items;return r.type==="array"&&t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}async function h(n,e){let o=new Map(n.map(a=>[a.functionId,a]));for(let a of e)!o.has(a.functionId)&&a.functionType!==void 0&&o.set(a.functionId,{functionId:a.functionId,functionType:a.functionType});let r=[...o.values()],t=["/* Generated by base-database-cli from Function metadata. Do not edit. */",...r.some(a=>a.functionType===1)?[`import type { DatabaseQueryResult } from '${y}';`]:[]],s=[];for(let[a,i]of r.sort((c,u)=>c.functionId.localeCompare(u.functionId)).entries()){let c=`Function${a}Output`;if(i.functionType===1){let u=S(i.output);if(u){let g=`Function${a}Row`;t.push(await O(u,g)),t.push(`export type ${c} = DatabaseQueryResult<${g}>;`)}else t.push(`export type ${c} = DatabaseQueryResult<unknown>;`)}else i.output?t.push(await O(i.output,c)):t.push(`export type ${c} = unknown;`);s.push(` ${JSON.stringify(i.functionId)}: ${c};`)}return t.push("export type DatabaseFunctionOutputMap = {",...s,"};",`declare module '${y}' { interface FunctionOutputMap extends DatabaseFunctionOutputMap {} }`,""),t.join(`
|
|
9
|
+
`)}async function T(n,e,o="../lib/database-function-inputs.generated"){let r=["/* Generated by base-database-cli. Runtime validation remains authoritative. */",`import { invokeDatabaseFunction } from '${y}';`,"import { SDKError } from '@lark-base-open/base-database-app-sdk/shared';",`import type { DatabaseFunctionInputMap as GeneratedFunctionInputs } from ${JSON.stringify(o)};`,`import type { DatabaseFunctionOutputMap as GeneratedFunctionOutputs } from ${JSON.stringify(o)};`,`export const contract = ${JSON.stringify({version:1,schemaHash:e,remoteContractMatch:"unknown"})} as const;`],t=[];for(let[s,a]of[...n].sort((i,c)=>i.functionId.localeCompare(c.functionId)).entries()){let i=`Function${s}Input`,c=`Function${s}Output`;r.push(`export type ${i} = GeneratedFunctionInputs[${JSON.stringify(a.functionId)}];`),r.push(`export type ${c} = GeneratedFunctionOutputs[${JSON.stringify(a.functionId)}];`),t.push(` [${JSON.stringify(a.functionId)}]: async (input: ${i}): Promise<${c}> => {
|
|
10
|
+
const response = await invokeDatabaseFunction(${JSON.stringify(a.functionId)}, input);
|
|
10
11
|
if (!response || !Number.isSafeInteger(response.code)) throw new SDKError('FUNCTION_RESPONSE_INVALID', 'Invalid Function response', {outcome:'unknown'});
|
|
11
12
|
if (response.code !== 0) throw new SDKError('FUNCTION_INVOKE_FAILED', 'Function invocation failed', String(response.code));
|
|
12
13
|
return response.data as ${c};
|
|
13
|
-
},`)}return
|
|
14
|
-
`)}function
|
|
15
|
-
`)}var
|
|
14
|
+
},`)}return r.push(`declare module '${y}' { interface FunctionInputMap extends GeneratedFunctionInputs {} }`,"export const functions = {",...t,"};",""),r.join(`
|
|
15
|
+
`)}function F(n,e){let o=structuredClone(n);return p(o,r=>{Array.isArray(r.prefixItems)&&(r.additionalItems=r.items??r.maxItems!==r.prefixItems.length,r.items=r.prefixItems,delete r.prefixItems)}),o.title=e,o}function f(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function w(n){return n===null?"null":typeof n=="string"||typeof n=="boolean"?JSON.stringify(n):typeof n=="number"&&Number.isFinite(n)?Object.is(n,-0)?"-0":String(n):Array.isArray(n)?`[${n.map(w).join(", ")}]`:f(n)?`{ ${Object.entries(n).map(([e,o])=>`${JSON.stringify(e)}: ${w(o)}`).join("; ")} }`:"never"}function C(n,e){switch(e){case"string":return typeof n=="string";case"integer":return typeof n=="number"&&Number.isInteger(n);case"number":return typeof n=="number"&&Number.isFinite(n);case"boolean":return typeof n=="boolean";case"null":return n===null;case"array":return Array.isArray(n);case"object":return f(n);default:return!1}}function R(n){return typeof n.type=="string"?[n.type]:Array.isArray(n.type)?n.type.filter(e=>typeof e=="string"):[]}function x(n,e){switch(e){case"string":return"string";case"integer":case"number":return"number";case"boolean":return"boolean";case"null":return"null";case"array":{let o=n.prefixItems,r=Array.isArray(o),t=r?o.filter(f):[];if(r&&n.minItems===t.length&&n.maxItems===t.length)return`[${t.map(d).join(", ")}]`;let s=f(n.items)?d(n.items):"unknown";return t.length===0?`Array<${s}>`:`[${[...t.map(i=>`${d(i)}?`),`...Array<${s}>`].join(", ")}]`}case"object":{let o=f(n.properties)?n.properties:{},r=new Set(Array.isArray(n.required)?n.required.filter(u=>typeof u=="string"):[]),t=Object.entries(o).filter(u=>f(u[1])),s=new Set(t.map(([u])=>u)),a=[...r].filter(u=>!s.has(u));if(a.length>0&&n.additionalProperties===!1)return"never";let i=t.map(([u,g])=>`${JSON.stringify(u)}${r.has(u)?"":"?"}: ${d(g)}`);i.push(...a.map(u=>`${JSON.stringify(u)}: unknown`));let c=`{ ${i.join("; ")} }`;return n.additionalProperties===!1?i.length===0?"Record<string, never>":c:`${c} & Record<string, unknown>`}default:return"unknown"}}function d(n){let e=["anyOf","oneOf","allOf"].filter(t=>Array.isArray(n[t]));if(e.length){let t={...n};for(let i of e)delete t[i];let s=e.map(i=>{let c=n[i].filter(f).map(d);return c.length?c.map(u=>`(${u})`).join(i==="allOf"?" & ":" | "):"never"}),a=d(t);return a!=="unknown"&&s.unshift(a),s.map(i=>`(${i})`).join(" & ")}if(Object.hasOwn(n,"const"))return w(n.const);let o=R(n);if(Array.isArray(n.enum)&&n.enum.length>0){let t=n.enum.filter(s=>o.length===0||o.some(a=>C(s,a)));return t.length===0?"never":t.map(w).join(" | ")}let r=[...new Set(o.map(t=>x(n,t)))];return r.length===0?"unknown":r.join(" | ")}function N(n){let e=[...n].sort((t,s)=>t.functionId<s.functionId?-1:t.functionId>s.functionId?1:0),o=e.map(t=>` ${JSON.stringify(t.functionId)}: ${d(t.inputSchema)}`),r=e.flatMap(t=>{let s=Object.entries(t.parameterOptions??{});return s.length===0?[]:[` ${JSON.stringify(t.functionId)}: {`,...s.map(([a,i])=>` ${JSON.stringify(a)}: ${JSON.stringify(i)},`)," },"]});return["/* Generated by base-database-cli from Function metadata. Do not edit. */","// prettier-ignore","export type DatabaseFunctionInputMap = {",...o,"}",...r.length?["","/** Fixed options declared as enum, keyed by Function ID and parameter name; the Agent-facing schema uses the same values. */","// prettier-ignore","export const DatabaseFunctionParameterOptions = {",...r,"} as const"]:[],""].join(`
|
|
16
|
+
`)}var L=[1],m=class extends Error{constructor(o,r){super(r);this.code=o;this.name="CodegenError"}toJSON(){return{code:this.code,message:this.message}}},$=b.replace("./database-function-inputs.generated","../generated/function-inputs"),I=n=>!!n&&typeof n=="object"&&!Array.isArray(n);function E(n){if(!I(n)||n.contractFormatVersion!==1)throw new m("CONTRACT_FORMAT_UNSUPPORTED","Supported contractFormatVersion: 1");let e=()=>{throw new m("CONTRACT_DATA_INVALID","Invalid contract format 1 data")};(!["workspace","classic"].includes(String(n.layout))||typeof n.schemaHash!="string"||typeof n.client!="boolean"||!["none","compat","client"].includes(String(n.augmentation))||n.previousAugmentation!==void 0&&typeof n.previousAugmentation!="string")&&e();let o;try{o=JSON.stringify(n)}catch{return e()}Buffer.byteLength(o)>4*1024*1024&&e();for(let t of["functions","inputs"]){let s=n[t];if(!Array.isArray(s)||s.length>1e3)return e();let a=new Set;for(let i of s){if(!I(i)||typeof i.functionId!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(i.functionId)||a.has(i.functionId))return e();a.add(i.functionId),t==="functions"&&(typeof i.functionType!="number"||![1,2,5].includes(i.functionType))&&e(),t==="inputs"&&!I(i.inputSchema)&&e(),t==="inputs"&&i.functionType!==void 0&&(typeof i.functionType!="number"||![1,2,5].includes(i.functionType))&&e();for(let c of t==="inputs"?["inputSchema"]:["input","output"])if(i[c]!==void 0)try{l(i[c])}catch{e()}i.parameterOptions!==void 0&&(!I(i.parameterOptions)||!Object.values(i.parameterOptions).every(Array.isArray))&&e()}}let r=new Set(n.inputs.map(t=>t.functionId));n.functions.some(t=>!r.has(t.functionId))&&e()}async function V(n){if(E(n),n.previousAugmentation!==void 0&&![b,A,$].includes(n.previousAugmentation))throw new m("CONTRACT_INPUT_MAP_CONFLICT","Unrecognized FunctionInputMap augmentation; review before replacing");let e=[{path:n.layout==="workspace"?"page/src/generated/function-inputs.ts":"page/src/lib/database-function-inputs.generated.ts",content:`${await h(n.functions,n.inputs)}
|
|
17
|
+
${N(n.inputs)}`}];return n.client&&e.push({path:"page/src/generated/functions.ts",content:await T(n.functions,n.schemaHash,n.layout==="workspace"?"./function-inputs":"../lib/database-function-inputs.generated")}),n.augmentation!=="none"&&e.push({path:"page/src/lib/function-input-map.generated.ts",content:n.augmentation==="compat"?n.layout==="workspace"?$:b:A}),e}export{m as CodegenError,L as SUPPORTED_CONTRACT_FORMAT_VERSIONS,V as generateFunctionClients,E as validateContractData};
|
package/dist/components.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { _ as AttachmentImage, P as BaseAppContextValue, Q as BaseAppProvider, X as DatabaseAudience, Z as DatabaseUserMenu, Y as DatabaseUserMenuProps, W as FloatingButton, V as FloatingButtonProps, U as UiLanguage, $ as UiLanguageContext, H as User, K as UserSelectorAction, M as UserSelectorEditor, N as UserSelectorEditorProps, O as UserSelectorEditorValue, J as UserSelectorMode, E as UserSelectorPanel, G as UserSelectorPanelProps, L as UserSelectorSearchAction, I as UserSelectorValue, a1 as getUiLanguage, a2 as getUiLocale, a3 as initializeUiLanguage, a0 as selectUiLanguage, R as useBaseApp, T as useOptionalBaseApp, a4 as useUiLanguage } from './index-1e1bba93.js';
|
|
2
2
|
import 'react';
|
|
3
3
|
import '@lark-base-open/base-site-channel/runtime';
|
|
4
4
|
import './capabilities-56e403e7.js';
|
package/dist/components.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{L as a,M as b,N as c,O as d,P as e,Q as f,R as g,S as h,T as i,V as j,W as k,X as l,Y as m,Z as n}from"./chunk-
|
|
1
|
+
import{L as a,M as b,N as c,O as d,P as e,Q as f,R as g,S as h,T as i,V as j,W as k,X as l,Y as m,Z as n}from"./chunk-Q7AAUQ7T.js";import"./chunk-ZKBZAK4L.js";import"./chunk-3JX3FIBG.js";import"./chunk-OHPYKFCM.js";export{n as AttachmentImage,g as BaseAppProvider,k as DatabaseUserMenu,j as FloatingButton,a as UiLanguageContext,m as UserSelectorEditor,l as UserSelectorPanel,c as getUiLanguage,d as getUiLocale,e as initializeUiLanguage,b as selectUiLanguage,h as useBaseApp,i as useOptionalBaseApp,f as useUiLanguage};
|
|
@@ -27,6 +27,15 @@ interface DatabaseFunctionInputMap extends FunctionInputMap {
|
|
|
27
27
|
}
|
|
28
28
|
interface FunctionInputMap {
|
|
29
29
|
}
|
|
30
|
+
/** CLI 生成的 Function ID 到响应 data 类型的映射。 */
|
|
31
|
+
interface DatabaseFunctionOutputMap extends FunctionOutputMap {
|
|
32
|
+
}
|
|
33
|
+
interface FunctionOutputMap {
|
|
34
|
+
}
|
|
35
|
+
/** SQL Function 的 data 是查询结果对象,而不是 rows 数组本身。 */
|
|
36
|
+
interface DatabaseQueryResult<Row = unknown> {
|
|
37
|
+
rows: Row[];
|
|
38
|
+
}
|
|
30
39
|
|
|
31
40
|
/** 应用产物在 BaseApp 页面 iframe 中的运行上下文。 */
|
|
32
41
|
interface DatabaseContext {
|
|
@@ -112,7 +121,10 @@ type DatabaseFunctionInvocation<Inputs extends object> = [
|
|
|
112
121
|
params: Inputs[FunctionId]
|
|
113
122
|
];
|
|
114
123
|
}[Extract<keyof Inputs, string>];
|
|
115
|
-
|
|
124
|
+
type FunctionId = Extract<keyof DatabaseFunctionInputMap, string>;
|
|
125
|
+
type MappedOutputId = Extract<keyof DatabaseFunctionOutputMap, FunctionId>;
|
|
126
|
+
/** 仅允许同时具有输入和输出契约的 Function;data 按 ID 推断。 */
|
|
127
|
+
declare function invokeDatabaseFunction<Id extends MappedOutputId>(functionId: Id, params: DatabaseFunctionInputMap[Id]): Promise<DatabaseFunctionResponse<DatabaseFunctionOutputMap[Id]>>;
|
|
116
128
|
/** 每组参数应用同一份已发布 Mutation 声明;总记录数最多 200。 */
|
|
117
129
|
declare function invokeDatabaseMutationBatch<Data = unknown>(functionId: string, parameterGroups: Record<string, unknown>[]): Promise<DatabaseFunctionResponse<Data>>;
|
|
118
130
|
/** 每次点击重新取短效 URL,经宿主打开;不代表浏览器已完成落盘。 */
|
|
@@ -303,4 +315,4 @@ declare function AttachmentImage({ attachment, size, alt, className, slots, }: {
|
|
|
303
315
|
className?: string;
|
|
304
316
|
}): React.JSX.Element;
|
|
305
317
|
|
|
306
|
-
export {
|
|
318
|
+
export { UiLanguageContext as $, invokeApi as A, uploadAttachment as B, openLink as C, DatabaseContext as D, UserSelectorPanel as E, FunctionInputMap as F, UserSelectorPanelProps as G, User as H, UserSelectorValue as I, UserSelectorMode as J, UserSelectorAction as K, UserSelectorSearchAction as L, UserSelectorEditor as M, UserSelectorEditorProps as N, UserSelectorEditorValue as O, BaseAppContextValue as P, BaseAppProvider as Q, useBaseApp as R, SiteRuntimeClient as S, useOptionalBaseApp as T, UiLanguage as U, FloatingButtonProps as V, FloatingButton as W, DatabaseAudience as X, DatabaseUserMenuProps as Y, DatabaseUserMenu as Z, AttachmentImage as _, getDatabaseContext as a, selectUiLanguage as a0, getUiLanguage as a1, getUiLocale as a2, initializeUiLanguage as a3, useUiLanguage as a4, resolveDatabaseContext as b, fetchAttachmentCover as c, buildAttachmentCoverUrl as d, fetchAttachmentDownloadUrl as e, fetch as f, getCurrentUser as g, buildDatabaseInvokeGetPath as h, invokeHttp as i, buildDatabaseInvokeFunctionPath as j, invokeDatabaseFunction as k, logout as l, invokeDatabaseMutationBatch as m, DatabaseAttachmentRef as n, openAttachmentDownload as o, DatabaseEnv as p, DatabaseFunctionResponse as q, requestEdit as r, siteRuntime as s, DatabaseFunctionInvocation as t, DatabaseFunctionInputMap as u, DatabaseFunctionOutputMap as v, FunctionOutputMap as w, DatabaseQueryResult as x, createSiteRuntimeClient as y, createSiteRuntimeFetch as z };
|
package/dist/page.d.ts
CHANGED
|
@@ -8,8 +8,8 @@ import { R as RuntimeContextReader } from './capabilities-56e403e7.js';
|
|
|
8
8
|
export { S as SiteRuntimeContext, g as getCapabilities, a as getRuntimeCapabilities, h as hasCapability, q as queryCapability, r as readCapabilities, b as requireCapability } from './capabilities-56e403e7.js';
|
|
9
9
|
export * from '@lark-base-open/base-site-channel/runtime-contract';
|
|
10
10
|
export { SITE_RUNTIME_PROTOCOL_VERSION, SiteRuntimeApi, SiteRuntimeErrorCode, SiteRuntimeEvent, SiteRuntimeFunction, isValidSiteFunctionName, readSiteAITextDelta } from '@lark-base-open/base-site-channel/runtime-contract';
|
|
11
|
-
import { U as UiLanguage } from './index-
|
|
12
|
-
export {
|
|
11
|
+
import { U as UiLanguage } from './index-1e1bba93.js';
|
|
12
|
+
export { _ as AttachmentImage, P as BaseAppContextValue, Q as BaseAppProvider, n as DatabaseAttachmentRef, X as DatabaseAudience, D as DatabaseContext, p as DatabaseEnv, u as DatabaseFunctionInputMap, t as DatabaseFunctionInvocation, v as DatabaseFunctionOutputMap, q as DatabaseFunctionResponse, x as DatabaseQueryResult, Z as DatabaseUserMenu, Y as DatabaseUserMenuProps, W as FloatingButton, V as FloatingButtonProps, F as FunctionInputMap, w as FunctionOutputMap, S as SiteRuntimeClient, $ as UiLanguageContext, H as User, K as UserSelectorAction, M as UserSelectorEditor, N as UserSelectorEditorProps, O as UserSelectorEditorValue, J as UserSelectorMode, E as UserSelectorPanel, G as UserSelectorPanelProps, L as UserSelectorSearchAction, I as UserSelectorValue, d as buildAttachmentCoverUrl, j as buildDatabaseInvokeFunctionPath, h as buildDatabaseInvokeGetPath, y as createSiteRuntimeClient, z as createSiteRuntimeFetch, f as fetch, c as fetchAttachmentCover, e as fetchAttachmentDownloadUrl, g as getCurrentUser, a as getDatabaseContext, a1 as getUiLanguage, a2 as getUiLocale, a3 as initializeUiLanguage, A as invokeApi, k as invokeDatabaseFunction, m as invokeDatabaseMutationBatch, i as invokeHttp, l as logout, o as openAttachmentDownload, C as openLink, r as requestEdit, b as resolveDatabaseContext, a0 as selectUiLanguage, s as siteRuntime, B as uploadAttachment, R as useBaseApp, T as useOptionalBaseApp, a4 as useUiLanguage } from './index-1e1bba93.js';
|
|
13
13
|
import React__default from 'react';
|
|
14
14
|
export { CAPABILITY_CATALOG } from '@lark-base-open/base-site-channel/capabilities';
|
|
15
15
|
|
package/dist/page.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as
|
|
1
|
+
import{A as je,B as le,C as pe,D as fe,E as Se,F as Ae,G as ge,H as Ie,I as ke,J as ye,K as he,L as Ye,M as L,N as Je,O,P as Xe,Q as Ze,R as B,S as $e,T as et,U,V as G,W as tt,X as nt,Y as it,Z as rt,a as j,b as Y,c as J,d as X,e as Z,f as $,g as ee,h as x,i as M,j as te,k as ne,l as m,m as ie,n as re,o as ae,p as oe,q as se,r as ce,s as ue,t as de,u as me,v as ze,w as _,x as Ke,y as We,z as Qe}from"./chunk-Q7AAUQ7T.js";import{a as He,b as Ve,c as v,d as R}from"./chunk-ZKBZAK4L.js";import{a as qe}from"./chunk-3JX3FIBG.js";import"./chunk-OHPYKFCM.js";export*from"@lark-base-open/base-site-channel/runtime";import{installLinkGuard as Re}from"@lark-base-open/base-site-channel/runtime";function D(e={}){let t=!0,n,i=s=>{let c=R(s);e.onDiagnostic?e.onDiagnostic(c):console.warn("[Base Database SDK]",c)},a=e.runtime??m;return Promise.resolve().then(()=>a.getRuntimeContext()).then(s=>{if(t){if(!_(s,"link.open")){i(new v("link.open",1));return}n=Re(e)}}).catch(s=>{t&&i(s)}),()=>{t=!1,n?.()}}export*from"@lark-base-open/base-site-channel/runtime-contract";import{SiteChatbotStreamError as _t}from"@lark-base-open/base-site-channel/runtime";import*as u from"@lark-base-open/base-site-channel/runtime";var P=class extends u.SiteChatbotStreamAdapter{constructor(t){super({...t,channel:t.channel?x(t.channel):M})}},F=e=>({...e,channel:e?.channel?x(e.channel):M}),N=(e,t)=>u.callSiteAIFunction(e,F(t)),q=(e,t)=>u.invokeSiteAIFunctionStream(e,F(t)),H=(e,t)=>u.createSiteAIFunctionTask(e,F(t)),V=(e,t,n)=>u.getSiteAIFunctionTask(e,t,F(n));var Fe=new Set(["cancelled","failed","queued","running","succeeded"]);async function Te(e){let t=await N(e);return e.input&&!e.messages?k(t):t}function be(e){return q(e)}function o(e,t){for(let n of t){let i=e[n];if(typeof i=="string"&&i.trim())return i}}function Ce(e,t){for(let n of t){let i=e[n];if(typeof i=="number"&&Number.isFinite(i))return i}}function xe(e){let t=o(e,["capabilityType","capability_type","CapabilityType"]);return t==="image"||t==="video"?t:void 0}function Me(e){if(Array.isArray(e))return e.filter(b).map(t=>{let n=o(t,["size","Size"]),i=o(t,["token","Token"]),a=o(t,["url","URL"]);return{safetyStatus:o(t,["safetyStatus","safety_status","SafetyStatus"])??"",...n?{size:n}:{},...i?{token:i}:{},...a?{url:a}:{}}})}function De(e){if(!b(e))return;let t=e.durationSeconds??e.duration_seconds??e.DurationSeconds,n=o(e,["token","Token"]),i=o(e,["url","URL"]);return{...typeof t=="number"?{durationSeconds:t}:{},...n?{token:n}:{},...i?{url:i}:{}}}function T(e,t="INVALID_AI_FUNCTION_TASK"){let n=new Error(e);return n.name="SiteAIFunctionTaskError",n.code=t,n}function k(e){if(!b(e))throw T("AI Function task response has an invalid structure");let t=Pe(e);if(t)throw T(t.message,t.code);if("data"in e&&e.data!==void 0)return k(e.data);let n=o(e,["type","Type"]),i=o(e,["taskId","task_id","TaskID"]),a=e.status??e.Status;if(n!=="image_task"&&n!=="video_task"||!i||typeof a!="string"||!Fe.has(a))throw T("AI Function task response has an invalid structure");let s=Me(e.imageAssets??e.image_assets??e.ImageAssets),c=De(e.videoAsset??e.video_asset??e.VideoAsset),l=Ce(e,["progress","Progress"]),I=xe(e),p=o(e,["errCode","err_code","ErrCode"]),f=o(e,["errMessage","err_message","ErrMessage"]);return{...I?{capabilityType:I}:{},...p?{errCode:p}:{},...f?{errMessage:f}:{},...s?{imageAssets:s}:{},...l!==void 0?{progress:l}:{},...c?{videoAsset:c}:{},requestId:o(e,["requestId","request_id","RequestID"])??"",status:a,taskId:i,type:n}}function Pe(e){let t=e.code??e.Code;if(typeof t=="number"&&t!==0||typeof t=="string"&&t&&t!=="0")return{code:String(t),message:o(e,["msg","message","Message"])??"Failed to create the AI Function task"};let n=e.BaseResp??e.base_resp??e.baseResp;if(!b(n))return;let i=n.StatusCode??n.status_code??n.statusCode;if(typeof i=="number"&&i!==0||typeof i=="string"&&i&&i!=="0")return{code:String(i),message:o(n,["StatusMessage","status_message","statusMessage"])??"Failed to create the AI Function task"}}function Ee(e){return!!e.taskId.trim()&&(e.status==="queued"||e.status==="running")}async function we(e){return k(await H(e))}async function ve(e,t){if(!t.trim())throw T("AI Function task ID must not be empty");return k(await V(e,t))}function b(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{Component as _e,StrictMode as Le,useEffect as Oe,useState as Be}from"react";import{createRoot as Ue}from"react-dom/client";import{Fragment as Ge,jsx as d,jsxs as Ne}from"react/jsx-runtime";var E=new WeakSet,C=class extends _e{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(t){this.props.failed(t)}render(){let t=this.props.fallback;return this.state.failed?t?d(t,{code:"APP_BOOT_FAILED"}):d("div",{role:"alert",children:"APP_BOOT_FAILED"}):this.props.children}};function Tt(e){let t,n,i=new Promise((r,g)=>{t=r,n=g});i.catch(()=>{});let a=!1,s=!1,c=!1,l,I=()=>{},p=()=>{},f=r=>{try{e.onDiagnostic?.(R(r))}catch{}},S=r=>{f(r),!(a||s||c)&&(c=!0,n(r),e.reportLifecycle!==!1&&m.reportLoadFailed("APP_BOOT_FAILED").catch(f))},A;try{A=typeof e.root=="string"?document.querySelector(e.root):e.root??document.querySelector("#root")}catch(r){return S(r),{ready:i,dispose(){a=!0}}}if(!A)return S(new Error("APP_ROOT_NOT_FOUND")),{ready:i,dispose(){a=!0}};if(E.has(A))throw new Error("APP_ALREADY_STARTED");E.add(A);let z=()=>{a||(a=!0,I(),p(),l?.unmount(),E.delete(A),U.clear(),!s&&!c&&n(new Error("APP_DISPOSED")))},K=()=>{queueMicrotask(()=>{a||c||s||(s=!0,e.reportLifecycle===!1?t():m.ready().then(t,r=>{f(r),n(r)}))})};function W({locale:r,theme:g}){let[y,h]=Be();Oe(()=>(p=m.subscribeModeChanged(h),K(),()=>p()),[]);let Q=e.app,w=Ne(Ge,{children:[d(Q,{}),e.platformUI===!1?null:d(G,{})]});return d(B,{runtime:m,theme:g,locale:r,mode:y,onDiagnostic:e.onDiagnostic,children:e.providers?e.providers(w):w})}try{l=Ue(A);let r=e.slots?.loading;r&&l.render(d(C,{failed:S,fallback:e.slots?.error,children:d(r,{})})),m.getRuntimeContext().then(g=>{if(a||c)return;let y=e.locale&&e.locale!=="host"?e.locale:L(g.locale,"en");document.documentElement.lang=O(y),e.linkGuard!==!1&&(I=D({onDiagnostic:e.onDiagnostic}));let h=d(C,{failed:S,fallback:e.slots?.error,children:d(W,{locale:y,theme:e.theme&&e.theme!=="host"?e.theme:g.colorScheme==="dark"?"dark":"light"})});l.render(e.strictMode===!1?h:d(Le,{children:h}))}).catch(S)}catch(r){S(r)}return{ready:i,dispose:z}}export{rt as AttachmentImage,B as BaseAppProvider,He as CAPABILITY_CATALOG,v as CapabilityUnavailableError,tt as DatabaseUserMenu,Ve as DiagnosticCode,G as FloatingButton,qe as SDKError,j as SITE_RUNTIME_PROTOCOL_VERSION,P as SiteChatbotStreamAdapter,_t as SiteChatbotStreamError,Y as SiteRuntimeApi,te as SiteRuntimeClient,Z as SiteRuntimeErrorCode,J as SiteRuntimeEvent,X as SiteRuntimeFunction,Ye as UiLanguageContext,it as UserSelectorEditor,nt as UserSelectorPanel,he as buildAttachmentCoverUrl,ge as buildDatabaseInvokeFunctionPath,Ae as buildDatabaseInvokeGetPath,Te as callSiteAIFunction,R as classifyRuntimeError,we as createSiteAIFunctionTask,ne as createSiteRuntimeClient,de as createSiteRuntimeFetch,me as fetch,fe as fetchAttachmentCover,Se as fetchAttachmentDownloadUrl,Ke as getCapabilities,ae as getCurrentUser,le as getDatabaseContext,We as getRuntimeCapabilities,ve as getSiteAIFunctionTask,Je as getUiLanguage,O as getUiLocale,_ as hasCapability,Ee as hasRunnableMediaTask,Xe as initializeUiLanguage,D as installLinkGuard,re as invokeApi,Ie as invokeDatabaseFunction,ke as invokeDatabaseMutationBatch,ie as invokeHttp,be as invokeSiteAIFunctionStream,ee as isValidSiteFunctionName,oe as logout,k as normalizeSiteAIMediaTask,ye as openAttachmentDownload,ue as openLink,Qe as queryCapability,ze as readCapabilities,$ as readSiteAITextDelta,se as requestEdit,je as requireCapability,pe as resolveDatabaseContext,L as selectUiLanguage,m as siteRuntime,Tt as startBaseApp,ce as uploadAttachment,$e as useBaseApp,et as useOptionalBaseApp,Ze as useUiLanguage};
|
package/docs/codegen.md
CHANGED
|
@@ -19,10 +19,12 @@ export const files = await generateFunctionClients(data);
|
|
|
19
19
|
// {path:'page/src/generated/functions.ts',content:...}]
|
|
20
20
|
```
|
|
21
21
|
|
|
22
|
-
此入口只接收提取后的 JSON 数据并返回 `{path, content}[]`,不读工程、不写文件、不加载函数源码。函数契约、inputSchema、SQL/Mutation 命名参数转换及 parameterOptions 由 CLI 提取;SDK 负责所有 SDK 工程的 Page
|
|
22
|
+
此入口只接收提取后的 JSON 数据并返回 `{path, content}[]`,不读工程、不写文件、不加载函数源码。函数契约、inputSchema、SQL/Mutation 命名参数转换及 parameterOptions 由 CLI 提取;SDK 负责所有 SDK 工程的 Page 生成模板。每次生成都会按 Function ID 输出响应类型映射:SQL 的 `data` 为 `DatabaseQueryResult<Row>`(即 `{ rows: Row[] }`),未提供可信列类型时 `Row` 为 `unknown`;FaaS/Mutation 有输出 Schema 时按 Schema 生成,否则为 `unknown`。直接调用 `invokeDatabaseFunction('listDevices', params)` 会据此推断 `data`,已映射的 ID 不能再通过调用方泛型改写输出类型。
|
|
23
23
|
|
|
24
24
|
格式类型 `FunctionContractData`、`FunctionInputContract`、`ClientContract` 与等价校验函数 `validateContractData` 同入口导出。`SUPPORTED_CONTRACT_FORMAT_VERSIONS` 当前为 `[1]`。未知格式版本抛 `CodegenError`,其 `code=CONTRACT_FORMAT_UNSUPPORTED`、`toJSON()` 返回结构化错误;非法数据为 `CONTRACT_DATA_INVALID`。不接受外部 Schema 引用;沿用单 Schema 32KiB、256 节点和16层限制。
|
|
25
25
|
|
|
26
|
-
`client=false`
|
|
26
|
+
`client=false` 仍会在输入类型文件中生成输出映射,因此纯 SQL 工程直接调用 SDK 也有输出约束;仅省略 `functions.ts` 包装客户端。CLI 以 `functions: []` 重新生成旧 helper 时,SDK 可从 `inputs[].functionType` 保留 SQL 的 `{ rows }` 类型。`augmentation=compat|client` 生成相应 FunctionInputMap 增强文件,none 不生成增强。`previousAugmentation` 若提供,必须为已知的未修改生成文件,否则报 `CONTRACT_INPUT_MAP_CONFLICT`。生成文件有冻结的逐字节测试夹具。
|
|
27
|
+
|
|
28
|
+
直接调用要求输入、输出映射都包含该 Function ID;缺失输出映射不能退回到调用方自行指定泛型。FaaS/Mutation 未声明输出 Schema 时映射值为 `unknown`,页面须先校验或显式断言 `data` 的业务结构。这是对使用 `invokeDatabaseFunction<MyType>` 的旧工程的编译期破坏性变更,升级 SDK 后应重新生成契约并修改调用处。
|
|
27
29
|
|
|
28
30
|
CLI 在与契约提取相同的受限子进程边界执行安装在工程内的 codegen:环境清空、只读临时包快照、禁子进程/写文件、时间和内存限制;父进程校验相对路径、文件大小与目标软链后写入,check 比较文件内容。此机制不是面向任意恶意原生程序的通用沙箱。
|
package/docs/compat.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
数据库与附件实现位于 page/database.ts,AI helper 位于 page/ai-compat.ts。替换 import 后,Function 调用仍返回原 envelope;HTTP 失败仍抛错;Mutation batch 接受 1–200 个命名参数对象,与统一 Function 路由一致;旧位置数组必须按已发布的冻结声明人工迁移,不能直接替换 import 后发送。[`resolveDatabaseContext`](exports.md#page) 保持宿主优先、路径兜底和原会话缓存语义。媒体任务保留原 helper 的宽容归一化及错误名/码,流式 destroy 仍取消。
|
|
6
6
|
|
|
7
|
-
[`DatabaseFunctionInputMap`](exports.md#page) 可通过模块扩充,[`FunctionInputMap`](exports.md#page) 也可作为生成器的基础扩充接口;两者未提供函数时拒绝任意函数名和参数。不使用 Record<string,unknown>
|
|
7
|
+
[`DatabaseFunctionInputMap`](exports.md#page) 可通过模块扩充,[`FunctionInputMap`](exports.md#page) 也可作为生成器的基础扩充接口;两者未提供函数时拒绝任意函数名和参数。不使用 Record<string,unknown> 兜底伪造类型安全。新生成工程用 Function ID 输出映射推断 `data`:SQL 为 `DatabaseQueryResult<Row>`,无列 Schema 时 `Row=unknown`;缺失输出映射时直接调用编译失败,应核对 CLI/SDK 版本并运行 `contracts generate`。对自定义过 helper 的工程应先比对差异,不直接覆盖。
|
|
8
8
|
|
|
9
9
|
<!-- example: compat.ts -->
|
|
10
10
|
```ts
|
|
@@ -13,11 +13,14 @@ import {
|
|
|
13
13
|
invokeDatabaseMutationBatch,
|
|
14
14
|
type DatabaseFunctionResponse,
|
|
15
15
|
} from "@lark-base-open/base-database-app-sdk/page";
|
|
16
|
-
// CLI
|
|
16
|
+
// 类型扩充示例;业务工程由 CLI codegen 生成输入和输出映射。
|
|
17
17
|
declare module "@lark-base-open/base-database-app-sdk/page" {
|
|
18
18
|
interface DatabaseFunctionInputMap {
|
|
19
19
|
list_orders: { status: string };
|
|
20
20
|
}
|
|
21
|
+
interface DatabaseFunctionOutputMap {
|
|
22
|
+
list_orders: unknown;
|
|
23
|
+
}
|
|
21
24
|
}
|
|
22
25
|
export async function loadOrders(): Promise<DatabaseFunctionResponse> {
|
|
23
26
|
return invokeDatabaseFunction("list_orders", { status: "open" });
|
package/docs/exports.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
值:`AttachmentImage`、`BaseAppProvider`、`CAPABILITY_CATALOG`、`CapabilityUnavailableError`、`DatabaseUserMenu`、`DiagnosticCode`、`FloatingButton`、`SDKError`、`SITE_RUNTIME_PROTOCOL_VERSION`、`SiteChatbotStreamAdapter`、`SiteChatbotStreamError`、`SiteRuntimeApi`、`SiteRuntimeClient`、`SiteRuntimeErrorCode`、`SiteRuntimeEvent`、`SiteRuntimeFunction`、`SiteRuntimeInvocationError`、`UiLanguageContext`、`UserSelectorEditor`、`UserSelectorPanel`、`buildAttachmentCoverUrl`、`buildDatabaseInvokeFunctionPath`、`buildDatabaseInvokeGetPath`、`callSiteAIFunction`、`classifyRuntimeError`、`createSiteAIFunctionTask`、`createSiteRuntimeClient`、`createSiteRuntimeFetch`、`fetch`、`fetchAttachmentCover`、`fetchAttachmentDownloadUrl`、`getCapabilities`、`getCurrentUser`、`getDatabaseContext`、`getRuntimeCapabilities`、`getSiteAIFunctionTask`、`getUiLanguage`、`getUiLocale`、`hasCapability`、`hasRunnableMediaTask`、`initializeUiLanguage`、`installLinkGuard`、`invokeApi`、`invokeDatabaseFunction`、`invokeDatabaseMutationBatch`、`invokeHttp`、`invokeSiteAIFunctionStream`、`isValidSiteFunctionName`、`logout`、`normalizeSiteAIMediaTask`、`openAttachmentDownload`、`openLink`、`queryCapability`、`readCapabilities`、`readSiteAITextDelta`、`requestEdit`、`requireCapability`、`resolveDatabaseContext`、`selectUiLanguage`、`siteRuntime`、`startBaseApp`、`uploadAttachment`、`useBaseApp`、`useOptionalBaseApp`、`useUiLanguage`。
|
|
8
8
|
|
|
9
|
-
类型与值完整清单:`AttachmentImage`、`BaseAppContextValue`、`BaseAppHandle`、`BaseAppProvider`、`CAPABILITY_CATALOG`、`CallSiteAIFunctionParams`、`CapabilityContext`、`CapabilityDescriptor`、`CapabilityMap`、`CapabilityName`、`CapabilityQueryResult`、`CapabilityUnavailableError`、`CapabilityUnavailableReason`、`DatabaseAttachmentRef`、`DatabaseAudience`、`DatabaseContext`、`DatabaseEnv`、`DatabaseFunctionInputMap`、`DatabaseFunctionInvocation`、`DatabaseFunctionResponse`、`DatabaseUserMenu`、`DatabaseUserMenuProps`、`DevelopmentPairChallenge`、`DevelopmentPairProof`、`DiagnosticCategory`、`DiagnosticCode`、`FloatingButton`、`FloatingButtonProps`、`FunctionEnvelope`、`FunctionInputMap`、`FunctionMap`、`InvokeSiteAIFunctionStreamParams`、`JsonValue`、`LinkGuardOptions`、`RuntimeCapabilities`、`RuntimeChannel`、`RuntimeContextReader`、`RuntimeDiagnostic`、`SDKError`、`SDKErrorOptions`、`SITE_RUNTIME_PROTOCOL_VERSION`、`SiteAIAudioContentPart`、`SiteAICapabilityType`、`SiteAIFileContentPart`、`SiteAIFunctionArguments`、`SiteAIFunctionError`、`SiteAIFunctionOptions`、`SiteAIFunctionParams`、`SiteAIFunctionResult`、`SiteAIFunctionStreamCloseRequest`、`SiteAIFunctionStreamDone`、`SiteAIFunctionStreamError`、`SiteAIFunctionStreamHandle`、`SiteAIFunctionStreamMessage`、`SiteAIFunctionStreamOpenRequest`、`SiteAIFunctionVariables`、`SiteAIImageAsset`、`SiteAIImageContentPart`、`SiteAIImageGenerationInput`、`SiteAIImageTask`、`SiteAIMediaTask`、`SiteAIMediaTaskBase`、`SiteAIMessage`、`SiteAIMessageContentPart`、`SiteAIStreamDelta`、`SiteAIStreamMessageParam`、`SiteAITaskStatus`、`SiteAITextContentPart`、`SiteAITextDelta`、`SiteAITextMessageParam`、`SiteAIUserMessageParam`、`SiteAIVideoAsset`、`SiteAIVideoContentPart`、`SiteAIVideoGenerationInput`、`SiteAIVideoTask`、`SiteAttachmentTarget`、`SiteAttachmentUploadCancelRequest`、`SiteAttachmentUploadOptions`、`SiteAttachmentUploadPayload`、`SiteAttachmentUploadProgress`、`SiteAttachmentUploadRequest`、`SiteAttachmentUploadResult`、`SiteChatbotStreamAdapter`、`SiteChatbotStreamCloseRequest`、`SiteChatbotStreamError`、`SiteChatbotStreamMessage`、`SiteChatbotStreamOpenRequest`、`SiteFunctionDefinition`、`SiteFunctionInvokeRequest`、`SiteFunctionValidationIssue`、`SiteHttpCancelRequest`、`SiteHttpMethod`、`SiteHttpRequest`、`SiteHttpRequestInit`、`SiteHttpRequestOptions`、`SiteHttpResponse`、`SiteHttpResponseType`、`SiteOpenLinkRequest`、`SiteOpenLinkResult`、`SiteProjectEnv`、`SiteRuntimeApi`、`SiteRuntimeClient`、`SiteRuntimeContext`、`SiteRuntimeError`、`SiteRuntimeErrorCode`、`SiteRuntimeEvent`、`SiteRuntimeFunction`、`SiteRuntimeInvocationError`、`SiteRuntimeLoadFailedEvent`、`SiteRuntimeModeChangedEvent`、`SiteRuntimeReadyEvent`、`SiteRuntimeUserInfo`、`StartBaseAppOptions`、`UiLanguage`、`UiLanguageContext`、`User`、`UserSelectorAction`、`UserSelectorEditor`、`UserSelectorEditorProps`、`UserSelectorEditorValue`、`UserSelectorMode`、`UserSelectorPanel`、`UserSelectorPanelProps`、`UserSelectorSearchAction`、`UserSelectorValue`、`WriteResult`、`buildAttachmentCoverUrl`、`buildDatabaseInvokeFunctionPath`、`buildDatabaseInvokeGetPath`、`callSiteAIFunction`、`classifyRuntimeError`、`createSiteAIFunctionTask`、`createSiteRuntimeClient`、`createSiteRuntimeFetch`、`fetch`、`fetchAttachmentCover`、`fetchAttachmentDownloadUrl`、`getCapabilities`、`getCurrentUser`、`getDatabaseContext`、`getRuntimeCapabilities`、`getSiteAIFunctionTask`、`getUiLanguage`、`getUiLocale`、`hasCapability`、`hasRunnableMediaTask`、`initializeUiLanguage`、`installLinkGuard`、`invokeApi`、`invokeDatabaseFunction`、`invokeDatabaseMutationBatch`、`invokeHttp`、`invokeSiteAIFunctionStream`、`isValidSiteFunctionName`、`logout`、`normalizeSiteAIMediaTask`、`openAttachmentDownload`、`openLink`、`queryCapability`、`readCapabilities`、`readSiteAITextDelta`、`requestEdit`、`requireCapability`、`resolveDatabaseContext`、`selectUiLanguage`、`siteRuntime`、`startBaseApp`、`uploadAttachment`、`useBaseApp`、`useOptionalBaseApp`、`useUiLanguage`。
|
|
9
|
+
类型与值完整清单:`AttachmentImage`、`BaseAppContextValue`、`BaseAppHandle`、`BaseAppProvider`、`CAPABILITY_CATALOG`、`CallSiteAIFunctionParams`、`CapabilityContext`、`CapabilityDescriptor`、`CapabilityMap`、`CapabilityName`、`CapabilityQueryResult`、`CapabilityUnavailableError`、`CapabilityUnavailableReason`、`DatabaseAttachmentRef`、`DatabaseAudience`、`DatabaseContext`、`DatabaseEnv`、`DatabaseFunctionInputMap`、`DatabaseFunctionInvocation`、`DatabaseFunctionOutputMap`、`DatabaseFunctionResponse`、`DatabaseQueryResult`、`DatabaseUserMenu`、`DatabaseUserMenuProps`、`DevelopmentPairChallenge`、`DevelopmentPairProof`、`DiagnosticCategory`、`DiagnosticCode`、`FloatingButton`、`FloatingButtonProps`、`FunctionEnvelope`、`FunctionInputMap`、`FunctionMap`、`FunctionOutputMap`、`InvokeSiteAIFunctionStreamParams`、`JsonValue`、`LinkGuardOptions`、`RuntimeCapabilities`、`RuntimeChannel`、`RuntimeContextReader`、`RuntimeDiagnostic`、`SDKError`、`SDKErrorOptions`、`SITE_RUNTIME_PROTOCOL_VERSION`、`SiteAIAudioContentPart`、`SiteAICapabilityType`、`SiteAIFileContentPart`、`SiteAIFunctionArguments`、`SiteAIFunctionError`、`SiteAIFunctionOptions`、`SiteAIFunctionParams`、`SiteAIFunctionResult`、`SiteAIFunctionStreamCloseRequest`、`SiteAIFunctionStreamDone`、`SiteAIFunctionStreamError`、`SiteAIFunctionStreamHandle`、`SiteAIFunctionStreamMessage`、`SiteAIFunctionStreamOpenRequest`、`SiteAIFunctionVariables`、`SiteAIImageAsset`、`SiteAIImageContentPart`、`SiteAIImageGenerationInput`、`SiteAIImageTask`、`SiteAIMediaTask`、`SiteAIMediaTaskBase`、`SiteAIMessage`、`SiteAIMessageContentPart`、`SiteAIStreamDelta`、`SiteAIStreamMessageParam`、`SiteAITaskStatus`、`SiteAITextContentPart`、`SiteAITextDelta`、`SiteAITextMessageParam`、`SiteAIUserMessageParam`、`SiteAIVideoAsset`、`SiteAIVideoContentPart`、`SiteAIVideoGenerationInput`、`SiteAIVideoTask`、`SiteAttachmentTarget`、`SiteAttachmentUploadCancelRequest`、`SiteAttachmentUploadOptions`、`SiteAttachmentUploadPayload`、`SiteAttachmentUploadProgress`、`SiteAttachmentUploadRequest`、`SiteAttachmentUploadResult`、`SiteChatbotStreamAdapter`、`SiteChatbotStreamCloseRequest`、`SiteChatbotStreamError`、`SiteChatbotStreamMessage`、`SiteChatbotStreamOpenRequest`、`SiteFunctionDefinition`、`SiteFunctionInvokeRequest`、`SiteFunctionValidationIssue`、`SiteHttpCancelRequest`、`SiteHttpMethod`、`SiteHttpRequest`、`SiteHttpRequestInit`、`SiteHttpRequestOptions`、`SiteHttpResponse`、`SiteHttpResponseType`、`SiteOpenLinkRequest`、`SiteOpenLinkResult`、`SiteProjectEnv`、`SiteRuntimeApi`、`SiteRuntimeClient`、`SiteRuntimeContext`、`SiteRuntimeError`、`SiteRuntimeErrorCode`、`SiteRuntimeEvent`、`SiteRuntimeFunction`、`SiteRuntimeInvocationError`、`SiteRuntimeLoadFailedEvent`、`SiteRuntimeModeChangedEvent`、`SiteRuntimeReadyEvent`、`SiteRuntimeUserInfo`、`StartBaseAppOptions`、`UiLanguage`、`UiLanguageContext`、`User`、`UserSelectorAction`、`UserSelectorEditor`、`UserSelectorEditorProps`、`UserSelectorEditorValue`、`UserSelectorMode`、`UserSelectorPanel`、`UserSelectorPanelProps`、`UserSelectorSearchAction`、`UserSelectorValue`、`WriteResult`、`buildAttachmentCoverUrl`、`buildDatabaseInvokeFunctionPath`、`buildDatabaseInvokeGetPath`、`callSiteAIFunction`、`classifyRuntimeError`、`createSiteAIFunctionTask`、`createSiteRuntimeClient`、`createSiteRuntimeFetch`、`fetch`、`fetchAttachmentCover`、`fetchAttachmentDownloadUrl`、`getCapabilities`、`getCurrentUser`、`getDatabaseContext`、`getRuntimeCapabilities`、`getSiteAIFunctionTask`、`getUiLanguage`、`getUiLocale`、`hasCapability`、`hasRunnableMediaTask`、`initializeUiLanguage`、`installLinkGuard`、`invokeApi`、`invokeDatabaseFunction`、`invokeDatabaseMutationBatch`、`invokeHttp`、`invokeSiteAIFunctionStream`、`isValidSiteFunctionName`、`logout`、`normalizeSiteAIMediaTask`、`openAttachmentDownload`、`openLink`、`queryCapability`、`readCapabilities`、`readSiteAITextDelta`、`requestEdit`、`requireCapability`、`resolveDatabaseContext`、`selectUiLanguage`、`siteRuntime`、`startBaseApp`、`uploadAttachment`、`useBaseApp`、`useOptionalBaseApp`、`useUiLanguage`。
|
|
10
10
|
|
|
11
11
|
## server
|
|
12
12
|
|
package/examples/compat.ts
CHANGED
|
@@ -3,11 +3,14 @@ import {
|
|
|
3
3
|
invokeDatabaseMutationBatch,
|
|
4
4
|
type DatabaseFunctionResponse,
|
|
5
5
|
} from "@lark-base-open/base-database-app-sdk/page";
|
|
6
|
-
// CLI
|
|
6
|
+
// 类型扩充示例;业务工程由 CLI codegen 生成输入和输出映射。
|
|
7
7
|
declare module "@lark-base-open/base-database-app-sdk/page" {
|
|
8
8
|
interface DatabaseFunctionInputMap {
|
|
9
9
|
list_orders: { status: string };
|
|
10
10
|
}
|
|
11
|
+
interface DatabaseFunctionOutputMap {
|
|
12
|
+
list_orders: unknown;
|
|
13
|
+
}
|
|
11
14
|
}
|
|
12
15
|
export async function loadOrders(): Promise<DatabaseFunctionResponse> {
|
|
13
16
|
return invokeDatabaseFunction("list_orders", { status: "open" });
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lark-base-open/base-database-app-sdk",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Base Database 页面与服务端 SDK、平台组件及测试工具",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": [
|
|
@@ -61,6 +61,7 @@
|
|
|
61
61
|
"docs",
|
|
62
62
|
"examples",
|
|
63
63
|
"README.md",
|
|
64
|
+
"CHANGELOG.md",
|
|
64
65
|
"LICENSE",
|
|
65
66
|
"capabilities.json",
|
|
66
67
|
"development-pairing.json"
|
package/dist/chunk-5XIFZ4AH.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as Me,b as Q,c as Oe}from"./chunk-ZKBZAK4L.js";import{a as pe}from"./chunk-3JX3FIBG.js";import{a as F}from"./chunk-OHPYKFCM.js";import{createContext as Ht,useContext as Xe}from"react";import{createContext as It,useContext as Mt,useEffect as Ot,useSyncExternalStore as Ft}from"react";import{capabilityNames as Rt}from"@lark-base-open/base-site-channel/capabilities";import*as S from"@lark-base-open/base-site-channel/runtime";import{SITE_RUNTIME_PROTOCOL_VERSION as En,SiteRuntimeApi as ne,SiteRuntimeEvent as Un,SiteRuntimeFunction as Sn,SiteRuntimeErrorCode as Pn,readSiteAITextDelta as xn,isValidSiteFunctionName as An}from"@lark-base-open/base-site-channel/runtime-contract";var V=()=>{throw new pe(Q.ContextInvalid,"\u5BBF\u4E3B\u80FD\u529B\u5B57\u6BB5\u65E0\u6548")};function me(e){if(!e||typeof e!="object")return V();if(e.capabilities===void 0)return Object.fromEntries(Object.entries(Me).filter(([,o])=>o.baseline).map(([o])=>[o,{version:1}]));let t=e.capabilities;if(!t||typeof t!="object"||Array.isArray(t))return V();let n=Object.entries(t);return n.some(([,o])=>!o||typeof o!="object"||Array.isArray(o)||!Number.isSafeInteger(o.version)||o.version<=0)?V():Object.fromEntries(n.map(([o,r])=>[o,{version:r.version}]))}function wt(e,t,n=1){if(!Number.isSafeInteger(n)||n<1)return V();let o=me(e);return Object.prototype.hasOwnProperty.call(o,t)&&o[t].version>=n}async function vt(e=E){return me(await e.getRuntimeContext())}var _n=vt;async function Ct(e,t=1,n=E){let o=await n.getRuntimeContext(),r=me(o),s=wt(o,e,t),a=o.capabilityUnavailable;if(a!==void 0&&(!a||typeof a!="object"||Array.isArray(a)))return V();let i=a&&Object.prototype.hasOwnProperty.call(a,e)?a[e]:void 0;return i!==void 0&&(!i||typeof i!="object"||!["permission-denied","region-unavailable","temporarily-unavailable"].includes(i.reason)||typeof i.retryable!="boolean")?V():{name:e,requiredVersion:t,version:Object.prototype.hasOwnProperty.call(r,e)?r[e].version:null,supported:s,source:o.capabilities===void 0?"host-baseline":"advertised",availability:s?i?.reason??"unknown":"unsupported"}}async function Fe(e,t=1,n=E){let o=await n.getRuntimeContext(),r=await Ct(e,t,{getRuntimeContext:async()=>o});if(!r.supported)throw new Oe(e,t);let s={"permission-denied":Q.PermissionDenied,"region-unavailable":Q.RegionUnavailable,"temporarily-unavailable":Q.TemporarilyUnavailable};if(r.availability in s)throw new pe(s[r.availability],"\u5BBF\u4E3B\u660E\u786E\u62D2\u7EDD\u6B64\u80FD\u529B",void 0,o.capabilityUnavailable?.[e]?.retryable)}function Ne(e,t){let n,o=!1,r,s=new Promise(a=>{r=a});return e.registerApi(F.pairApi,async a=>{if(!a||!/^[A-Za-z0-9_-]{43}$/.test(a.challenge))throw new Error("INVALID_PAIRING_CHALLENGE");n=a.challenge;let i=n;o&&(o=!1,s=new Promise(u=>{r=u}));let c=await t(F.endpoint,{method:"POST",credentials:"omit",cache:"no-store",redirect:"error",headers:{"Content-Type":"application/json"},body:JSON.stringify({challenge:i})});if(!c.ok)throw new Error("DEVELOPMENT_PAIRING_FAILED");let d=await c.json();if(!/^[A-Za-z0-9_-]{43}$/.test(d.proof))throw new Error("INVALID_PAIRING_PROOF");return{proof:d.proof}}),e.subscribeEvent(F.pairedEvent,a=>{n&&a?.challenge===n&&(o=!0,r())}),{reset:()=>{n=void 0,o&&(o=!1,s=new Promise(a=>{r=a}))},wait:async()=>{let a;do a=s,await a;while(a!==s)}}}var je=typeof window<"u"&&window.location.protocol==="http:"&&window.location.hostname===F.host&&Number(window.location.port)>=F.portMin&&Number(window.location.port)<=F.portMax;var $e=S.siteRuntime,T=$e.getChannel?.()??$e.channel,Et=je&&typeof window<"u"&&window.parent!==window?Ne(T,globalThis.fetch.bind(globalThis)):void 0;function Be(e,t=async()=>{}){let n=new Map,o=async(r,s)=>{await t();for(let a of Rt(r,s))try{await Fe(a,1,{getRuntimeContext:()=>e.invokeApi(ne.RuntimeContext,void 0)})}catch(i){throw i instanceof Error&&"code"in i?Object.assign(new S.SiteRuntimeInvocationError(String(i.code),i.message),i):i}};return{subscribeEvent:(r,s)=>e.subscribeEvent(r,s),emitEvent:async(r,s)=>(await o(r,s),e.emitEvent(r,s)),invokeApi:async(r,s,a)=>{let i=s?.requestId??s?.subscriptionId??s?.uploadId,c=r===ne.HttpRequestCancel||r===ne.AttachmentUploadCancel||r.endsWith(".close");if(c&&i&&n.has(i)){n.get(i).canceled=!0;return}let d={canceled:!1};!c&&i&&n.set(i,d);try{if(await o(r,s),d.canceled)throw new DOMException("The operation was aborted","AbortError");return i&&n.delete(i),await e.invokeApi(r,s,a)}finally{i&&n.get(i)===d&&n.delete(i)}}}}var Ut={invokeApi:T.invokeApi.bind(T),emitEvent:T.emitEvent.bind(T),subscribeEvent:T.subscribeEvent.bind(T)},ge=Be(Ut,async()=>{if(typeof window<"u"&&window.parent===window)throw new S.SiteRuntimeInvocationError("CHANNEL_UNAVAILABLE","\u9875\u9762\u672A\u8FDE\u63A5\u5BBF\u4E3B channel");await Et?.wait()});T.invokeApi=ge.invokeApi;T.emitEvent=ge.emitEvent;var fe=class extends S.SiteRuntimeClient{constructor(t){super(t?Be(t):ge)}},jn=e=>new fe(e),E=S.siteRuntime,{invokeHttp:oe,invokeApi:$n,getCurrentUser:Y,logout:he,requestEdit:St,uploadAttachment:Bn,openLink:re}=E,Pt=(e=E,t)=>S.createSiteRuntimeFetch(e,t),L=Pt();var xt=oe,At=/^\/?(preview\/)?app\/([^/]+)(\/|$)/,He=/^[A-Za-z0-9_-]+$/,ze="/space/api/bitable/site/v1",kt="/space/api/box/file/temporary_download_url",G="preview",W=null;function Tt(){let t=(typeof globalThis.location>"u"?void 0:globalThis.location)?.ancestorOrigins?.[0];if(t)return t;let n=typeof globalThis.document>"u"?"":globalThis.document.referrer;if(!n)return"";try{return new URL(n).origin}catch{return""}}function be(){let e=typeof globalThis.location>"u"?"":globalThis.location.pathname,t=At.exec(e),n=Tt();return t?{env:t[1]?G:"prod",gatewayOrigin:n,token:decodeURIComponent(t[2]??"")}:{env:"prod",gatewayOrigin:n,token:""}}function Z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _t(e){return e===G||e==="prod"}function Lt(e){if(!Z(e))return{};let t=typeof e.siteToken=="string"?e.siteToken.trim():"";return{...t?{token:t}:{},..._t(e.env)?{env:e.env}:{}}}async function N(){return W||(W=(async()=>{let e=be(),t={};try{t=Lt(await E.getRuntimeContext())}catch(o){console.warn("Could not read the host Runtime context; inferring it from the artifact path",o)}let n={env:t.env??e.env,gatewayOrigin:e.gatewayOrigin,token:t.token??e.token};return n.token||console.error("Cannot determine the app token: the host did not provide siteToken and the current path does not match an artifact path"),n})().catch(e=>{throw W=null,e}),W)}function ye(e){return!!(e.tableId.trim()&&e.fieldId.trim()&&e.recordId.trim()&&e.fileToken.trim())}function qe(e,t){return JSON.stringify({bitablePerm:{tableId:t.tableId,attachments:{[t.fieldId]:{[t.recordId]:[t.fileToken]}},siteToken:e.token,siteEnv:e.env}})}function Ve(e,t){if(t instanceof Error)return t;let n=Z(t)?t.code:void 0,o=typeof n=="string"||typeof n=="number"?String(n):"",r=o==="REQUEST_TIMEOUT"||o==="10005"?`${e} timed out`:`${e} failed`;return Object.assign(new Error(`${r}${o?` (code ${o})`:""}`),{cause:t,...o?{code:o}:{}})}async function Ge(e,t=360,n={}){if(n.signal?.throwIfAborted(),!ye(e)||!Number.isFinite(t)||t<=0)throw new Error("Attachment location or image size is invalid");let o=await N();if(n.signal?.throwIfAborted(),!o.token)throw new Error("Cannot load the attachment image without an app token");let r=[120,360,720,1280].find(c=>c>=t)??1280,s=new URLSearchParams({extra:qe(o,e),width:String(r),height:String(r),policy:"allow_up",fallback_source:"1"}),a=await xt({url:`/space/api/box/stream/download/v2/cover/${encodeURIComponent(e.fileToken)}?${s}`,init:{method:"GET",responseType:"arrayBuffer",timeoutMs:45e3},signal:n.signal}).catch(c=>{throw Ve("Attachment image request",c)});if(!a.ok){let c=a.headers.get("x-tt-logid");throw new Error(`Failed to load attachment image: HTTP ${a.status}${c?`, LogID ${c}`:""}`)}let i=await a.blob();if(!i.size||!i.type.startsWith("image/"))throw new Error("The host did not return a valid image");return i}async function Dt(e,t){if(!e.token)throw new Error("Cannot get an attachment download URL without an app token");if(!ye(t))throw new Error("Cannot get an attachment download URL: the attachment location is incomplete");let n=await L(kt,{body:JSON.stringify({extra:qe(e,t),file_token:t.fileToken}),headers:{"content-type":"application/json"},method:"POST"}).catch(i=>{throw Ve("Attachment download URL request",i)}),o=n.headers?.get("x-tt-logid")?.trim(),r;try{r=await n.json()}catch{throw new Error(n.ok?`Attachment download URL response is not valid JSON${o?`, LogID ${o}`:""}`:`Failed to get attachment download URL: HTTP ${n.status}${o?`, LogID ${o}`:""}`)}let s=Z(r)?r.code:void 0;if(typeof s=="number"&&s!==0||typeof s=="string"&&s.trim()!==""&&s.trim()!=="0"){let i=new Error(`Attachment service could not provide a download URL (code ${String(s)}${o?`, LogID ${o}`:""})`);throw Object.assign(i,{code:String(s),cause:r})}if(!n.ok)throw new Error(`Failed to get attachment download URL: HTTP ${n.status}${o?`, LogID ${o}`:""}`);let a=Z(r)&&Z(r.data)&&typeof r.data.url=="string"?r.data.url.trim():"";if(!a)throw new Error(`Attachment download URL response is missing data.url${o?`, LogID ${o}`:""}`);return a}function Je(e){let t=new URLSearchParams;e.env===G&&t.set("env",G);let n=t.toString(),o=`${ze}/${encodeURIComponent(e.token)}/invoke_get`;return n?`${o}?${n}`:o}function Ke(e,t){if(!He.test(t))throw new TypeError(`functionId ${t} does not match the required pattern ${String(He)}`);let n=`${ze}/${encodeURIComponent(e.token)}/functions/${encodeURIComponent(t)}/invoke`;return e.env===G?`${n}?env=${encodeURIComponent(G)}`:n}async function qn(...[e,t]){let n=await N();if(!n.token)throw new Error(`Cannot invoke Function ${e} without an app token`);let o=await oe({url:Ke(n,e),init:{body:JSON.stringify({params:t}),headers:{"content-type":"application/json"},method:"POST"}});if(!o.ok)throw new Error(`Function ${e} request failed: HTTP ${o.status}`);return await o.json()}async function Vn(e,t){if(!Array.isArray(t)||t.length<1||t.length>200||t.some(r=>r===null||typeof r!="object"||Array.isArray(r)))throw new TypeError("Mutation batch requires 1 to 200 named parameter objects");let n=await N();if(!n.token)throw new Error("\u5E94\u7528 token \u672A\u786E\u5B9A\uFF0C\u65E0\u6CD5\u8C03\u7528 Mutation");let o=await oe({url:Ke(n,e),init:{body:JSON.stringify({batch:t.map(r=>({params:r}))}),headers:{"content-type":"application/json"},method:"POST"}});if(!o.ok)throw new Error(`Mutation \u8C03\u7528\u5931\u8D25\uFF1AHTTP ${o.status}`);return await o.json()}async function Gn(e,t){let n=await Dt(e,t);if(!(await re(n)).opened)throw new Error("The host did not open the attachment download link")}function Jn(e,t,n=360){if(!e.gatewayOrigin||!e.token||!ye(t))return"";let o=[120,360,720,1280].find(s=>s>=n)??1280,r=new URLSearchParams({extra:JSON.stringify({bitablePerm:{tableId:t.tableId,attachments:{[t.fieldId]:{[t.recordId]:[t.fileToken]}},baseAppToken:e.token}}),width:String(o),height:String(o),policy:"allow_up",fallback_source:"1"});return`${e.gatewayOrigin}/space/api/box/stream/download/v2/cover/${encodeURIComponent(t.fileToken)}?${r.toString()}`}var Re=It(void 0),Ye=[{id:"en",locale:"en-US",match:/^en(?:-|$)/},{id:"zh",locale:"zh-CN",match:/^zh(?:-|$)/},{id:"ja",locale:"ja-JP",match:/^ja(?:-|$)/}],ve=new Set,We,we=null;function Ce(e){if(typeof e!="string")return;let t=e.trim().replace(/_/g,"-").toLowerCase();return Ye.find(({match:n})=>n.test(t))?.id}function Nt(){return typeof navigator>"u"?void 0:navigator.language}function jt(e,t){return Ce(e)??Ce(t)??"en"}function j(){return We??jt(void 0,Nt())}function Ee(e=j()){return Ye.find(({id:t})=>t===e)?.locale??"en-US"}function $t(e){return ve.add(e),()=>ve.delete(e)}function Qe(e){We=Ce(e);let t=j();Ze(t);for(let n of ve)n();return t}function Ze(e){typeof document<"u"&&(document.documentElement.lang=Ee(e))}function Bt(){return we||(Ze(j()),we=E.getRuntimeContext().then(e=>Qe(e?.locale)).catch(()=>Qe(void 0))),we}function P(){let e=Mt(Re),t=Ft($t,j,()=>"en");return Ot(()=>{e||Bt()},[e]),e??t}import{jsx as Ue}from"react/jsx-runtime";var Se=Ht(null);function no({children:e,...t}){return Ue(Se.Provider,{value:t,children:Ue(Re.Provider,{value:t.locale,children:Ue("div",{className:"base-app-platform","data-theme":t.theme,children:e})})})}function oo(){let e=Xe(Se);if(!e)throw new Error("BASE_APP_PROVIDER_REQUIRED");return e}function ae(){return Xe(Se)}import{useState as X,useEffect as nt}from"react";import{QueryClient as zt}from"@tanstack/react-query";var Pe=new zt({defaultOptions:{queries:{retry:!1,staleTime:3e4,gcTime:3e4}}});function ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function se(e,t){let n=e[t];return typeof n=="string"?n.trim():""}function qt(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function $(){return{baseBindings:[],name:"",description:"",isOwner:!1,allowEdit:!1,organization:""}}function Vt(){let e=document.querySelector('meta[name="description"]');return e instanceof HTMLMetaElement?e:null}function Gt(e){if(e.name&&(document.title=e.name),e.description){let t=Vt();t&&(t.content=e.description)}}function Jt(e){return Array.isArray(e)?e.reduce((t,n)=>{if(!ie(n))return t;let o=se(n,"baseToken");return o&&t.push({baseToken:o,tableIds:qt(n.tableIds)}),t},[]):[]}function Kt(e){if(!ie(e)||e.code!==0)return $();let t=e.data;if(!ie(t))return $();let n=t.site;return ie(n)?{baseBindings:Jt(n.baseBindings),description:se(n,"description"),name:se(n,"name"),isOwner:t.isOwner===!0,allowEdit:n.allowEdit===void 0?t.isOwner===!0:n.allowEdit===!0,organization:se(n,"organization")}:$()}async function et(e){try{let t=await L(Je(e),{method:"GET"});if(!t.ok)return $();let n=await t.json(),o=Kt(n);return Gt(o),o}catch{return $()}}async function J(){let e=await N();if(!e.token)return $();let t=await Y().catch(()=>null);return t?.userId?Pe.fetchQuery({queryKey:["project-meta",e.token,e.env,t.userId],queryFn:()=>et(e)}):et(e)}var Qt="https://feishu.cn/base/site/detail/overview";async function tt(){try{await E.requestEdit();return}catch{let{token:e}=await N(),t=new URL(Qt);if(t.searchParams.set("token",e),!(await re(t.toString())).opened)throw new Error("Management page was not opened")}}import{jsx as B,jsxs as ot}from"react/jsx-runtime";var Yt={en:{openFailed:"Unable to open the management page. Please try again.",editSite:"Edit and manage your apps",hidePanel:"Hide until next visit",hiddenConfirmation:"Edit button hidden until you reopen the app",dismissNotification:"Dismiss notification"},zh:{openFailed:"\u65E0\u6CD5\u6253\u5F00\u7BA1\u7406\u9875\u9762\uFF0C\u8BF7\u91CD\u8BD5",editSite:"\u7F16\u8F91\u4E0E\u7BA1\u7406\u5E94\u7528",hidePanel:"\u9690\u85CF\u9762\u677F",hiddenConfirmation:"\u7F16\u8F91\u6309\u94AE\u5DF2\u9690\u85CF\uFF0C\u76F4\u81F3\u4E0B\u6B21\u91CD\u65B0\u6253\u5F00\u5E94\u7528",dismissNotification:"\u5173\u95ED\u63D0\u793A"},ja:{openFailed:"\u7BA1\u7406\u30DA\u30FC\u30B8\u3092\u958B\u3051\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u3082\u3046\u4E00\u5EA6\u304A\u8A66\u3057\u304F\u3060\u3055\u3044\u3002",editSite:"\u30A2\u30D7\u30EA\u3092\u7DE8\u96C6\u30FB\u7BA1\u7406",hidePanel:"\u6B21\u56DE\u306E\u30A2\u30AF\u30BB\u30B9\u307E\u3067\u975E\u8868\u793A",hiddenConfirmation:"\u7DE8\u96C6\u30DC\u30BF\u30F3\u3092\u975E\u8868\u793A\u306B\u3057\u307E\u3057\u305F\u3002\u30A2\u30D7\u30EA\u3092\u518D\u5EA6\u958B\u304F\u3068\u8868\u793A\u3055\u308C\u307E\u3059",dismissNotification:"\u901A\u77E5\u3092\u9589\u3058\u308B"}};function vo({position:e="bottom-right",className:t="",slots:n={}}){let o=Yt[P()],[r,s]=X(!1),[a,i]=X(!1),[c,d]=X(!1),[u,p]=X(!1),[g,f]=X(!1);nt(()=>{let b=!0;return J().then(M=>{b&&s(M.allowEdit&&be().env==="prod")}).catch(()=>{}),()=>{b=!1}},[]),nt(()=>{if(!c)return;let b=setTimeout(()=>d(!1),3e3);return()=>clearTimeout(b)},[c]);let m=n.trigger,v=n.tooltip;return r?a?c?ot("div",{className:"base-app-platform base-app-notice",role:"status",children:[o.hiddenConfirmation,B("button",{"aria-label":o.dismissNotification,onClick:()=>d(!1),children:"\xD7"})]}):null:ot("div",{className:`base-app-platform base-app-floating ${t}`,"data-position":e,children:[u?B("div",{role:"alert",children:o.openFailed}):null,g?B("div",{role:"tooltip",children:v?B(v,{text:o.editSite}):o.editSite}):null,B("button",{"aria-label":o.editSite,onFocus:()=>f(!0),onBlur:()=>f(!1),onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),onClick:()=>{p(!1),tt().catch(()=>p(!0))},children:m?B(m,{}):"\u270E"}),B("button",{"aria-label":o.hidePanel,onClick:()=>{i(!0),d(!0)},children:"\xD7"})]}):null}var xe=new Set;function rt(e){return xe.add(e),()=>{xe.delete(e)}}function at(){for(let e of xe)e()}import{useEffect as Wt,useState as st}from"react";import*as D from"@radix-ui/react-popover";async function it(){try{let e=await Y();if(typeof e?.name=="string"&&e.name)return{name:e.name,avatarUrl:typeof e.avatarUrl=="string"?e.avatarUrl:"",tenantName:""}}catch{}try{let e=await L("/space/api/user/",{headers:{accept:"application/json"}});if(!e.ok)return null;let n=(await e.json()).data;return!n||typeof n.name!="string"||!n.name?null:{name:n.name,avatarUrl:typeof n.avatar_url=="string"?n.avatar_url:"",tenantName:typeof n.tenant_name=="string"?n.tenant_name:""}}catch{return null}}import{Fragment as Xt,jsx as x,jsxs as Ae}from"react/jsx-runtime";var Zt={en:{account:"Account",logout:"Log out"},zh:{account:"\u8D26\u53F7",logout:"\u9000\u51FA\u767B\u5F55"},ja:{account:"\u30A2\u30AB\u30A6\u30F3\u30C8",logout:"\u30ED\u30B0\u30A2\u30A6\u30C8"}};function Io({audience:e="enterprise",align:t="right",side:n="down",showName:o=!0,className:r="",slots:s={}}){let[a,i]=st(null),[c,d]=st(""),u=ae(),p=Zt[P()];if(Wt(()=>{if(e!=="enterprise")return;let m=!0;return Promise.all([it(),J().catch(()=>null)]).then(([v,b])=>{m&&(i(v),d(v?.tenantName||b?.organization||""))}),()=>{m=!1}},[e]),e!=="enterprise"||!a)return null;let g=s.trigger,f=s.organization;return Ae(D.Root,{children:[x(D.Trigger,{asChild:!0,children:x("button",{className:`base-app-platform base-app-user-menu ${r}`,"aria-label":p.account,children:g?x(g,{user:a}):Ae(Xt,{children:[a.avatarUrl?x("img",{src:a.avatarUrl,alt:"",referrerPolicy:"no-referrer"}):x("span",{children:a.name.slice(0,1)}),o?a.name:null]})})}),x(D.Portal,{children:Ae(D.Content,{"data-theme":u?.theme,className:"base-app-platform base-app-popover",align:t==="right"?"end":"start",side:n==="up"?"top":"bottom",sideOffset:8,collisionPadding:8,children:[x("strong",{children:a.name}),f?x(f,{name:c}):x("p",{children:c}),x("button",{onClick:()=>{at(),Pe.clear(),he().catch(()=>{for(let m of["base-site-session","session","sl_session"])document.cookie=`${m}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;window.location.reload()})},children:p.logout})]})})]})}import{useEffect as ce,useRef as dt,useState as z}from"react";import{Command as ee}from"cmdk";import{QueryClient as dn,useQuery as pn}from"@tanstack/react-query";var en="/space/api/mention/recommend.v2/",tn="8",nn="4",on="0",rn=20,ct={en:{businessError:e=>`Could not search members (error code ${e})`,httpError:e=>`Member search request failed: HTTP ${e}`,invalidResponse:"Member search response has an invalid structure",noBoundBase:"Cannot search members: the application is not bound to a Base"},zh:{businessError:e=>`\u641C\u7D22\u6210\u5458\u5931\u8D25\uFF08\u9519\u8BEF\u7801 ${e}\uFF09`,httpError:e=>`\u641C\u7D22\u6210\u5458\u8BF7\u6C42\u5931\u8D25\uFF1AHTTP ${e}`,invalidResponse:"\u6210\u5458\u641C\u7D22\u54CD\u5E94\u7ED3\u6784\u65E0\u6548",noBoundBase:"\u65E0\u6CD5\u641C\u7D22\u6210\u5458\uFF1A\u5E94\u7528\u5C1A\u672A\u7ED1\u5B9A\u591A\u7EF4\u8868\u683C"},ja:{businessError:e=>`\u30E1\u30F3\u30D0\u30FC\u3092\u691C\u7D22\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08\u30A8\u30E9\u30FC\u30B3\u30FC\u30C9 ${e}\uFF09`,httpError:e=>`\u30E1\u30F3\u30D0\u30FC\u691C\u7D22\u306E\u30EA\u30AF\u30A8\u30B9\u30C8\u306B\u5931\u6557\u3057\u307E\u3057\u305F\uFF1AHTTP ${e}`,invalidResponse:"\u30E1\u30F3\u30D0\u30FC\u691C\u7D22\u306E\u5FDC\u7B54\u5F62\u5F0F\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093",noBoundBase:"\u30E1\u30F3\u30D0\u30FC\u3092\u691C\u7D22\u3067\u304D\u307E\u305B\u3093\uFF1A\u30A2\u30D7\u30EA\u306BBase\u304C\u95A2\u9023\u4ED8\u3051\u3089\u308C\u3066\u3044\u307E\u305B\u3093"}};async function lt(e,t,n){let o=t??j(),r=ct[o],a=(await J()).baseBindings[0]?.baseToken;if(!a)throw new Error(r.noBoundBase);let i=new URLSearchParams({config_source:"0",obj_type:tn,source:nn,token:a,type:on,user_type:"0",content:e.trim().slice(0,50)}).toString(),c=await L(en,{signal:n,body:i,headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST"});if(!c.ok)throw new Error(r.httpError(c.status));let d=await c.json();return{code:0,msg:"ok",data:an(d,o)}}function an(e,t=j()){let n=Ee(t),o=ct[t],r=sn(e,o);if(!r)throw new Error(o.invalidResponse);let s=r.entities,a=H(s)?s.users:void 0;if(!H(a)||!Array.isArray(r.result_list))throw new Error(o.invalidResponse);let i=[],c=new Set;for(let d of r.result_list){if(!H(d)||Number(d.type)!==0)continue;let u=h(d.token);if(!u)continue;let p=a[u];if(!H(p))continue;let g=h(p.user_id)||h(p.id)||u,f=cn(p,n);if(!g||!f||c.has(g))continue;c.add(g);let m=h(p.avatar_url),v=h(p.open_id);if(i.push({avatar:{avatar_72:m,avatar_240:m,avatar_640:m,avatar_origin:m},department_ids:un(p.department_ids),description:ln(p,n),is_external:p.is_external===!0,name:f,user_id:g,...v?{open_id:v}:{}}),i.length>=rn)break}return{users:i}}function sn(e,t){if(H(e)){if(typeof e.code=="number"&&e.code!==0){let n=h(e.msg);throw Object.assign(new Error(n||t.businessError(e.code)),{code:String(e.code),cause:e})}return"entities"in e&&"result_list"in e?e:H(e.data)?e.data:void 0}}function cn(e,t){return ut(e.display_name,t)||(t.toLowerCase().startsWith("zh")?h(e.cn_name):h(e.en_name))||h(e.name)||h(e.en_name)||h(e.cn_name)}function ln(e,t){let n=e.is_external===!0?e.i18n_tenant:e.i18n_department;return ut(n,t)||h(e.department)}function ut(e,t){if(typeof e=="string")return e.trim();if(!H(e))return"";let n=t.toLowerCase().replace("-","_"),o=n.split("_")[0]??"",r=o==="zh"?h(e.zh_cn)||h(e.en_us):h(e.en_us)||h(e.zh_cn);return h(e[n])||h(e[o])||r}function h(e){return typeof e=="string"?e.trim():""}function un(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{Fragment as mt,jsx as R,jsxs as ke}from"react/jsx-runtime";var ft={en:{invalidResponse:"Member search response has an invalid structure",loading:"Loading...",memberList:"Member list",noMatches:"No matching members. Try another search term.",noRecommendations:"No recommended members yet",recordCreator:"Add the person who created this record",searchFailed:"Member search failed",searchFailedCode:e=>`Could not search members (error code ${e})`,searchMembers:"Search members"},zh:{invalidResponse:"\u6210\u5458\u641C\u7D22\u54CD\u5E94\u7ED3\u6784\u65E0\u6548",loading:"\u52A0\u8F7D\u4E2D...",memberList:"\u6210\u5458\u5217\u8868",noMatches:"\u6CA1\u6709\u5339\u914D\u7684\u6210\u5458\uFF0C\u8BF7\u6362\u4E2A\u5173\u952E\u8BCD",noRecommendations:"\u6682\u65E0\u63A8\u8350\u6210\u5458",recordCreator:"\u6DFB\u52A0\u6B64\u8BB0\u5F55\u7684\u4EBA\u5458",searchFailed:"\u641C\u7D22\u6210\u5458\u5931\u8D25",searchFailedCode:e=>`\u641C\u7D22\u6210\u5458\u5931\u8D25\uFF08\u9519\u8BEF\u7801 ${e}\uFF09`,searchMembers:"\u641C\u7D22\u6210\u5458"},ja:{invalidResponse:"\u30E1\u30F3\u30D0\u30FC\u691C\u7D22\u306E\u5FDC\u7B54\u5F62\u5F0F\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093",loading:"\u8AAD\u307F\u8FBC\u307F\u4E2D...",memberList:"\u30E1\u30F3\u30D0\u30FC\u4E00\u89A7",noMatches:"\u4E00\u81F4\u3059\u308B\u30E1\u30F3\u30D0\u30FC\u304C\u3044\u307E\u305B\u3093\u3002\u5225\u306E\u30AD\u30FC\u30EF\u30FC\u30C9\u3067\u691C\u7D22\u3057\u3066\u304F\u3060\u3055\u3044\u3002",noRecommendations:"\u304A\u3059\u3059\u3081\u306E\u30E1\u30F3\u30D0\u30FC\u304C\u3044\u307E\u305B\u3093",recordCreator:"\u3053\u306E\u30EC\u30B3\u30FC\u30C9\u306E\u4F5C\u6210\u8005\u3092\u8FFD\u52A0",searchFailed:"\u30E1\u30F3\u30D0\u30FC\u306E\u691C\u7D22\u306B\u5931\u6557\u3057\u307E\u3057\u305F",searchFailedCode:e=>`\u30E1\u30F3\u30D0\u30FC\u3092\u691C\u7D22\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08\u30A8\u30E9\u30FC\u30B3\u30FC\u30C9 ${e}\uFF09`,searchMembers:"\u30E1\u30F3\u30D0\u30FC\u3092\u691C\u7D22"}};function le(e){let[t,n]=z(!1),[o,r]=z(!1);ce(()=>r(!0),[]);let s=P(),a=ft[s],[i]=z(()=>new dn({defaultOptions:{queries:{retry:!1,staleTime:3e4,gcTime:3e4}}}));ce(()=>{let l=rt(()=>{n(!0),i.clear()});return()=>{l(),i.clear()}},[i]);let c=Object.prototype.hasOwnProperty.call(e,"value"),d=dt(c);ce(()=>{c!==d.current&&console.warn("UserSelectorPanel controlled mode changed")},[c]);let[u,p]=z(e.defaultValue),g=c?e.value:u,f=Array.isArray(g)?g:g?[g]:[],[m,v]=z(""),[b,M]=z(""),[A,K]=z(!1),O=dt(!1);ce(()=>{if(A)return;let l=setTimeout(()=>M(m.trim()),m.trim()?400:0);return()=>clearTimeout(l)},[m,A]);let y=pn({queryKey:["members",s,b],queryFn:async({signal:l})=>{let C=await lt(b,s,l);return mn(C,s)},enabled:!t&&o&&!A&&m.trim()===b},i),w=e.loading||y.isFetching||m.trim()!==b,k=!t&&!w&&!y.error&&y.data?[...y.data.users,...f.filter(l=>!y.data.users.some(C=>C.user_id===l.user_id))]:[],U=(l,C)=>{v(l),e.onSearch?.(l,{action:C})},ue=()=>{U("","AutoClear"),e.onClose?.()},yt=l=>{if(O.current)return;let C=f.some(de=>de.user_id===l.user_id),te=e.mode==="multiple"?C?f.filter(de=>de.user_id!==l.user_id):[...f,l]:C?void 0:l;c||p(te),e.onChange?.(te,{option:l,action:C?"Remove":"Select"}),C||e.onSelect?.(l,{option:l}),e.mode==="multiple"?U("","AutoClear"):ue()},_e=e.slots?.empty,Le=e.slots?.loading,De=e.slots?.option,Ie=e.slots?.footer;return ke(ee,{shouldFilter:!1,loop:!0,className:`base-app-platform base-app-selector ${e.className??""}`,label:a.memberList,children:[R(ee.Input,{autoFocus:!0,placeholder:a.searchMembers,"aria-label":a.searchMembers,value:m,onValueChange:l=>U(l,"Input"),onCompositionStart:()=>{O.current=!0,K(!0)},onCompositionEnd:()=>{O.current=!1,K(!1)},onKeyDown:l=>{if(e.onKeyDown?.(l),l.defaultPrevented){l.stopPropagation();return}if(O.current||fn(l)){l.stopPropagation();return}l.key==="Escape"&&(l.preventDefault(),ue())}}),R(ee.List,{"aria-label":a.memberList,"aria-multiselectable":e.mode==="multiple"||void 0,children:w?R("div",{role:"status",children:Le?R(Le,{}):a.loading}):y.error?R("div",{role:"alert",children:a.searchFailed}):ke(mt,{children:[e.onSelectRecordCreator?R(ee.Item,{value:"record-creator",onSelect:()=>{e.onSelectRecordCreator?.(),ue()},children:a.recordCreator}):null,k.map(l=>{let C=f.some(te=>te.user_id===l.user_id);return R(ee.Item,{value:l.user_id,onSelect:()=>yt(l),"data-checked":C,children:De?R(De,{user:l,selected:C}):ke(mt,{children:[R("span",{children:l.name}),R("small",{children:e.getUserDescription?.(l)??l.description}),C?R("span",{"aria-label":"selected",children:"\u2713"}):null]})},l.user_id)}),!k.length&&!e.onSelectRecordCreator?R("div",{role:"status",children:_e?R(_e,{}):m.trim()?a.noMatches:a.noRecommendations}):null]})}),Ie?R(Ie,{}):null]})}function mn(e,t){let n=ft[t];if(!pt(e)||typeof e.code!="number")throw new Error(n.invalidResponse);if(e.code!==0){let o=typeof e.msg=="string"?e.msg.trim():"";throw Object.assign(new Error(o||n.searchFailedCode(e.code)),{code:String(e.code),cause:e})}if(!pt(e.data)||!Array.isArray(e.data.users))throw new Error(n.invalidResponse);return{users:e.data.users}}function pt(e){return typeof e=="object"&&e!==null}function fn(e){return e.nativeEvent?.isComposing===!0||e.keyCode===229}import{useState as gn,useRef as hn}from"react";import*as I from"@radix-ui/react-popover";import{jsx as _,jsxs as gt}from"react/jsx-runtime";var bn={en:{clearSelected:"Clear selected members",removeMember:e=>`Remove member ${e}`,selectMembers:"Select members"},zh:{clearSelected:"\u6E05\u9664\u5DF2\u9009\u6210\u5458",removeMember:e=>`\u79FB\u9664\u6210\u5458 ${e}`,selectMembers:"\u9009\u62E9\u6210\u5458"},ja:{clearSelected:"\u9078\u629E\u3057\u305F\u30E1\u30F3\u30D0\u30FC\u3092\u30AF\u30EA\u30A2",removeMember:e=>`\u30E1\u30F3\u30D0\u30FC ${e} \u3092\u524A\u9664`,selectMembers:"\u30E1\u30F3\u30D0\u30FC\u3092\u9078\u629E"}};function ht(e){let t=hn(null),n=ae(),o=bn[P()],[r,s]=gn(!1),a=Array.isArray(e.value)?e.value:e.value?[e.value]:[],i=u=>{s(u),u!==r&&e.onDropdownVisibleChange?.(u)},c=e.slots?.trigger,d=e.slots?.chip;return gt(I.Root,{open:r,onOpenChange:i,children:[gt("div",{ref:t,className:`base-app-platform base-app-editor ${e.className??""}`,onClickCapture:u=>{u.target.closest("[data-base-app-trigger]")&&e.onClick?.(u)},children:[_(I.Trigger,{asChild:!0,children:_("button",{type:"button","data-base-app-trigger":"","aria-label":o.selectMembers,onFocus:e.onFocus,onBlur:e.onBlur,children:c?_(c,{value:e.value}):a.length?a.map(u=>_("span",{children:d?_(d,{user:u}):u.name},u.user_id)):o.selectMembers})}),a.map(u=>_("button",{type:"button","aria-label":e.mode==="multiple"?o.removeMember(u.name):o.clearSelected,onClick:p=>{p.stopPropagation(),e.onChange?.(e.mode==="multiple"?a.filter(g=>g.user_id!==u.user_id):void 0),e.mode==="multiple"?e.onRemove?.(u):e.onClear?.()},children:"\xD7"},u.user_id))]}),_(I.Portal,{container:e.portalContainer??t.current?.closest("dialog")??void 0,children:_(I.Content,{"data-theme":n?.theme,className:"base-app-platform base-app-popover",sideOffset:4,collisionPadding:8,children:_(le,{...e,slots:void 0,onChange:(u,p)=>{e.onChange?.(u),p.action==="Remove"&&p.option&&e.onRemove?.(p.option)},onClose:()=>i(!1)})})})]})}import{useEffect as bt,useRef as yn,useState as Te}from"react";import{jsx as q,jsxs as vn}from"react/jsx-runtime";var wn={en:{decodeFailed:"Image could not be decoded",loadFailed:"Failed to load image",loading:"Loading image",retry:"Retry image"},zh:{decodeFailed:"\u56FE\u7247\u65E0\u6CD5\u89E3\u7801",loadFailed:"\u56FE\u7247\u52A0\u8F7D\u5931\u8D25",loading:"\u56FE\u7247\u52A0\u8F7D\u4E2D",retry:"\u91CD\u8BD5\u56FE\u7247"},ja:{decodeFailed:"\u753B\u50CF\u3092\u8868\u793A\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F",loadFailed:"\u753B\u50CF\u3092\u8AAD\u307F\u8FBC\u3081\u307E\u305B\u3093\u3067\u3057\u305F",loading:"\u753B\u50CF\u3092\u8AAD\u307F\u8FBC\u307F\u4E2D",retry:"\u753B\u50CF\u3092\u518D\u8AAD\u307F\u8FBC\u307F"}};function ir({attachment:e,size:t=360,alt:n,className:o,slots:r={}}){let s=P(),a=wn[s],i=yn(null),[c,d]=Te(!1),[u,p]=Te(0),[g,f]=Te({key:"",url:"",error:""}),{tableId:m,fieldId:v,recordId:b,fileToken:M}=e,A=JSON.stringify([m,v,b,M,t,u]);bt(()=>{if(typeof IntersectionObserver>"u"){d(!0);return}let w=new IntersectionObserver(k=>{k.some(U=>U.isIntersecting)&&(d(!0),w.disconnect())},{rootMargin:"200px"});return i.current&&w.observe(i.current),()=>w.disconnect()},[]),bt(()=>{if(!c)return;let w=new AbortController,k="";return Ge({tableId:m,fieldId:v,recordId:b,fileToken:M},t,{signal:w.signal}).then(U=>{w.signal.aborted||(k=URL.createObjectURL(U),f({key:A,url:k,error:""}))}).catch(U=>{w.signal.aborted||f({key:A,url:"",error:U instanceof Error?U.message:"",localError:U instanceof Error?void 0:"loadFailed"})}),()=>{w.abort(),k&&URL.revokeObjectURL(k)}},[c,A,m,v,b,M,t]);let K=r.loading,O=r.error,y=g.key===A?g:void 0;return q("span",{ref:i,className:`base-app-platform base-app-attachment ${o??""}`,"aria-busy":!y,children:y?.url?q("img",{src:y.url,alt:n,onError:()=>f({key:A,url:"",error:"",localError:"decodeFailed"})}):y?.error||y?.localError?O?q(O,{code:"ATTACHMENT_LOAD_FAILED",retry:()=>p(w=>w+1)}):vn("span",{children:[q("span",{role:"status",children:y.localError?a[y.localError]:y.error}),q("button",{type:"button",onClick:()=>p(w=>w+1),children:a.retry})]}):q("span",{role:"status",children:K?q(K,{}):a.loading})})}export{En as a,ne as b,Un as c,Sn as d,Pn as e,xn as f,An as g,Be as h,ge as i,fe as j,jn as k,E as l,oe as m,$n as n,Y as o,he as p,St as q,Bn as r,re as s,Pt as t,L as u,me as v,wt as w,vt as x,_n as y,Ct as z,Fe as A,be as B,N as C,Ge as D,Dt as E,Je as F,Ke as G,qn as H,Vn as I,Gn as J,Jn as K,Re as L,jt as M,j as N,Ee as O,Bt as P,P as Q,no as R,oo as S,ae as T,Pe as U,vo as V,Io as W,le as X,ht as Y,ir as Z};
|