@lark-base-open/base-database-app-sdk 0.0.0-stage → 0.0.1-alpha.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/LICENSE +6 -0
- package/README.md +30 -2
- package/capabilities.json +75 -0
- package/development-pairing.json +11 -0
- package/dist/capabilities-56e403e7.d.ts +22 -0
- package/dist/chunk-3JX3FIBG.js +1 -0
- package/dist/chunk-HEMWSWXI.js +1 -0
- package/dist/chunk-OHPYKFCM.js +1 -0
- package/dist/chunk-YDAVA3BB.js +1 -0
- package/dist/components.d.ts +5 -0
- package/dist/components.js +1 -0
- package/dist/index-64557073.d.ts +306 -0
- package/dist/page.d.ts +137 -0
- package/dist/page.js +1 -0
- package/dist/server.cjs +1 -0
- package/dist/server.d.cts +78 -0
- package/dist/server.d.ts +78 -0
- package/dist/server.js +1 -0
- package/dist/shared.cjs +1 -0
- package/dist/shared.d.cts +177 -0
- package/dist/shared.d.ts +177 -0
- package/dist/shared.js +1 -0
- package/dist/testing.d.ts +73 -0
- package/dist/testing.js +1 -0
- package/dist/theme.css +168 -0
- package/dist/vite.d.ts +15 -0
- package/dist/vite.js +3 -0
- package/docs/README.md +16 -0
- package/docs/capabilities.md +59 -0
- package/docs/compat.md +36 -0
- package/docs/components.md +34 -0
- package/docs/exports.md +39 -0
- package/docs/page.md +101 -0
- package/docs/server.md +92 -0
- package/docs/shared.md +21 -0
- package/docs/start-base-app.md +47 -0
- package/docs/testing.md +57 -0
- package/docs/upgrade.md +44 -0
- package/examples/capabilities.ts +7 -0
- package/examples/compat.ts +21 -0
- package/examples/components.tsx +11 -0
- package/examples/contract-types.ts +41 -0
- package/examples/development-context.ts +17 -0
- package/examples/http.ts +12 -0
- package/examples/link.ts +10 -0
- package/examples/mock.ts +8 -0
- package/examples/msw.ts +5 -0
- package/examples/page.ts +6 -0
- package/examples/server.ts +57 -0
- package/examples/shared.ts +10 -0
- package/examples/start-base-app.tsx +8 -0
- package/examples/upgrade.ts +7 -0
- package/examples/upload.ts +18 -0
- package/examples/vite.ts +2 -0
- package/package.json +105 -4
package/dist/page.d.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import * as channelRuntime from '@lark-base-open/base-site-channel/runtime';
|
|
2
|
+
import { LinkGuardOptions as LinkGuardOptions$1, CallSiteAIFunctionParams as CallSiteAIFunctionParams$1, InvokeSiteAIFunctionStreamParams as InvokeSiteAIFunctionStreamParams$1, SiteAIVideoTask, SiteAIImageAsset, SiteAIFunctionResult, SiteAIFunctionStreamHandle } from '@lark-base-open/base-site-channel/runtime';
|
|
3
|
+
export * from '@lark-base-open/base-site-channel/runtime';
|
|
4
|
+
export { SiteChatbotStreamError } from '@lark-base-open/base-site-channel/runtime';
|
|
5
|
+
import { RuntimeDiagnostic } from './shared.js';
|
|
6
|
+
export { CAPABILITY_CATALOG, CapabilityContext, CapabilityDescriptor, CapabilityMap, CapabilityName, CapabilityQueryResult, CapabilityUnavailableError, CapabilityUnavailableReason, DiagnosticCategory, DiagnosticCode, FunctionEnvelope, JsonValue, RuntimeCapabilities, SDKError, SDKErrorOptions, WriteResult, classifyRuntimeError } from './shared.js';
|
|
7
|
+
import { R as RuntimeContextReader } from './capabilities-56e403e7.js';
|
|
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
|
+
export * from '@lark-base-open/base-site-channel/runtime-contract';
|
|
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-64557073.js';
|
|
12
|
+
export { X as AttachmentImage, M as BaseAppContextValue, N as BaseAppProvider, n as DatabaseAttachmentRef, T as DatabaseAudience, D as DatabaseContext, p as DatabaseEnv, u as DatabaseFunctionInputMap, t as DatabaseFunctionInvocation, q as DatabaseFunctionResponse, W as DatabaseUserMenu, V as DatabaseUserMenuProps, R as FloatingButton, Q as FloatingButtonProps, F as FunctionInputMap, S as SiteRuntimeClient, Y as UiLanguageContext, C as User, H as UserSelectorAction, J as UserSelectorEditor, K as UserSelectorEditorProps, L as UserSelectorEditorValue, G as UserSelectorMode, A as UserSelectorPanel, B as UserSelectorPanelProps, I as UserSelectorSearchAction, E as UserSelectorValue, d as buildAttachmentCoverUrl, j as buildDatabaseInvokeFunctionPath, h as buildDatabaseInvokeGetPath, v as createSiteRuntimeClient, w as createSiteRuntimeFetch, f as fetch, c as fetchAttachmentCover, e as fetchAttachmentDownloadUrl, g as getCurrentUser, a as getDatabaseContext, _ as getUiLanguage, $ as getUiLocale, a0 as initializeUiLanguage, x as invokeApi, k as invokeDatabaseFunction, m as invokeDatabaseMutationBatch, i as invokeHttp, l as logout, o as openAttachmentDownload, z as openLink, r as requestEdit, b as resolveDatabaseContext, Z as selectUiLanguage, s as siteRuntime, y as uploadAttachment, O as useBaseApp, P as useOptionalBaseApp, a1 as useUiLanguage } from './index-64557073.js';
|
|
13
|
+
import React__default from 'react';
|
|
14
|
+
|
|
15
|
+
interface LinkGuardOptions extends LinkGuardOptions$1 {
|
|
16
|
+
/** 测试时可注入上下文读取器;转发链接仍使用 channel 默认运行时。 */
|
|
17
|
+
runtime?: RuntimeContextReader;
|
|
18
|
+
onDiagnostic?: (diagnostic: RuntimeDiagnostic) => void;
|
|
19
|
+
}
|
|
20
|
+
/** 同步返回清理函数,异步查询期间维持原生行为;卸载后迟到的查询不会安装。 */
|
|
21
|
+
declare function installLinkGuard(options?: LinkGuardOptions): () => void;
|
|
22
|
+
|
|
23
|
+
type SiteAIMessageContentPart = {
|
|
24
|
+
text: string;
|
|
25
|
+
type: "text";
|
|
26
|
+
} | {
|
|
27
|
+
detail?: "high" | "low" | "xhigh";
|
|
28
|
+
type: "image";
|
|
29
|
+
url: string;
|
|
30
|
+
} | {
|
|
31
|
+
fps?: number;
|
|
32
|
+
type: "video";
|
|
33
|
+
url: string;
|
|
34
|
+
} | {
|
|
35
|
+
type: "audio";
|
|
36
|
+
url: string;
|
|
37
|
+
} | {
|
|
38
|
+
filename?: string;
|
|
39
|
+
type: "file";
|
|
40
|
+
url: string;
|
|
41
|
+
};
|
|
42
|
+
/** AI Function 对话消息。所有 content 都使用非空 parts 数组;System Prompt 由 Function 配置管理。
|
|
43
|
+
* 元组式 `[X, ...X[]]` 保证空数组无法通过 TS 编译,避免把空 content 推迟到运行态服务端校验。 */
|
|
44
|
+
type SiteAIMessage = {
|
|
45
|
+
content: [SiteAIMessageContentPart, ...SiteAIMessageContentPart[]];
|
|
46
|
+
role: "user";
|
|
47
|
+
} | {
|
|
48
|
+
content: [
|
|
49
|
+
Extract<SiteAIMessageContentPart, {
|
|
50
|
+
type: "text";
|
|
51
|
+
}>,
|
|
52
|
+
...Array<Extract<SiteAIMessageContentPart, {
|
|
53
|
+
type: "text";
|
|
54
|
+
}>>
|
|
55
|
+
];
|
|
56
|
+
role: "assistant";
|
|
57
|
+
};
|
|
58
|
+
type WithSiteAIMessages<T> = T extends unknown ? Omit<T, "messages"> & {
|
|
59
|
+
messages?: SiteAIMessage[];
|
|
60
|
+
} : never;
|
|
61
|
+
type CallSiteAIFunctionParams = WithSiteAIMessages<CallSiteAIFunctionParams$1>;
|
|
62
|
+
type InvokeSiteAIFunctionStreamParams = Omit<InvokeSiteAIFunctionStreamParams$1, "messages"> & {
|
|
63
|
+
messages: SiteAIMessage[];
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/** AI Function 可判别联合返回与媒体任务态,供页面按 type 分支渲染。 */
|
|
67
|
+
type SiteAIMediaTask = SiteAIVideoTask | {
|
|
68
|
+
capabilityType?: "image";
|
|
69
|
+
errCode?: string;
|
|
70
|
+
errMessage?: string;
|
|
71
|
+
imageAssets?: SiteAIImageAsset[];
|
|
72
|
+
progress?: number;
|
|
73
|
+
requestId: string;
|
|
74
|
+
status: "cancelled" | "failed" | "queued" | "running" | "succeeded";
|
|
75
|
+
taskId: string;
|
|
76
|
+
type: "image_task";
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/** 按 functionKey 调用 AI Function,返回可判别联合结果(text/image_task/video_task)。
|
|
80
|
+
*
|
|
81
|
+
* 页面用 switch(result.type) 分支渲染:text 为聚合文本,image_task/video_task
|
|
82
|
+
* 需再用 getSiteAIFunctionTask 轮询。传 messages 走文本/多模态理解,
|
|
83
|
+
* 传 input 创建媒体任务;随后用 getSiteAIFunctionTask 轮询。
|
|
84
|
+
*/
|
|
85
|
+
declare function callSiteAIFunction(params: CallSiteAIFunctionParams): Promise<SiteAIFunctionResult>;
|
|
86
|
+
/** 显式流式调用 AI Function(text/vision):逐帧消费增量,卸载或取消时 destroy。 */
|
|
87
|
+
declare function invokeSiteAIFunctionStream(params: InvokeSiteAIFunctionStreamParams): SiteAIFunctionStreamHandle;
|
|
88
|
+
/** 校验并归一化 AI Function 媒体任务响应。
|
|
89
|
+
*
|
|
90
|
+
* Channel SDK 新旧版本、OpenAPI 和父页面代理可能返回裸 task 或
|
|
91
|
+
* `{code,msg,data}` 包裹;页面只接受含合法 taskId/type/status 的任务。
|
|
92
|
+
*/
|
|
93
|
+
declare function normalizeSiteAIMediaTask(value: unknown): SiteAIMediaTask;
|
|
94
|
+
declare function hasRunnableMediaTask(task: SiteAIMediaTask): task is SiteAIMediaTask & {
|
|
95
|
+
taskId: string;
|
|
96
|
+
};
|
|
97
|
+
/** 提交文生图或文生视频任务,返回封装后的 taskId 与初始状态。 */
|
|
98
|
+
declare function createSiteAIFunctionTask(params: CallSiteAIFunctionParams): Promise<SiteAIMediaTask>;
|
|
99
|
+
/** 轮询文生图或文生视频任务进度与最终资源。 */
|
|
100
|
+
declare function getSiteAIFunctionTask(functionKey: string, taskId: string): Promise<SiteAIMediaTask>;
|
|
101
|
+
|
|
102
|
+
interface StartBaseAppOptions {
|
|
103
|
+
app: React__default.ComponentType;
|
|
104
|
+
root?: HTMLElement | string;
|
|
105
|
+
strictMode?: boolean;
|
|
106
|
+
linkGuard?: boolean;
|
|
107
|
+
reportLifecycle?: boolean;
|
|
108
|
+
platformUI?: boolean;
|
|
109
|
+
theme?: "host" | "light" | "dark";
|
|
110
|
+
locale?: "host" | UiLanguage;
|
|
111
|
+
providers?: (children: React__default.ReactNode) => React__default.ReactNode;
|
|
112
|
+
onDiagnostic?: (record: RuntimeDiagnostic) => void;
|
|
113
|
+
slots?: {
|
|
114
|
+
loading?: React__default.ComponentType;
|
|
115
|
+
error?: React__default.ComponentType<{
|
|
116
|
+
code: string;
|
|
117
|
+
}>;
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
interface BaseAppHandle {
|
|
121
|
+
ready: Promise<void>;
|
|
122
|
+
dispose(): void;
|
|
123
|
+
}
|
|
124
|
+
declare function startBaseApp(options: StartBaseAppOptions): BaseAppHandle;
|
|
125
|
+
|
|
126
|
+
interface DevelopmentPairChallenge {
|
|
127
|
+
challenge: string;
|
|
128
|
+
}
|
|
129
|
+
interface DevelopmentPairProof {
|
|
130
|
+
proof: string;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
declare class SiteChatbotStreamAdapter extends channelRuntime.SiteChatbotStreamAdapter {
|
|
134
|
+
constructor(options: ConstructorParameters<typeof channelRuntime.SiteChatbotStreamAdapter>[0]);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export { BaseAppHandle, CallSiteAIFunctionParams, DevelopmentPairChallenge, DevelopmentPairProof, InvokeSiteAIFunctionStreamParams, LinkGuardOptions, RuntimeContextReader, RuntimeDiagnostic, SiteAIMediaTask, SiteAIMessage, SiteAIMessageContentPart, SiteChatbotStreamAdapter, StartBaseAppOptions, UiLanguage, callSiteAIFunction, createSiteAIFunctionTask, getSiteAIFunctionTask, hasRunnableMediaTask, installLinkGuard, invokeSiteAIFunctionStream, normalizeSiteAIMediaTask, startBaseApp };
|
package/dist/page.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{A as Qe,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 Q,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 oe,p as ae,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 je}from"./chunk-HEMWSWXI.js";import{a as He,b as Ve,c as v,d as R}from"./chunk-YDAVA3BB.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)},o=e.runtime??m;return Promise.resolve().then(()=>o.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 Ce(e){return q(e)}function a(e,t){for(let n of t){let i=e[n];if(typeof i=="string"&&i.trim())return i}}function be(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=a(e,["capabilityType","capability_type","CapabilityType"]);return t==="image"||t==="video"?t:void 0}function Me(e){if(Array.isArray(e))return e.filter(C).map(t=>{let n=a(t,["size","Size"]),i=a(t,["token","Token"]),o=a(t,["url","URL"]);return{safetyStatus:a(t,["safetyStatus","safety_status","SafetyStatus"])??"",...n?{size:n}:{},...i?{token:i}:{},...o?{url:o}:{}}})}function De(e){if(!C(e))return;let t=e.durationSeconds??e.duration_seconds??e.DurationSeconds,n=a(e,["token","Token"]),i=a(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(!C(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=a(e,["type","Type"]),i=a(e,["taskId","task_id","TaskID"]),o=e.status??e.Status;if(n!=="image_task"&&n!=="video_task"||!i||typeof o!="string"||!Fe.has(o))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=be(e,["progress","Progress"]),I=xe(e),p=a(e,["errCode","err_code","ErrCode"]),f=a(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:a(e,["requestId","request_id","RequestID"])??"",status:o,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:a(e,["msg","message","Message"])??"Failed to create the AI Function task"};let n=e.BaseResp??e.base_resp??e.baseResp;if(!C(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:a(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 C(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,b=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 o=!1,s=!1,c=!1,l,I=()=>{},p=()=>{},f=r=>{try{e.onDiagnostic?.(R(r))}catch{}},S=r=>{f(r),!(o||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(){o=!0}}}if(!A)return S(new Error("APP_ROOT_NOT_FOUND")),{ready:i,dispose(){o=!0}};if(E.has(A))throw new Error("APP_ALREADY_STARTED");E.add(A);let z=()=>{o||(o=!0,I(),p(),l?.unmount(),E.delete(A),U.clear(),!s&&!c&&n(new Error("APP_DISPOSED")))},K=()=>{queueMicrotask(()=>{o||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 j=e.app,w=Ne(Ge,{children:[d(j,{}),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(b,{failed:S,fallback:e.slots?.error,children:d(r,{})})),m.getRuntimeContext().then(g=>{if(o||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(b,{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,Q 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,oe 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,Ce as invokeSiteAIFunctionStream,ee as isValidSiteFunctionName,ae as logout,k as normalizeSiteAIMediaTask,ye as openAttachmentDownload,ue as openLink,je as queryCapability,ze as readCapabilities,$ as readSiteAITextDelta,se as requestEdit,Qe 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/dist/server.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var k=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var W=Object.prototype.hasOwnProperty;var J=(t,s)=>{for(var o in s)k(t,o,{get:s[o],enumerable:!0})},V=(t,s,o,e)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of L(s))!W.call(t,n)&&n!==o&&k(t,n,{get:()=>s[n],enumerable:!(e=U(s,n))||e.enumerable});return t};var z=t=>V(k({},"__esModule",{value:!0}),t);var M={};J(M,{SDKError:()=>f,bindFunctionRuntime:()=>j,createServerContext:()=>_,defineFunction:()=>K,normalizeRecordsResult:()=>x});module.exports=z(M);var F=Symbol.for("@lark-base-open/base-database-app-sdk/SDKError/v1"),f=class extends Error{constructor(o,e,n,r){super(e);this.code=o;this.name="SDKError",this.safeMessage=e;let c=typeof n=="object"?n:{};this.upstreamCode=typeof n=="string"?n:void 0,this.wireCode=Number.isSafeInteger(c.wireCode)&&c.wireCode!==0?c.wireCode:o==="SDK_TIMEOUT"?504:o==="SDK_CANCELLED"?499:o==="SDK_INPUT_INVALID"?400:500,this.retryable=c.retryable??r??!1,this.outcome=c.outcome??"failed",this.paths=c.paths??[]}[F]=!0;static[Symbol.hasInstance](o){return this!==f?Function.prototype[Symbol.hasInstance].call(this,o):o!==null&&typeof o=="object"&&o[F]===!0}wireCode;safeMessage;retryable;outcome;paths;upstreamCode};var d=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),b=t=>typeof t=="string"&&/^rec[A-Za-z0-9]{1,32}$/.test(t);function S(t){let s=new Set,o=e=>{if(!(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))){if(typeof e!="object"||!e||s.has(e)||Array.isArray(e)&&Object.getPrototypeOf(e)!==Array.prototype||!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null||Array.isArray(e)&&(Object.keys(e).length!==e.length||Object.keys(e).some((n,r)=>n!==String(r))))throw 0;s.add(e);for(let n of Reflect.ownKeys(e)){if(Array.isArray(e)&&n==="length")continue;if(typeof n!="string")throw 0;let r=Object.getOwnPropertyDescriptor(e,n);if(!r.enumerable||!("value"in r))throw 0;o(r.value)}s.delete(e)}};try{o(t)}catch{throw new f("SDK_OUTPUT_NOT_JSON","\u8F93\u51FA\u5FC5\u987B\u662F\u65E0\u635F JSON \u503C")}}function O(t,s,o){return{status:"unknown",code:t,retryable:!1,...s?{requestedIds:[...s]}:{},...o?{logid:o}:{}}}var B=t=>typeof t=="number"&&[401,403,404,91403,1254302,1254043,1254044].includes(t),A=t=>({status:"failed",code:"SDK_RECORDS_REJECTED",upstreamCode:t,retryable:!1,appliedIds:[]}),D=t=>Array.isArray(t)&&t.every(b)&&new Set(t).size===t.length;function x(t,s){let o=()=>O("SDK_RECORDS_RESULT_UNKNOWN",s.requestedIds);if(d(t)&&B(t.code))return A(t.code);if(!d(t)||t.code!==0||!d(t.data))return o();let e=t.data,n=e.ignored_fields??[];if(!Array.isArray(n)||!n.every(a=>d(a)&&["id","name","reason"].every(i=>typeof a[i]=="string")))return o();let r=e.record_not_found??[];if(!D(r))return o();let c=s.requestedIds??[],u,y;if(s.operation==="appendAttachments"||s.operation==="removeAttachments"){if(!d(e.attachments))return o();try{S(e.attachments)}catch{return o()}for(let[a,i]of Object.entries(e.attachments)){if(!b(a)||!c.includes(a)||!d(i)||!Object.keys(i).length)return o();for(let[p,m]of Object.entries(i))if(!/^fld[A-Za-z0-9]+$/.test(p)||!Array.isArray(m)||!m.every(g=>d(g)&&typeof g.file_token=="string"&&g.file_token.length>0))return o()}if(u=Object.keys(e.attachments),r.some(a=>!c.includes(a)||u.includes(a))||!n.length&&c.some(a=>!u.includes(a)&&!r.includes(a)))return o();y=e.attachments}else{if(!D(e.record_id_list))return o();let a=e.record_id_list;if(s.operation==="create"){if(a.length!==s.count||Object.hasOwn(e,"record_not_found"))return o();u=a}else if(s.operation==="update"){if(a.some(i=>!c.includes(i)||r.includes(i))||r.some(i=>!c.includes(i))||a.length+r.length!==c.length)return o();u=a}else{if(a.length!==c.length||a.some((i,p)=>i!==c[p])||r.some(i=>!c.includes(i)))return o();u=a.filter(i=>!r.includes(i))}}let l=y===void 0?{}:{attachments:y};return r.length||n.length?{status:"partial",appliedIds:u,notFoundIds:r,ignoredFields:n,...l}:{status:"success",appliedIds:u,notFoundIds:[],ignoredFields:[],...l}}var E={create:"records/batch_create",update:"records/batch_update",delete:"records/batch_delete",appendAttachments:"append_attachments",removeAttachments:"remove_attachments"},I=t=>({status:"failed",code:t,retryable:!1,appliedIds:[]});function $(t){if(t?.platformEnv==="online")return t.brand==="feishu"?"https://open.feishu.cn":t.brand==="lark"?"https://open.larksuite.com":void 0;if(t?.brand==="feishu"){if(t.platformEnv==="pre")return"https://open.feishu-pre.cn";if(t.platformEnv==="boe")return"https://open.feishu-boe.cn"}}function T(t,s){let o=async(e,n,r,c)=>{if(!s)return I("SDK_RUNTIME_PROFILE_MISSING");let u=$(s);if(!u)return I("SDK_RUNTIME_PROFILE_UNSUPPORTED");if(c?.signal?.aborted)return I("SDK_CANCELLED");let y,l,a;try{if(!d(n)||typeof n.baseToken!="string"||typeof n.tableId!="string"||!/^[A-Za-z0-9]+$/.test(n.baseToken)||!/^tbl[A-Za-z0-9]+$/.test(n.tableId))throw 0;if(S(r),e==="create"){if(!Array.isArray(r)||!r.every(d))throw 0;a=r.length,y={create_records:r}}else if(e==="update"){if(!d(r)||!Object.values(r).every(d))throw 0;l=Object.keys(r),a=l.length,y={update_records:r}}else if(e==="delete"){if(!Array.isArray(r)||!r.every(b))throw 0;l=r,a=r.length,y={record_id_list:r}}else{if(!d(r))throw 0;let i=Object.create(null),p=0;for(let[m,g]of Object.entries(r)){if(!b(m)||!d(g))throw 0;for(let[C,w]of Object.entries(g)){if(!C.trim()||!Array.isArray(w))throw 0;for(let h of w){if(!d(h)||typeof h.file_token!="string"||!h.file_token.trim()||Object.keys(h).some(R=>!["file_token",...e==="appendAttachments"?["image_width","image_height"]:[]].includes(R)))throw 0;for(let R of["image_width","image_height"])if(h[R]!==void 0&&(typeof h[R]!="number"||!Number.isInteger(h[R])||h[R]<=0))throw 0}p+=w.length,w.length&&(i[m]??=Object.create(null),i[m][C]=w)}}if(p>50)throw 0;if(!p)return{status:"success",appliedIds:[],notFoundIds:[],ignoredFields:[],noop:!0};l=Object.keys(i),y={attachments:i}}if(a!==void 0&&(a<1||a>200)||l&&(!l.every(b)||new Set(l).size!==l.length))throw 0}catch{return I("SDK_RECORDS_INPUT_INVALID")}try{let i=await t.fetch(`${u}/open-apis/bitable/v1/apps/${encodeURIComponent(n.baseToken)}/tables/${encodeURIComponent(n.tableId)}/${E[e]}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(y),signal:c?.signal}),p=i.headers.get("x-tt-logid")??void 0;if([401,403,404].includes(i.status))return A(i.status);if(!i.ok)return O("SDK_RECORDS_HTTP_ERROR",l,p);let m=x(await i.json(),{operation:e,requestedIds:l,count:a});return m.status==="unknown"&&p?{...m,logid:p}:m}catch(i){let p=i instanceof Error?i.name:"";return O(p==="AbortError"?"SDK_CANCELLED":p==="TimeoutError"?"SDK_TIMEOUT":"SDK_RECORDS_RESULT_UNKNOWN",l)}};return Object.fromEntries(Object.keys(E).map(e=>[e,(n,r,c)=>o(e,n,r,c)]))}var P=Symbol("base-database-runtime-profile");function j(t,s){let o=Object.freeze({platformEnv:s.platformEnv,brand:s.brand});return function(e,n){let r=Object.defineProperty({...n},P,{value:o});return t.call(this,e,r)}}function _(t){return{...t,records:T(t,t[P])}}async function N(t,s,o){let e;try{e=await t["~standard"].validate(s)}catch{throw new f("SDK_VALIDATOR_FAILED","Schema \u6821\u9A8C\u5668\u6267\u884C\u5931\u8D25")}if(e.issues){let n=e.issues.map(r=>(r.path??[]).map(c=>{let u=typeof c=="object"?c.key:c;return typeof u=="number"||typeof u=="string"?u:"[symbol]"}));throw new f(`SDK_${o}_INVALID`,o==="INPUT"?"\u8F93\u5165\u4E0D\u7B26\u5408\u5951\u7EA6":"\u8F93\u51FA\u4E0D\u7B26\u5408\u5951\u7EA6",{paths:n})}return e.value}function K(t){return async(s,o)=>{try{let e=await N(t.input,s,"INPUT"),n=await t.handler(e,_(o)),r=await N(t.output,n,"OUTPUT");return S(r),{code:0,msg:"success",data:r}}catch(e){let n=e instanceof f?e:new f("SDK_HANDLER_FAILED","\u51FD\u6570\u6267\u884C\u5931\u8D25");return console.error(JSON.stringify({source:"sdk",code:n.code,paths:n.paths,retryable:n.retryable,outcome:n.outcome})),{code:n.wireCode,msg:n.safeMessage}}}}0&&(module.exports={SDKError,bindFunctionRuntime,createServerContext,defineFunction,normalizeRecordsResult});
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
|
+
import { JsonValue, WriteResult, FunctionEnvelope } from './shared.cjs';
|
|
3
|
+
export { DiagnosticCategory, RuntimeDiagnostic, SDKError, SDKErrorOptions } from './shared.cjs';
|
|
4
|
+
|
|
5
|
+
type Fields = Record<string, JsonValue>;
|
|
6
|
+
type Target = {
|
|
7
|
+
baseToken: string;
|
|
8
|
+
tableId: string;
|
|
9
|
+
};
|
|
10
|
+
type AttachmentInput = {
|
|
11
|
+
file_token: string;
|
|
12
|
+
image_width?: number;
|
|
13
|
+
image_height?: number;
|
|
14
|
+
};
|
|
15
|
+
type Attachments = Record<string, Record<string, AttachmentInput[]>>;
|
|
16
|
+
interface RecordsClient {
|
|
17
|
+
create<T extends Fields>(target: Target, records: readonly T[], opts?: {
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
}): Promise<WriteResult>;
|
|
20
|
+
update<T extends Fields>(target: Target, records: Readonly<Record<string, Partial<T>>>, opts?: {
|
|
21
|
+
signal?: AbortSignal;
|
|
22
|
+
}): Promise<WriteResult>;
|
|
23
|
+
delete(target: Target, ids: readonly string[], opts?: {
|
|
24
|
+
signal?: AbortSignal;
|
|
25
|
+
}): Promise<WriteResult>;
|
|
26
|
+
appendAttachments(target: Target, values: Attachments, opts?: {
|
|
27
|
+
signal?: AbortSignal;
|
|
28
|
+
}): Promise<WriteResult>;
|
|
29
|
+
removeAttachments(target: Target, values: Record<string, Record<string, {
|
|
30
|
+
file_token: string;
|
|
31
|
+
}[]>>, opts?: {
|
|
32
|
+
signal?: AbortSignal;
|
|
33
|
+
}): Promise<WriteResult>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface RawFunctionContext {
|
|
37
|
+
fetch: typeof globalThis.fetch;
|
|
38
|
+
invokeFunction(p: {
|
|
39
|
+
projectId: string;
|
|
40
|
+
functionId: string;
|
|
41
|
+
params?: unknown;
|
|
42
|
+
}): Promise<unknown>;
|
|
43
|
+
}
|
|
44
|
+
interface RuntimeBuildProfile {
|
|
45
|
+
platformEnv: "online" | "pre" | "boe";
|
|
46
|
+
brand: "feishu" | "lark";
|
|
47
|
+
}
|
|
48
|
+
interface ServerContext extends RawFunctionContext {
|
|
49
|
+
records: RecordsClient;
|
|
50
|
+
}
|
|
51
|
+
declare function bindFunctionRuntime<F extends (raw: unknown, ctx: RawFunctionContext) => unknown>(fn: F, profile: RuntimeBuildProfile): F;
|
|
52
|
+
declare function createServerContext(raw: RawFunctionContext): ServerContext;
|
|
53
|
+
|
|
54
|
+
interface DefineFunctionOptions<I extends StandardSchemaV1, O extends StandardSchemaV1> {
|
|
55
|
+
input: I;
|
|
56
|
+
output: O;
|
|
57
|
+
handler(input: StandardSchemaV1.InferOutput<I>, ctx: ServerContext): StandardSchemaV1.InferInput<O> | Promise<StandardSchemaV1.InferInput<O>>;
|
|
58
|
+
}
|
|
59
|
+
interface DefinedFunction<I extends StandardSchemaV1, O extends StandardSchemaV1> {
|
|
60
|
+
(rawParams: unknown, context: RawFunctionContext): Promise<FunctionEnvelope<StandardSchemaV1.InferOutput<O>>>;
|
|
61
|
+
readonly __contractTypes?: {
|
|
62
|
+
input: StandardSchemaV1.InferInput<I>;
|
|
63
|
+
output: StandardSchemaV1.InferOutput<O>;
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
declare function defineFunction<I extends StandardSchemaV1, O extends StandardSchemaV1>(definition: DefineFunctionOptions<I, O>): DefinedFunction<I, O>;
|
|
67
|
+
|
|
68
|
+
type RecordsOperation = "create" | "update" | "delete" | "appendAttachments" | "removeAttachments";
|
|
69
|
+
interface RecordsResultRequest {
|
|
70
|
+
operation: RecordsOperation;
|
|
71
|
+
requestedIds?: readonly string[];
|
|
72
|
+
count?: number;
|
|
73
|
+
}
|
|
74
|
+
declare function normalizeRecordsResult(body: unknown, request: RecordsResultRequest): WriteResult;
|
|
75
|
+
|
|
76
|
+
type LegacyFunctionHandler<Context = unknown> = (rawParams: unknown, context: Context) => unknown | Promise<unknown>;
|
|
77
|
+
|
|
78
|
+
export { AttachmentInput, Attachments, DefineFunctionOptions, DefinedFunction, Fields, FunctionEnvelope, FunctionEnvelope as FunctionResult, JsonValue, LegacyFunctionHandler, RawFunctionContext, RecordsClient, RecordsOperation, RecordsResultRequest, RuntimeBuildProfile, ServerContext, Target, WriteResult, bindFunctionRuntime, createServerContext, defineFunction, normalizeRecordsResult };
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
|
+
import { JsonValue, WriteResult, FunctionEnvelope } from './shared.js';
|
|
3
|
+
export { DiagnosticCategory, RuntimeDiagnostic, SDKError, SDKErrorOptions } from './shared.js';
|
|
4
|
+
|
|
5
|
+
type Fields = Record<string, JsonValue>;
|
|
6
|
+
type Target = {
|
|
7
|
+
baseToken: string;
|
|
8
|
+
tableId: string;
|
|
9
|
+
};
|
|
10
|
+
type AttachmentInput = {
|
|
11
|
+
file_token: string;
|
|
12
|
+
image_width?: number;
|
|
13
|
+
image_height?: number;
|
|
14
|
+
};
|
|
15
|
+
type Attachments = Record<string, Record<string, AttachmentInput[]>>;
|
|
16
|
+
interface RecordsClient {
|
|
17
|
+
create<T extends Fields>(target: Target, records: readonly T[], opts?: {
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
}): Promise<WriteResult>;
|
|
20
|
+
update<T extends Fields>(target: Target, records: Readonly<Record<string, Partial<T>>>, opts?: {
|
|
21
|
+
signal?: AbortSignal;
|
|
22
|
+
}): Promise<WriteResult>;
|
|
23
|
+
delete(target: Target, ids: readonly string[], opts?: {
|
|
24
|
+
signal?: AbortSignal;
|
|
25
|
+
}): Promise<WriteResult>;
|
|
26
|
+
appendAttachments(target: Target, values: Attachments, opts?: {
|
|
27
|
+
signal?: AbortSignal;
|
|
28
|
+
}): Promise<WriteResult>;
|
|
29
|
+
removeAttachments(target: Target, values: Record<string, Record<string, {
|
|
30
|
+
file_token: string;
|
|
31
|
+
}[]>>, opts?: {
|
|
32
|
+
signal?: AbortSignal;
|
|
33
|
+
}): Promise<WriteResult>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface RawFunctionContext {
|
|
37
|
+
fetch: typeof globalThis.fetch;
|
|
38
|
+
invokeFunction(p: {
|
|
39
|
+
projectId: string;
|
|
40
|
+
functionId: string;
|
|
41
|
+
params?: unknown;
|
|
42
|
+
}): Promise<unknown>;
|
|
43
|
+
}
|
|
44
|
+
interface RuntimeBuildProfile {
|
|
45
|
+
platformEnv: "online" | "pre" | "boe";
|
|
46
|
+
brand: "feishu" | "lark";
|
|
47
|
+
}
|
|
48
|
+
interface ServerContext extends RawFunctionContext {
|
|
49
|
+
records: RecordsClient;
|
|
50
|
+
}
|
|
51
|
+
declare function bindFunctionRuntime<F extends (raw: unknown, ctx: RawFunctionContext) => unknown>(fn: F, profile: RuntimeBuildProfile): F;
|
|
52
|
+
declare function createServerContext(raw: RawFunctionContext): ServerContext;
|
|
53
|
+
|
|
54
|
+
interface DefineFunctionOptions<I extends StandardSchemaV1, O extends StandardSchemaV1> {
|
|
55
|
+
input: I;
|
|
56
|
+
output: O;
|
|
57
|
+
handler(input: StandardSchemaV1.InferOutput<I>, ctx: ServerContext): StandardSchemaV1.InferInput<O> | Promise<StandardSchemaV1.InferInput<O>>;
|
|
58
|
+
}
|
|
59
|
+
interface DefinedFunction<I extends StandardSchemaV1, O extends StandardSchemaV1> {
|
|
60
|
+
(rawParams: unknown, context: RawFunctionContext): Promise<FunctionEnvelope<StandardSchemaV1.InferOutput<O>>>;
|
|
61
|
+
readonly __contractTypes?: {
|
|
62
|
+
input: StandardSchemaV1.InferInput<I>;
|
|
63
|
+
output: StandardSchemaV1.InferOutput<O>;
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
declare function defineFunction<I extends StandardSchemaV1, O extends StandardSchemaV1>(definition: DefineFunctionOptions<I, O>): DefinedFunction<I, O>;
|
|
67
|
+
|
|
68
|
+
type RecordsOperation = "create" | "update" | "delete" | "appendAttachments" | "removeAttachments";
|
|
69
|
+
interface RecordsResultRequest {
|
|
70
|
+
operation: RecordsOperation;
|
|
71
|
+
requestedIds?: readonly string[];
|
|
72
|
+
count?: number;
|
|
73
|
+
}
|
|
74
|
+
declare function normalizeRecordsResult(body: unknown, request: RecordsResultRequest): WriteResult;
|
|
75
|
+
|
|
76
|
+
type LegacyFunctionHandler<Context = unknown> = (rawParams: unknown, context: Context) => unknown | Promise<unknown>;
|
|
77
|
+
|
|
78
|
+
export { AttachmentInput, Attachments, DefineFunctionOptions, DefinedFunction, Fields, FunctionEnvelope, FunctionEnvelope as FunctionResult, JsonValue, LegacyFunctionHandler, RawFunctionContext, RecordsClient, RecordsOperation, RecordsResultRequest, RuntimeBuildProfile, ServerContext, Target, WriteResult, bindFunctionRuntime, createServerContext, defineFunction, normalizeRecordsResult };
|
package/dist/server.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as y}from"./chunk-3JX3FIBG.js";var d=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),w=t=>typeof t=="string"&&/^rec[A-Za-z0-9]{1,32}$/.test(t);function O(t){let a=new Set,i=e=>{if(!(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))){if(typeof e!="object"||!e||a.has(e)||Array.isArray(e)&&Object.getPrototypeOf(e)!==Array.prototype||!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null||Array.isArray(e)&&(Object.keys(e).length!==e.length||Object.keys(e).some((r,n)=>r!==String(n))))throw 0;a.add(e);for(let r of Reflect.ownKeys(e)){if(Array.isArray(e)&&r==="length")continue;if(typeof r!="string")throw 0;let n=Object.getOwnPropertyDescriptor(e,r);if(!n.enumerable||!("value"in n))throw 0;i(n.value)}a.delete(e)}};try{i(t)}catch{throw new y("SDK_OUTPUT_NOT_JSON","\u8F93\u51FA\u5FC5\u987B\u662F\u65E0\u635F JSON \u503C")}}function x(t,a,i){return{status:"unknown",code:t,retryable:!1,...a?{requestedIds:[...a]}:{},...i?{logid:i}:{}}}var P=t=>typeof t=="number"&&[401,403,404,91403,1254302,1254043,1254044].includes(t),I=t=>({status:"failed",code:"SDK_RECORDS_REJECTED",upstreamCode:t,retryable:!1,appliedIds:[]}),F=t=>Array.isArray(t)&&t.every(w)&&new Set(t).size===t.length;function _(t,a){let i=()=>x("SDK_RECORDS_RESULT_UNKNOWN",a.requestedIds);if(d(t)&&P(t.code))return I(t.code);if(!d(t)||t.code!==0||!d(t.data))return i();let e=t.data,r=e.ignored_fields??[];if(!Array.isArray(r)||!r.every(s=>d(s)&&["id","name","reason"].every(o=>typeof s[o]=="string")))return i();let n=e.record_not_found??[];if(!F(n))return i();let c=a.requestedIds??[],u,m;if(a.operation==="appendAttachments"||a.operation==="removeAttachments"){if(!d(e.attachments))return i();try{O(e.attachments)}catch{return i()}for(let[s,o]of Object.entries(e.attachments)){if(!w(s)||!c.includes(s)||!d(o)||!Object.keys(o).length)return i();for(let[p,f]of Object.entries(o))if(!/^fld[A-Za-z0-9]+$/.test(p)||!Array.isArray(f)||!f.every(g=>d(g)&&typeof g.file_token=="string"&&g.file_token.length>0))return i()}if(u=Object.keys(e.attachments),n.some(s=>!c.includes(s)||u.includes(s))||!r.length&&c.some(s=>!u.includes(s)&&!n.includes(s)))return i();m=e.attachments}else{if(!F(e.record_id_list))return i();let s=e.record_id_list;if(a.operation==="create"){if(s.length!==a.count||Object.hasOwn(e,"record_not_found"))return i();u=s}else if(a.operation==="update"){if(s.some(o=>!c.includes(o)||n.includes(o))||n.some(o=>!c.includes(o))||s.length+n.length!==c.length)return i();u=s}else{if(s.length!==c.length||s.some((o,p)=>o!==c[p])||n.some(o=>!c.includes(o)))return i();u=s.filter(o=>!n.includes(o))}}let l=m===void 0?{}:{attachments:m};return n.length||r.length?{status:"partial",appliedIds:u,notFoundIds:n,ignoredFields:r,...l}:{status:"success",appliedIds:u,notFoundIds:[],ignoredFields:[],...l}}var C={create:"records/batch_create",update:"records/batch_update",delete:"records/batch_delete",appendAttachments:"append_attachments",removeAttachments:"remove_attachments"},S=t=>({status:"failed",code:t,retryable:!1,appliedIds:[]});function j(t){if(t?.platformEnv==="online")return t.brand==="feishu"?"https://open.feishu.cn":t.brand==="lark"?"https://open.larksuite.com":void 0;if(t?.brand==="feishu"){if(t.platformEnv==="pre")return"https://open.feishu-pre.cn";if(t.platformEnv==="boe")return"https://open.feishu-boe.cn"}}function E(t,a){let i=async(e,r,n,c)=>{if(!a)return S("SDK_RUNTIME_PROFILE_MISSING");let u=j(a);if(!u)return S("SDK_RUNTIME_PROFILE_UNSUPPORTED");if(c?.signal?.aborted)return S("SDK_CANCELLED");let m,l,s;try{if(!d(r)||typeof r.baseToken!="string"||typeof r.tableId!="string"||!/^[A-Za-z0-9]+$/.test(r.baseToken)||!/^tbl[A-Za-z0-9]+$/.test(r.tableId))throw 0;if(O(n),e==="create"){if(!Array.isArray(n)||!n.every(d))throw 0;s=n.length,m={create_records:n}}else if(e==="update"){if(!d(n)||!Object.values(n).every(d))throw 0;l=Object.keys(n),s=l.length,m={update_records:n}}else if(e==="delete"){if(!Array.isArray(n)||!n.every(w))throw 0;l=n,s=n.length,m={record_id_list:n}}else{if(!d(n))throw 0;let o=Object.create(null),p=0;for(let[f,g]of Object.entries(n)){if(!w(f)||!d(g))throw 0;for(let[A,b]of Object.entries(g)){if(!A.trim()||!Array.isArray(b))throw 0;for(let h of b){if(!d(h)||typeof h.file_token!="string"||!h.file_token.trim()||Object.keys(h).some(R=>!["file_token",...e==="appendAttachments"?["image_width","image_height"]:[]].includes(R)))throw 0;for(let R of["image_width","image_height"])if(h[R]!==void 0&&(typeof h[R]!="number"||!Number.isInteger(h[R])||h[R]<=0))throw 0}p+=b.length,b.length&&(o[f]??=Object.create(null),o[f][A]=b)}}if(p>50)throw 0;if(!p)return{status:"success",appliedIds:[],notFoundIds:[],ignoredFields:[],noop:!0};l=Object.keys(o),m={attachments:o}}if(s!==void 0&&(s<1||s>200)||l&&(!l.every(w)||new Set(l).size!==l.length))throw 0}catch{return S("SDK_RECORDS_INPUT_INVALID")}try{let o=await t.fetch(`${u}/open-apis/bitable/v1/apps/${encodeURIComponent(r.baseToken)}/tables/${encodeURIComponent(r.tableId)}/${C[e]}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(m),signal:c?.signal}),p=o.headers.get("x-tt-logid")??void 0;if([401,403,404].includes(o.status))return I(o.status);if(!o.ok)return x("SDK_RECORDS_HTTP_ERROR",l,p);let f=_(await o.json(),{operation:e,requestedIds:l,count:s});return f.status==="unknown"&&p?{...f,logid:p}:f}catch(o){let p=o instanceof Error?o.name:"";return x(p==="AbortError"?"SDK_CANCELLED":p==="TimeoutError"?"SDK_TIMEOUT":"SDK_RECORDS_RESULT_UNKNOWN",l)}};return Object.fromEntries(Object.keys(C).map(e=>[e,(r,n,c)=>i(e,r,n,c)]))}var T=Symbol("base-database-runtime-profile");function N(t,a){let i=Object.freeze({platformEnv:a.platformEnv,brand:a.brand});return function(e,r){let n=Object.defineProperty({...r},T,{value:i});return t.call(this,e,n)}}function k(t){return{...t,records:E(t,t[T])}}async function D(t,a,i){let e;try{e=await t["~standard"].validate(a)}catch{throw new y("SDK_VALIDATOR_FAILED","Schema \u6821\u9A8C\u5668\u6267\u884C\u5931\u8D25")}if(e.issues){let r=e.issues.map(n=>(n.path??[]).map(c=>{let u=typeof c=="object"?c.key:c;return typeof u=="number"||typeof u=="string"?u:"[symbol]"}));throw new y(`SDK_${i}_INVALID`,i==="INPUT"?"\u8F93\u5165\u4E0D\u7B26\u5408\u5951\u7EA6":"\u8F93\u51FA\u4E0D\u7B26\u5408\u5951\u7EA6",{paths:r})}return e.value}function K(t){return async(a,i)=>{try{let e=await D(t.input,a,"INPUT"),r=await t.handler(e,k(i)),n=await D(t.output,r,"OUTPUT");return O(n),{code:0,msg:"success",data:n}}catch(e){let r=e instanceof y?e:new y("SDK_HANDLER_FAILED","\u51FD\u6570\u6267\u884C\u5931\u8D25");return console.error(JSON.stringify({source:"sdk",code:r.code,paths:r.paths,retryable:r.retryable,outcome:r.outcome})),{code:r.wireCode,msg:r.safeMessage}}}}export{y as SDKError,N as bindFunctionRuntime,k as createServerContext,K as defineFunction,_ as normalizeRecordsResult};
|
package/dist/shared.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var p=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var m=(r,n)=>{for(var e in n)p(r,e,{get:n[e],enumerable:!0})},E=(r,n,e,a)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of b(n))!y.call(r,t)&&t!==e&&p(r,t,{get:()=>n[t],enumerable:!(a=c(n,t))||a.enumerable});return r};var f=r=>E(p({},"__esModule",{value:!0}),r);var I={};m(I,{CAPABILITY_CATALOG:()=>C,CapabilityUnavailableError:()=>u,DiagnosticCode:()=>o,SDKError:()=>i,classifyRuntimeError:()=>A});module.exports=f(I);var d=Symbol.for("@lark-base-open/base-database-app-sdk/SDKError/v1"),i=class extends Error{constructor(e,a,t,l){super(a);this.code=e;this.name="SDKError",this.safeMessage=a;let s=typeof t=="object"?t:{};this.upstreamCode=typeof t=="string"?t:void 0,this.wireCode=Number.isSafeInteger(s.wireCode)&&s.wireCode!==0?s.wireCode:e==="SDK_TIMEOUT"?504:e==="SDK_CANCELLED"?499:e==="SDK_INPUT_INVALID"?400:500,this.retryable=s.retryable??l??!1,this.outcome=s.outcome??"failed",this.paths=s.paths??[]}[d]=!0;static[Symbol.hasInstance](e){return this!==i?Function.prototype[Symbol.hasInstance].call(this,e):e!==null&&typeof e=="object"&&e[d]===!0}wireCode;safeMessage;retryable;outcome;paths;upstreamCode};var C={"runtime.context":{kind:"critical",hostBaseline84afb07:!0},"http.request":{kind:"critical",hostBaseline84afb07:!0},"http.binary":{kind:"critical",hostBaseline84afb07:!0},"http.cancel":{kind:"optional",hostBaseline84afb07:!0},"function.invoke":{kind:"critical",hostBaseline84afb07:!0},"runtime.user":{kind:"optional",hostBaseline84afb07:!0},"runtime.logout":{kind:"optional",hostBaseline84afb07:!0},"runtime.requestEdit":{kind:"optional",hostBaseline84afb07:!0},"attachment.upload":{kind:"critical",hostBaseline84afb07:!0},"attachment.cancel":{kind:"optional",hostBaseline84afb07:!0},"chatbot.stream":{kind:"critical",hostBaseline84afb07:!0},"ai.function.stream":{kind:"critical",hostBaseline84afb07:!0},"runtime.lifecycle":{kind:"optional",hostBaseline84afb07:!0},"runtime.mode":{kind:"optional",hostBaseline84afb07:!0},"attachment.progress":{kind:"optional",hostBaseline84afb07:!0},"link.open":{kind:"optional",hostBaseline84afb07:!0}},o={HostUnsupported:"CAPABILITY_HOST_UNSUPPORTED",PermissionDenied:"CAPABILITY_PERMISSION_DENIED",RegionUnavailable:"CAPABILITY_REGION_UNAVAILABLE",TemporarilyUnavailable:"CAPABILITY_TEMPORARILY_UNAVAILABLE",ContextInvalid:"CAPABILITY_CONTEXT_INVALID",UnavailableUnknown:"CAPABILITY_UNAVAILABLE_UNKNOWN"},u=class extends i{constructor(e,a){super(o.HostUnsupported,`\u5F53\u524D\u5BBF\u4E3B\u4E0D\u652F\u6301 ${e} v${a}`);this.capability=e;this.minimumVersion=a;this.name="CapabilityUnavailableError"}};function A(r){let n=r&&typeof r=="object"?r:{},e=typeof n.code=="string"||typeof n.code=="number"?String(n.code):"UNKNOWN",a=o.UnavailableUnknown,t="unknown";[o.HostUnsupported,"10004","PROTOCOL_MISMATCH","ATTACHMENT_UNAVAILABLE","HTTP_RESPONSE_TYPE_UNSUPPORTED"].includes(e)?(a=o.HostUnsupported,t="host-unsupported"):[o.PermissionDenied,"403","PERMISSION_DENIED","FORBIDDEN","FUNCTION_NOT_ALLOWED"].includes(e)?(a=o.PermissionDenied,t="permission-denied"):[o.RegionUnavailable,"REGION_UNAVAILABLE","REGION_NOT_SUPPORTED"].includes(e)?(a=o.RegionUnavailable,t="region-unavailable"):[o.TemporarilyUnavailable,"REQUEST_TIMEOUT","10003","10005","HTTP_REQUEST_FAILED","FUNCTION_REQUEST_FAILED","STREAM_DISCONNECTED","STREAM_HEALTH_TIMEOUT","ATTACHMENT_UPLOAD_STALLED"].includes(e)?(a=o.TemporarilyUnavailable,t="temporary"):e===o.ContextInvalid&&(a=o.ContextInvalid,t="protocol");let l={"host-unsupported":"\u5F53\u524D\u5BBF\u4E3B\u4E0D\u652F\u6301\u6B64\u80FD\u529B","permission-denied":"\u5F53\u524D\u8EAB\u4EFD\u6216\u53D1\u5E03\u6E05\u5355\u4E0D\u5141\u8BB8\u6B64\u64CD\u4F5C","region-unavailable":"\u5BBF\u4E3B\u660E\u786E\u5F53\u524D\u533A\u57DF\u4E0D\u53EF\u7528",temporary:"\u8C03\u7528\u6682\u65F6\u5931\u8D25\uFF0C\u8BF7\u6838\u5BF9\u7ED3\u679C\u540E\u51B3\u5B9A\u662F\u5426\u91CD\u8BD5",protocol:"\u5BBF\u4E3B\u80FD\u529B\u5B57\u6BB5\u65E0\u6548",unknown:"\u8C03\u7528\u5931\u8D25\uFF0C\u539F\u56E0\u672A\u660E\u786E"};return{source:"sdk",code:a,upstreamCode:n.upstreamCode??e,category:t,retryable:t==="temporary"&&n.retryable!==!1,message:l[t],redaction:"\u539F\u59CB\u9519\u8BEF\u6D88\u606F\u548C\u4E1A\u52A1\u53C2\u6570\u5DF2\u7701\u7565"}}0&&(module.exports={CAPABILITY_CATALOG,CapabilityUnavailableError,DiagnosticCode,SDKError,classifyRuntimeError});
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
interface SDKErrorOptions {
|
|
2
|
+
wireCode?: number;
|
|
3
|
+
retryable?: boolean;
|
|
4
|
+
outcome?: "failed" | "unknown";
|
|
5
|
+
paths?: readonly (readonly (string | number)[])[];
|
|
6
|
+
}
|
|
7
|
+
/** message 必须是开发者提供的安全文案,不能包含原始错误或参数。 */
|
|
8
|
+
declare const errorBrand: unique symbol;
|
|
9
|
+
declare class SDKError extends Error {
|
|
10
|
+
readonly code: string;
|
|
11
|
+
private readonly [errorBrand];
|
|
12
|
+
static [Symbol.hasInstance](value: unknown): boolean;
|
|
13
|
+
readonly wireCode: number;
|
|
14
|
+
readonly safeMessage: string;
|
|
15
|
+
readonly retryable: boolean;
|
|
16
|
+
readonly outcome: "failed" | "unknown";
|
|
17
|
+
readonly paths: readonly (readonly (string | number)[])[];
|
|
18
|
+
readonly upstreamCode?: string;
|
|
19
|
+
constructor(code: string, message: string, options?: SDKErrorOptions | string, legacyRetryable?: boolean);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
type JsonValue = null | boolean | number | string | JsonValue[] | {
|
|
23
|
+
[key: string]: JsonValue;
|
|
24
|
+
};
|
|
25
|
+
interface FunctionEnvelope<T = unknown> {
|
|
26
|
+
code: number;
|
|
27
|
+
msg: string;
|
|
28
|
+
data?: T;
|
|
29
|
+
}
|
|
30
|
+
type IgnoredField = {
|
|
31
|
+
id: string;
|
|
32
|
+
name: string;
|
|
33
|
+
reason: string;
|
|
34
|
+
};
|
|
35
|
+
type WriteResult = {
|
|
36
|
+
status: "success";
|
|
37
|
+
appliedIds: string[];
|
|
38
|
+
notFoundIds: [];
|
|
39
|
+
ignoredFields: [];
|
|
40
|
+
attachments?: JsonValue;
|
|
41
|
+
noop?: boolean;
|
|
42
|
+
} | {
|
|
43
|
+
status: "partial";
|
|
44
|
+
appliedIds: string[];
|
|
45
|
+
notFoundIds: string[];
|
|
46
|
+
ignoredFields: IgnoredField[];
|
|
47
|
+
attachments?: JsonValue;
|
|
48
|
+
} | {
|
|
49
|
+
status: "failed";
|
|
50
|
+
code: string;
|
|
51
|
+
upstreamCode?: number;
|
|
52
|
+
retryable: false;
|
|
53
|
+
appliedIds: [];
|
|
54
|
+
} | {
|
|
55
|
+
status: "unknown";
|
|
56
|
+
code: string;
|
|
57
|
+
retryable: false;
|
|
58
|
+
requestedIds?: string[];
|
|
59
|
+
logid?: string;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
type CapabilityDescriptor = Readonly<{
|
|
63
|
+
version: number;
|
|
64
|
+
}>;
|
|
65
|
+
type CapabilityMap = Readonly<Record<string, CapabilityDescriptor>>;
|
|
66
|
+
type RuntimeCapabilities = CapabilityMap;
|
|
67
|
+
type CapabilityUnavailableReason = "permission-denied" | "region-unavailable" | "temporarily-unavailable";
|
|
68
|
+
interface CapabilityContext {
|
|
69
|
+
capabilities?: CapabilityMap;
|
|
70
|
+
capabilityUnavailable?: Readonly<Record<string, {
|
|
71
|
+
reason: CapabilityUnavailableReason;
|
|
72
|
+
retryable: boolean;
|
|
73
|
+
}>>;
|
|
74
|
+
}
|
|
75
|
+
declare const CAPABILITY_CATALOG: {
|
|
76
|
+
readonly "runtime.context": {
|
|
77
|
+
readonly kind: "critical";
|
|
78
|
+
readonly hostBaseline84afb07: true;
|
|
79
|
+
};
|
|
80
|
+
readonly "http.request": {
|
|
81
|
+
readonly kind: "critical";
|
|
82
|
+
readonly hostBaseline84afb07: true;
|
|
83
|
+
};
|
|
84
|
+
readonly "http.binary": {
|
|
85
|
+
readonly kind: "critical";
|
|
86
|
+
readonly hostBaseline84afb07: true;
|
|
87
|
+
};
|
|
88
|
+
readonly "http.cancel": {
|
|
89
|
+
readonly kind: "optional";
|
|
90
|
+
readonly hostBaseline84afb07: true;
|
|
91
|
+
};
|
|
92
|
+
readonly "function.invoke": {
|
|
93
|
+
readonly kind: "critical";
|
|
94
|
+
readonly hostBaseline84afb07: true;
|
|
95
|
+
};
|
|
96
|
+
readonly "runtime.user": {
|
|
97
|
+
readonly kind: "optional";
|
|
98
|
+
readonly hostBaseline84afb07: true;
|
|
99
|
+
};
|
|
100
|
+
readonly "runtime.logout": {
|
|
101
|
+
readonly kind: "optional";
|
|
102
|
+
readonly hostBaseline84afb07: true;
|
|
103
|
+
};
|
|
104
|
+
readonly "runtime.requestEdit": {
|
|
105
|
+
readonly kind: "optional";
|
|
106
|
+
readonly hostBaseline84afb07: true;
|
|
107
|
+
};
|
|
108
|
+
readonly "attachment.upload": {
|
|
109
|
+
readonly kind: "critical";
|
|
110
|
+
readonly hostBaseline84afb07: true;
|
|
111
|
+
};
|
|
112
|
+
readonly "attachment.cancel": {
|
|
113
|
+
readonly kind: "optional";
|
|
114
|
+
readonly hostBaseline84afb07: true;
|
|
115
|
+
};
|
|
116
|
+
readonly "chatbot.stream": {
|
|
117
|
+
readonly kind: "critical";
|
|
118
|
+
readonly hostBaseline84afb07: true;
|
|
119
|
+
};
|
|
120
|
+
readonly "ai.function.stream": {
|
|
121
|
+
readonly kind: "critical";
|
|
122
|
+
readonly hostBaseline84afb07: true;
|
|
123
|
+
};
|
|
124
|
+
readonly "runtime.lifecycle": {
|
|
125
|
+
readonly kind: "optional";
|
|
126
|
+
readonly hostBaseline84afb07: true;
|
|
127
|
+
};
|
|
128
|
+
readonly "runtime.mode": {
|
|
129
|
+
readonly kind: "optional";
|
|
130
|
+
readonly hostBaseline84afb07: true;
|
|
131
|
+
};
|
|
132
|
+
readonly "attachment.progress": {
|
|
133
|
+
readonly kind: "optional";
|
|
134
|
+
readonly hostBaseline84afb07: true;
|
|
135
|
+
};
|
|
136
|
+
readonly "link.open": {
|
|
137
|
+
readonly kind: "optional";
|
|
138
|
+
readonly hostBaseline84afb07: true;
|
|
139
|
+
};
|
|
140
|
+
};
|
|
141
|
+
type CapabilityName = keyof typeof CAPABILITY_CATALOG;
|
|
142
|
+
interface CapabilityQueryResult {
|
|
143
|
+
name: string;
|
|
144
|
+
requiredVersion: number;
|
|
145
|
+
version: number | null;
|
|
146
|
+
supported: boolean;
|
|
147
|
+
source: "advertised" | "host-baseline-84afb07";
|
|
148
|
+
availability: "available" | "unknown" | CapabilityUnavailableReason | "unsupported";
|
|
149
|
+
}
|
|
150
|
+
declare const DiagnosticCode: {
|
|
151
|
+
readonly HostUnsupported: "CAPABILITY_HOST_UNSUPPORTED";
|
|
152
|
+
readonly PermissionDenied: "CAPABILITY_PERMISSION_DENIED";
|
|
153
|
+
readonly RegionUnavailable: "CAPABILITY_REGION_UNAVAILABLE";
|
|
154
|
+
readonly TemporarilyUnavailable: "CAPABILITY_TEMPORARILY_UNAVAILABLE";
|
|
155
|
+
readonly ContextInvalid: "CAPABILITY_CONTEXT_INVALID";
|
|
156
|
+
readonly UnavailableUnknown: "CAPABILITY_UNAVAILABLE_UNKNOWN";
|
|
157
|
+
};
|
|
158
|
+
type DiagnosticCategory = "host-unsupported" | "permission-denied" | "region-unavailable" | "temporary" | "protocol" | "unknown";
|
|
159
|
+
interface RuntimeDiagnostic {
|
|
160
|
+
source: "sdk";
|
|
161
|
+
code: string;
|
|
162
|
+
upstreamCode?: string;
|
|
163
|
+
category: DiagnosticCategory;
|
|
164
|
+
retryable: boolean;
|
|
165
|
+
message: string;
|
|
166
|
+
redaction: "原始错误消息和业务参数已省略";
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
declare class CapabilityUnavailableError extends SDKError {
|
|
170
|
+
readonly capability: string;
|
|
171
|
+
readonly minimumVersion: number;
|
|
172
|
+
constructor(capability: string, minimumVersion: number);
|
|
173
|
+
}
|
|
174
|
+
/** 不解析 message 猜测原因;可恢复不代表写入可安全重试。 */
|
|
175
|
+
declare function classifyRuntimeError(error: unknown): RuntimeDiagnostic;
|
|
176
|
+
|
|
177
|
+
export { CAPABILITY_CATALOG, CapabilityContext, CapabilityDescriptor, CapabilityMap, CapabilityName, CapabilityQueryResult, CapabilityUnavailableError, CapabilityUnavailableReason, DiagnosticCategory, DiagnosticCode, FunctionEnvelope, JsonValue, RuntimeCapabilities, RuntimeDiagnostic, SDKError, SDKErrorOptions, WriteResult, classifyRuntimeError };
|