@lark-base-open/base-database-app-sdk 0.5.2 → 0.6.0-durable.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/README.md +7 -1
- package/capabilities.json +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.d.cts +1 -1
- package/dist/codegen.d.ts +1 -1
- package/dist/codegen.js +1 -1
- package/dist/durable/activity.cjs +25 -0
- package/dist/durable/activity.d.cts +6 -0
- package/dist/durable/activity.d.ts +6 -0
- package/dist/durable/workflow.cjs +107 -0
- package/dist/durable/workflow.d.cts +15 -0
- package/dist/durable/workflow.d.ts +15 -0
- package/dist/page.js +1 -1
- package/docs/codegen.md +2 -0
- package/docs/durable.md +54 -0
- package/docs/exports.md +12 -0
- package/examples/durable-activities.ts +3 -0
- package/examples/durable-workflow.ts +8 -0
- package/package.json +36 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.6.0-durable.1] - 2026-11-03
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- 修复 Durable Function 契约生成失败,codegen 直接接受 `functionType: 6` 并保留控制命令参数与输出类型。
|
|
8
|
+
|
|
9
|
+
## [0.6.0-durable.0] - 2026-11-03
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- 在 0.5.2 功能基线上提供 `/durable/workflow` 与 `/durable/activity`,支持持久化步骤、等待、进度、事件及站点 Function 调用。
|
|
14
|
+
- 提供 Durable 使用文档和可编译的 Workflow/Activity 示例。
|
|
15
|
+
|
|
16
|
+
### Compatibility
|
|
17
|
+
|
|
18
|
+
- Durable 入口需要平台提供匹配的托管运行时;Temporal 1.24.0 作为可选 peer 依赖提供。
|
|
19
|
+
|
|
3
20
|
## 0.5.2 - 2026-10-30
|
|
4
21
|
|
|
5
22
|
### Added
|
|
@@ -28,6 +45,12 @@
|
|
|
28
45
|
- 页面启动时向平台报告所用的 SDK 版本,便于排查问题。
|
|
29
46
|
- 页面出现未处理的错误时,错误信息会上报给平台;内容会截断,并去掉链接里的参数。
|
|
30
47
|
|
|
48
|
+
## [0.5.0-durable.0] - 2026-10-26
|
|
49
|
+
|
|
50
|
+
### Added
|
|
51
|
+
|
|
52
|
+
- 新增 Durable Workflow 与 Activity 入口,支持持久化步骤、等待、进度和站点 Function 调用。
|
|
53
|
+
|
|
31
54
|
## 0.4.2 - 2026-10-26
|
|
32
55
|
|
|
33
56
|
### Fixed
|
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.
|
|
5
|
+
安装:`npm install @lark-base-open/base-database-app-sdk@0.6.0-durable.1`。从旧版本升级前请阅读 [变更记录](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.2.1。
|
|
8
8
|
|
|
@@ -33,3 +33,9 @@ SDK 文档说明本版本 API、组件、兼容语义与可编译示例。业务
|
|
|
33
33
|
页面类型客户端生成使用 [codegen](docs/codegen.md) 入口;CLI 仅提取契约、隔离调用并写入返回文件。
|
|
34
34
|
|
|
35
35
|
新建工程可显式开启 `styleScope: 'components'` 隔离业务样式;主题和迁移契约见 [启动说明](docs/start-base-app.md)。
|
|
36
|
+
|
|
37
|
+
## Durable Function
|
|
38
|
+
|
|
39
|
+
本预发布版本通过 npm 的 `durable` 标签提供 `/durable/workflow` 和 `/durable/activity` 持久化函数 API,见 [Durable 文档](docs/durable.md)。
|
|
40
|
+
|
|
41
|
+
使用前需确认平台部署了匹配的 Durable 运行时;Temporal 为可选 peer,仅 Durable 开发和执行环境安装匹配版本,普通页面和普通 Function 不依赖它。ESM import 与 CJS require 共享 Durable 模块。
|
package/capabilities.json
CHANGED
package/dist/codegen.cjs
CHANGED
|
@@ -13,5 +13,5 @@ export type ${t} = unknown;`}}function _(n){if(!n||n.type!=="object")return;let
|
|
|
13
13
|
return response.data as ${a};
|
|
14
14
|
},`)}return r.push(`declare module '${p}' { interface FunctionInputMap extends GeneratedFunctionInputs {} }`,"export const functions = {",...e,"};",""),r.join(`
|
|
15
15
|
`)}function j(n,t){let i=structuredClone(n);return f(i,r=>{Array.isArray(r.prefixItems)&&(r.additionalItems=r.items??r.maxItems!==r.prefixItems.length,r.items=r.prefixItems,delete r.prefixItems)}),i.title=t,i}function d(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(", ")}]`:d(n)?`{ ${Object.entries(n).map(([t,i])=>`${JSON.stringify(t)}: ${w(i)}`).join("; ")} }`:"never"}function P(n,t){switch(t){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 d(n);default:return!1}}function G(n){return typeof n.type=="string"?[n.type]:Array.isArray(n.type)?n.type.filter(t=>typeof t=="string"):[]}function J(n,t){switch(t){case"string":return"string";case"integer":case"number":return"number";case"boolean":return"boolean";case"null":return"null";case"array":{let i=n.prefixItems,r=Array.isArray(i),e=r?i.filter(d):[];if(r&&n.minItems===e.length&&n.maxItems===e.length)return`[${e.map(y).join(", ")}]`;let o=d(n.items)?y(n.items):"unknown";return e.length===0?`Array<${o}>`:`[${[...e.map(u=>`${y(u)}?`),`...Array<${o}>`].join(", ")}]`}case"object":{let i=d(n.properties)?n.properties:{},r=new Set(Array.isArray(n.required)?n.required.filter(c=>typeof c=="string"):[]),e=Object.entries(i).filter(c=>d(c[1])),o=new Set(e.map(([c])=>c)),s=[...r].filter(c=>!o.has(c));if(s.length>0&&n.additionalProperties===!1)return"never";let u=e.map(([c,g])=>`${JSON.stringify(c)}${r.has(c)?"":"?"}: ${y(g)}`);u.push(...s.map(c=>`${JSON.stringify(c)}: unknown`));let a=`{ ${u.join("; ")} }`;return n.additionalProperties===!1?u.length===0?"Record<string, never>":a:`${a} & Record<string, unknown>`}default:return"unknown"}}function y(n){let t=["anyOf","oneOf","allOf"].filter(e=>Array.isArray(n[e]));if(t.length){let e={...n};for(let u of t)delete e[u];let o=t.map(u=>{let a=n[u].filter(d).map(y);return a.length?a.map(c=>`(${c})`).join(u==="allOf"?" & ":" | "):"never"}),s=y(e);return s!=="unknown"&&o.unshift(s),o.map(u=>`(${u})`).join(" & ")}if(Object.hasOwn(n,"const"))return w(n.const);let i=G(n);if(Array.isArray(n.enum)&&n.enum.length>0){let e=n.enum.filter(o=>i.length===0||i.some(s=>P(o,s)));return e.length===0?"never":e.map(w).join(" | ")}let r=[...new Set(i.map(e=>J(n,e)))];return r.length===0?"unknown":r.join(" | ")}function F(n){let t=[...n].sort((e,o)=>e.functionId<o.functionId?-1:e.functionId>o.functionId?1:0),i=t.map(e=>` ${JSON.stringify(e.functionId)}: ${y(e.inputSchema)}`),r=t.flatMap(e=>{let o=Object.entries(e.parameterOptions??{});return o.length===0?[]:[` ${JSON.stringify(e.functionId)}: {`,...o.map(([s,u])=>` ${JSON.stringify(s)}: ${JSON.stringify(u)},`)," },"]});return["/* Generated by base-database-cli from Function metadata. Do not edit. */","// prettier-ignore","export type DatabaseFunctionInputMap = {",...i,"}",...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(i,r){super(r);this.code=i;this.name="CodegenError"}toJSON(){return{code:this.code,message:this.message}}},k=b.replace("./database-function-inputs.generated","../generated/function-inputs"),I=n=>!!n&&typeof n=="object"&&!Array.isArray(n);function S(n){if(!I(n)||n.contractFormatVersion!==1)throw new m("CONTRACT_FORMAT_UNSUPPORTED","Supported contractFormatVersion: 1");let t=()=>{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")&&t();let i;try{i=JSON.stringify(n)}catch{return t()}Buffer.byteLength(i)>4*1024*1024&&t();for(let o of["functions","inputs"]){let s=n[o];if(!Array.isArray(s)||s.length>1e3)return t();let u=new Set;for(let a of s){if(!I(a)||typeof a.functionId!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(a.functionId)||u.has(a.functionId))return t();u.add(a.functionId),o==="functions"&&(typeof a.functionType!="number"||![1,2,5].includes(a.functionType))&&t(),o==="inputs"&&!I(a.inputSchema)&&t(),o==="inputs"&&a.functionType!==void 0&&(typeof a.functionType!="number"||![1,2,5].includes(a.functionType))&&t();for(let c of o==="inputs"?["inputSchema"]:["input","output"])if(a[c]!==void 0)try{l(a[c])}catch{t()}a.parameterOptions!==void 0&&(!I(a.parameterOptions)||!Object.values(a.parameterOptions).every(Array.isArray))&&t()}}let r=new Set(n.inputs.map(o=>o.functionId));n.functions.some(o=>!r.has(o.functionId))&&t();let e=new Map(n.functions.map(o=>[o.functionId,o.functionType]));n.inputs.some(o=>o.functionType!==void 0&&e.has(o.functionId)&&e.get(o.functionId)!==o.functionType)&&t()}async function L(n){if(S(n),n.previousAugmentation!==void 0&&![b,O,k].includes(n.previousAugmentation))throw new m("CONTRACT_INPUT_MAP_CONFLICT","Unrecognized FunctionInputMap augmentation; review before replacing");let t=[{path:n.layout==="workspace"?"page/src/generated/function-inputs.ts":"page/src/lib/database-function-inputs.generated.ts",content:`${await $(n.functions,n.inputs)}
|
|
16
|
+
`)}var U=[1],m=class extends Error{constructor(i,r){super(r);this.code=i;this.name="CodegenError"}toJSON(){return{code:this.code,message:this.message}}},k=b.replace("./database-function-inputs.generated","../generated/function-inputs"),I=n=>!!n&&typeof n=="object"&&!Array.isArray(n);function S(n){if(!I(n)||n.contractFormatVersion!==1)throw new m("CONTRACT_FORMAT_UNSUPPORTED","Supported contractFormatVersion: 1");let t=()=>{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")&&t();let i;try{i=JSON.stringify(n)}catch{return t()}Buffer.byteLength(i)>4*1024*1024&&t();for(let o of["functions","inputs"]){let s=n[o];if(!Array.isArray(s)||s.length>1e3)return t();let u=new Set;for(let a of s){if(!I(a)||typeof a.functionId!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(a.functionId)||u.has(a.functionId))return t();u.add(a.functionId),o==="functions"&&(typeof a.functionType!="number"||![1,2,5,6].includes(a.functionType))&&t(),o==="inputs"&&!I(a.inputSchema)&&t(),o==="inputs"&&a.functionType!==void 0&&(typeof a.functionType!="number"||![1,2,5,6].includes(a.functionType))&&t();for(let c of o==="inputs"?["inputSchema"]:["input","output"])if(a[c]!==void 0)try{l(a[c])}catch{t()}a.parameterOptions!==void 0&&(!I(a.parameterOptions)||!Object.values(a.parameterOptions).every(Array.isArray))&&t()}}let r=new Set(n.inputs.map(o=>o.functionId));n.functions.some(o=>!r.has(o.functionId))&&t();let e=new Map(n.functions.map(o=>[o.functionId,o.functionType]));n.inputs.some(o=>o.functionType!==void 0&&e.has(o.functionId)&&e.get(o.functionId)!==o.functionType)&&t()}async function L(n){if(S(n),n.previousAugmentation!==void 0&&![b,O,k].includes(n.previousAugmentation))throw new m("CONTRACT_INPUT_MAP_CONFLICT","Unrecognized FunctionInputMap augmentation; review before replacing");let t=[{path:n.layout==="workspace"?"page/src/generated/function-inputs.ts":"page/src/lib/database-function-inputs.generated.ts",content:`${await $(n.functions,n.inputs)}
|
|
17
17
|
${F(n.inputs)}`}];return n.client&&t.push({path:"page/src/generated/functions.ts",content:await N(n.functions,n.schemaHash,n.layout==="workspace"?"./function-inputs":"../lib/database-function-inputs.generated")}),n.augmentation!=="none"&&t.push({path:"page/src/lib/function-input-map.generated.ts",content:n.augmentation==="compat"?n.layout==="workspace"?k:b:O}),t}0&&(module.exports={CodegenError,SUPPORTED_CONTRACT_FORMAT_VERSIONS,generateFunctionClients,validateContractData});
|
package/dist/codegen.d.cts
CHANGED
|
@@ -9,7 +9,7 @@ declare const SUPPORTED_CONTRACT_FORMAT_VERSIONS: readonly [1];
|
|
|
9
9
|
interface FunctionInputContract {
|
|
10
10
|
functionId: string;
|
|
11
11
|
/** CLI also supplies the type when regenerating a legacy helper without client contracts. */
|
|
12
|
-
functionType?: 1 | 2 | 5;
|
|
12
|
+
functionType?: 1 | 2 | 5 | 6;
|
|
13
13
|
inputSchema: Record<string, unknown>;
|
|
14
14
|
parameterOptions?: Record<string, unknown[]>;
|
|
15
15
|
}
|
package/dist/codegen.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ declare const SUPPORTED_CONTRACT_FORMAT_VERSIONS: readonly [1];
|
|
|
9
9
|
interface FunctionInputContract {
|
|
10
10
|
functionId: string;
|
|
11
11
|
/** CLI also supplies the type when regenerating a legacy helper without client contracts. */
|
|
12
|
-
functionType?: 1 | 2 | 5;
|
|
12
|
+
functionType?: 1 | 2 | 5 | 6;
|
|
13
13
|
inputSchema: Record<string, unknown>;
|
|
14
14
|
parameterOptions?: Record<string, unknown[]>;
|
|
15
15
|
}
|
package/dist/codegen.js
CHANGED
|
@@ -13,5 +13,5 @@ export type ${e} = unknown;`}}function k(n){if(!n||n.type!=="object")return;let
|
|
|
13
13
|
return response.data as ${a};
|
|
14
14
|
},`)}return r.push(`declare module '${p}' { interface FunctionInputMap extends GeneratedFunctionInputs {} }`,"export const functions = {",...t,"};",""),r.join(`
|
|
15
15
|
`)}function S(n,e){let i=structuredClone(n);return f(i,r=>{Array.isArray(r.prefixItems)&&(r.additionalItems=r.items??r.maxItems!==r.prefixItems.length,r.items=r.prefixItems,delete r.prefixItems)}),i.title=e,i}function d(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(", ")}]`:d(n)?`{ ${Object.entries(n).map(([e,i])=>`${JSON.stringify(e)}: ${w(i)}`).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 d(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 i=n.prefixItems,r=Array.isArray(i),t=r?i.filter(d):[];if(r&&n.minItems===t.length&&n.maxItems===t.length)return`[${t.map(y).join(", ")}]`;let o=d(n.items)?y(n.items):"unknown";return t.length===0?`Array<${o}>`:`[${[...t.map(u=>`${y(u)}?`),`...Array<${o}>`].join(", ")}]`}case"object":{let i=d(n.properties)?n.properties:{},r=new Set(Array.isArray(n.required)?n.required.filter(c=>typeof c=="string"):[]),t=Object.entries(i).filter(c=>d(c[1])),o=new Set(t.map(([c])=>c)),s=[...r].filter(c=>!o.has(c));if(s.length>0&&n.additionalProperties===!1)return"never";let u=t.map(([c,g])=>`${JSON.stringify(c)}${r.has(c)?"":"?"}: ${y(g)}`);u.push(...s.map(c=>`${JSON.stringify(c)}: unknown`));let a=`{ ${u.join("; ")} }`;return n.additionalProperties===!1?u.length===0?"Record<string, never>":a:`${a} & Record<string, unknown>`}default:return"unknown"}}function y(n){let e=["anyOf","oneOf","allOf"].filter(t=>Array.isArray(n[t]));if(e.length){let t={...n};for(let u of e)delete t[u];let o=e.map(u=>{let a=n[u].filter(d).map(y);return a.length?a.map(c=>`(${c})`).join(u==="allOf"?" & ":" | "):"never"}),s=y(t);return s!=="unknown"&&o.unshift(s),o.map(u=>`(${u})`).join(" & ")}if(Object.hasOwn(n,"const"))return w(n.const);let i=R(n);if(Array.isArray(n.enum)&&n.enum.length>0){let t=n.enum.filter(o=>i.length===0||i.some(s=>C(o,s)));return t.length===0?"never":t.map(w).join(" | ")}let r=[...new Set(i.map(t=>x(n,t)))];return r.length===0?"unknown":r.join(" | ")}function $(n){let e=[...n].sort((t,o)=>t.functionId<o.functionId?-1:t.functionId>o.functionId?1:0),i=e.map(t=>` ${JSON.stringify(t.functionId)}: ${y(t.inputSchema)}`),r=e.flatMap(t=>{let o=Object.entries(t.parameterOptions??{});return o.length===0?[]:[` ${JSON.stringify(t.functionId)}: {`,...o.map(([s,u])=>` ${JSON.stringify(s)}: ${JSON.stringify(u)},`)," },"]});return["/* Generated by base-database-cli from Function metadata. Do not edit. */","// prettier-ignore","export type DatabaseFunctionInputMap = {",...i,"}",...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(i,r){super(r);this.code=i;this.name="CodegenError"}toJSON(){return{code:this.code,message:this.message}}},N=b.replace("./database-function-inputs.generated","../generated/function-inputs"),I=n=>!!n&&typeof n=="object"&&!Array.isArray(n);function D(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 i;try{i=JSON.stringify(n)}catch{return e()}Buffer.byteLength(i)>4*1024*1024&&e();for(let o of["functions","inputs"]){let s=n[o];if(!Array.isArray(s)||s.length>1e3)return e();let u=new Set;for(let a of s){if(!I(a)||typeof a.functionId!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(a.functionId)||u.has(a.functionId))return e();u.add(a.functionId),o==="functions"&&(typeof a.functionType!="number"||![1,2,5].includes(a.functionType))&&e(),o==="inputs"&&!I(a.inputSchema)&&e(),o==="inputs"&&a.functionType!==void 0&&(typeof a.functionType!="number"||![1,2,5].includes(a.functionType))&&e();for(let c of o==="inputs"?["inputSchema"]:["input","output"])if(a[c]!==void 0)try{l(a[c])}catch{e()}a.parameterOptions!==void 0&&(!I(a.parameterOptions)||!Object.values(a.parameterOptions).every(Array.isArray))&&e()}}let r=new Set(n.inputs.map(o=>o.functionId));n.functions.some(o=>!r.has(o.functionId))&&e();let t=new Map(n.functions.map(o=>[o.functionId,o.functionType]));n.inputs.some(o=>o.functionType!==void 0&&t.has(o.functionId)&&t.get(o.functionId)!==o.functionType)&&e()}async function V(n){if(D(n),n.previousAugmentation!==void 0&&![b,A,N].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)}
|
|
16
|
+
`)}var L=[1],m=class extends Error{constructor(i,r){super(r);this.code=i;this.name="CodegenError"}toJSON(){return{code:this.code,message:this.message}}},N=b.replace("./database-function-inputs.generated","../generated/function-inputs"),I=n=>!!n&&typeof n=="object"&&!Array.isArray(n);function D(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 i;try{i=JSON.stringify(n)}catch{return e()}Buffer.byteLength(i)>4*1024*1024&&e();for(let o of["functions","inputs"]){let s=n[o];if(!Array.isArray(s)||s.length>1e3)return e();let u=new Set;for(let a of s){if(!I(a)||typeof a.functionId!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(a.functionId)||u.has(a.functionId))return e();u.add(a.functionId),o==="functions"&&(typeof a.functionType!="number"||![1,2,5,6].includes(a.functionType))&&e(),o==="inputs"&&!I(a.inputSchema)&&e(),o==="inputs"&&a.functionType!==void 0&&(typeof a.functionType!="number"||![1,2,5,6].includes(a.functionType))&&e();for(let c of o==="inputs"?["inputSchema"]:["input","output"])if(a[c]!==void 0)try{l(a[c])}catch{e()}a.parameterOptions!==void 0&&(!I(a.parameterOptions)||!Object.values(a.parameterOptions).every(Array.isArray))&&e()}}let r=new Set(n.inputs.map(o=>o.functionId));n.functions.some(o=>!r.has(o.functionId))&&e();let t=new Map(n.functions.map(o=>[o.functionId,o.functionType]));n.inputs.some(o=>o.functionType!==void 0&&t.has(o.functionId)&&t.get(o.functionId)!==o.functionType)&&e()}async function V(n){if(D(n),n.previousAugmentation!==void 0&&![b,A,N].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
17
|
${$(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"?N:b:A}),e}export{m as CodegenError,L as SUPPORTED_CONTRACT_FORMAT_VERSIONS,V as generateFunctionClients,D as validateContractData};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getAttempt = getAttempt;
|
|
4
|
+
exports.cancellationSignal = cancellationSignal;
|
|
5
|
+
exports.__installCapabilityTransport = __installCapabilityTransport;
|
|
6
|
+
exports.invokeFunction = invokeFunction;
|
|
7
|
+
const activity_1 = require("@temporalio/activity");
|
|
8
|
+
function getAttempt() { return (0, activity_1.activityInfo)().attempt; }
|
|
9
|
+
function cancellationSignal() { return activity_1.Context.current().cancellationSignal; }
|
|
10
|
+
let capabilityTransport;
|
|
11
|
+
// 只由通用 Worker 启动器装配;公开 SDK 类型不暴露凭证或配置入口。
|
|
12
|
+
/** @internal */
|
|
13
|
+
function __installCapabilityTransport(transport) {
|
|
14
|
+
if (capabilityTransport)
|
|
15
|
+
throw new Error('Site capability transport is already configured');
|
|
16
|
+
capabilityTransport = transport;
|
|
17
|
+
}
|
|
18
|
+
/** input 与普通 Site Function 的请求体一致,例如 { params: { city: '北京' } }。 */
|
|
19
|
+
async function invokeFunction(functionId, input, options) {
|
|
20
|
+
if (!functionId || !options?.key || options.key.length > 256)
|
|
21
|
+
throw new Error('Function and a stable call key are required');
|
|
22
|
+
if (!capabilityTransport)
|
|
23
|
+
throw new Error('Site capability transport is unavailable');
|
|
24
|
+
return capabilityTransport((0, activity_1.activityInfo)().taskToken, { function_id: functionId, call_key: options.key, payload: input }, cancellationSignal());
|
|
25
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare function getAttempt(): number;
|
|
2
|
+
export declare function cancellationSignal(): AbortSignal;
|
|
3
|
+
/** input 与普通 Site Function 的请求体一致,例如 { params: { city: '北京' } }。 */
|
|
4
|
+
export declare function invokeFunction<T = unknown>(functionId: string, input: Record<string, unknown>, options: {
|
|
5
|
+
key: string;
|
|
6
|
+
}): Promise<T>;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare function getAttempt(): number;
|
|
2
|
+
export declare function cancellationSignal(): AbortSignal;
|
|
3
|
+
/** input 与普通 Site Function 的请求体一致,例如 { params: { city: '北京' } }。 */
|
|
4
|
+
export declare function invokeFunction<T = unknown>(functionId: string, input: Record<string, unknown>, options: {
|
|
5
|
+
key: string;
|
|
6
|
+
}): Promise<T>;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.runDefinition = runDefinition;
|
|
4
|
+
exports.callStep = callStep;
|
|
5
|
+
exports.sleep = sleep;
|
|
6
|
+
exports.reportProgress = reportProgress;
|
|
7
|
+
exports.waitForEvent = waitForEvent;
|
|
8
|
+
const workflow_1 = require("@temporalio/workflow");
|
|
9
|
+
let state;
|
|
10
|
+
let definition;
|
|
11
|
+
let keys;
|
|
12
|
+
let events;
|
|
13
|
+
let receivedEvents;
|
|
14
|
+
let eventOverflow;
|
|
15
|
+
function receiveEvent(name, data, id) {
|
|
16
|
+
if (!(definition.events ?? ['approval']).includes(name))
|
|
17
|
+
return;
|
|
18
|
+
const key = id === undefined ? undefined : name + ':' + id;
|
|
19
|
+
if (key && receivedEvents.has(key))
|
|
20
|
+
return;
|
|
21
|
+
if (receivedEvents.size >= 1000 || [...events.values()].reduce((n, items) => n + items.length, 0) >= 1000) {
|
|
22
|
+
eventOverflow = true;
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
if (key)
|
|
26
|
+
receivedEvents.add(key);
|
|
27
|
+
const pending = events.get(name) ?? [];
|
|
28
|
+
pending.push(data);
|
|
29
|
+
events.set(name, pending);
|
|
30
|
+
}
|
|
31
|
+
/** @internal */
|
|
32
|
+
async function runDefinition(meta, fn, input) {
|
|
33
|
+
definition = meta;
|
|
34
|
+
keys = new Set();
|
|
35
|
+
events = new Map();
|
|
36
|
+
receivedEvents = new Set();
|
|
37
|
+
eventOverflow = false;
|
|
38
|
+
state = { stage: 'starting', processed: 0, total: 0, paused: false, approved: false, results: [] };
|
|
39
|
+
(0, workflow_1.setHandler)((0, workflow_1.defineQuery)('progress'), () => ({ ...state, results: [...state.results] }));
|
|
40
|
+
(0, workflow_1.setHandler)((0, workflow_1.defineSignal)('pause'), () => { state.paused = true; });
|
|
41
|
+
(0, workflow_1.setHandler)((0, workflow_1.defineSignal)('resume'), () => { state.paused = false; });
|
|
42
|
+
(0, workflow_1.setHandler)((0, workflow_1.defineSignal)('approve'), () => { state.approved = true; receiveEvent('approval', { approved: true }); });
|
|
43
|
+
(0, workflow_1.setHandler)((0, workflow_1.defineSignal)('event'), (event) => {
|
|
44
|
+
if (!event || typeof event.name !== 'string' || typeof event.id !== 'string' || event.id.length < 8 || event.id.length > 128)
|
|
45
|
+
return;
|
|
46
|
+
receiveEvent(event.name, event.data, event.id);
|
|
47
|
+
});
|
|
48
|
+
try {
|
|
49
|
+
const result = await fn(input);
|
|
50
|
+
await boundary();
|
|
51
|
+
state.stage = 'completed';
|
|
52
|
+
return result;
|
|
53
|
+
}
|
|
54
|
+
catch (e) {
|
|
55
|
+
if (e instanceof TypeError || e instanceof RangeError)
|
|
56
|
+
throw workflow_1.ApplicationFailure.nonRetryable('Durable Function definition error', 'DefinitionError');
|
|
57
|
+
throw e;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async function boundary() {
|
|
61
|
+
if (eventOverflow)
|
|
62
|
+
throw workflow_1.ApplicationFailure.nonRetryable('Durable event limit exceeded', 'EventLimitExceeded');
|
|
63
|
+
if (state.paused) {
|
|
64
|
+
state.stage = 'paused';
|
|
65
|
+
await (0, workflow_1.condition)(() => !state.paused || eventOverflow);
|
|
66
|
+
}
|
|
67
|
+
if (eventOverflow)
|
|
68
|
+
throw workflow_1.ApplicationFailure.nonRetryable('Durable event limit exceeded', 'EventLimitExceeded');
|
|
69
|
+
}
|
|
70
|
+
async function callStep(name, args, options) {
|
|
71
|
+
await boundary();
|
|
72
|
+
if (!definition.activities[name] || !options.key || keys.has(options.key) || keys.size >= 100)
|
|
73
|
+
throw workflow_1.ApplicationFailure.nonRetryable('Invalid or repeated step key', 'DefinitionError');
|
|
74
|
+
keys.add(options.key);
|
|
75
|
+
const policy = definition.activities[name];
|
|
76
|
+
state.stage = 'processing';
|
|
77
|
+
const activity = definition.id + '__' + name;
|
|
78
|
+
const proxy = (0, workflow_1.proxyActivities)({
|
|
79
|
+
activityId: options.key, startToCloseTimeout: policy.timeout, scheduleToCloseTimeout: '2 minutes',
|
|
80
|
+
retry: { initialInterval: '1 second', maximumInterval: '5 seconds', maximumAttempts: policy.retry.maximumAttempts },
|
|
81
|
+
});
|
|
82
|
+
return proxy[activity](args);
|
|
83
|
+
}
|
|
84
|
+
async function sleep(milliseconds) {
|
|
85
|
+
await boundary();
|
|
86
|
+
state.stage = 'durable_wait';
|
|
87
|
+
await (0, workflow_1.sleep)(milliseconds);
|
|
88
|
+
await boundary();
|
|
89
|
+
}
|
|
90
|
+
function reportProgress(progress) {
|
|
91
|
+
Object.assign(state, progress);
|
|
92
|
+
}
|
|
93
|
+
async function waitForEvent(name, options) {
|
|
94
|
+
if (!(definition.events ?? ['approval']).includes(name))
|
|
95
|
+
throw workflow_1.ApplicationFailure.nonRetryable('Undeclared event', 'DefinitionError');
|
|
96
|
+
if (!Number.isFinite(options.timeout) || options.timeout <= 0)
|
|
97
|
+
throw workflow_1.ApplicationFailure.nonRetryable('Invalid event timeout', 'DefinitionError');
|
|
98
|
+
await boundary();
|
|
99
|
+
state.stage = 'waiting_' + name;
|
|
100
|
+
if (!await (0, workflow_1.condition)(() => (events.get(name)?.length ?? 0) > 0 || eventOverflow, options.timeout))
|
|
101
|
+
throw workflow_1.ApplicationFailure.nonRetryable('Event wait timed out', 'EventTimeout');
|
|
102
|
+
await boundary();
|
|
103
|
+
const result = events.get(name).shift();
|
|
104
|
+
if (name === 'approval')
|
|
105
|
+
state.approved = false;
|
|
106
|
+
return result;
|
|
107
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
type Json = any;
|
|
2
|
+
export declare function callStep<T>(name: string, args: Json, options: {
|
|
3
|
+
key: string;
|
|
4
|
+
}): Promise<T>;
|
|
5
|
+
export declare function sleep(milliseconds: number): Promise<void>;
|
|
6
|
+
export declare function reportProgress(progress: {
|
|
7
|
+
stage?: string;
|
|
8
|
+
processed: number;
|
|
9
|
+
total: number;
|
|
10
|
+
results?: Json[];
|
|
11
|
+
}): void;
|
|
12
|
+
export declare function waitForEvent<T = Json>(name: string, options: {
|
|
13
|
+
timeout: number;
|
|
14
|
+
}): Promise<T>;
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
type Json = any;
|
|
2
|
+
export declare function callStep<T>(name: string, args: Json, options: {
|
|
3
|
+
key: string;
|
|
4
|
+
}): Promise<T>;
|
|
5
|
+
export declare function sleep(milliseconds: number): Promise<void>;
|
|
6
|
+
export declare function reportProgress(progress: {
|
|
7
|
+
stage?: string;
|
|
8
|
+
processed: number;
|
|
9
|
+
total: number;
|
|
10
|
+
results?: Json[];
|
|
11
|
+
}): void;
|
|
12
|
+
export declare function waitForEvent<T = Json>(name: string, options: {
|
|
13
|
+
timeout: number;
|
|
14
|
+
}): Promise<T>;
|
|
15
|
+
export {};
|
package/dist/page.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as Ze,B as Se,C as fe,D as ge,E as Ae,F as Ie,G as ye,H as ke,I as Re,J as he,K as Fe,L as Te,M as $e,N as B,O as et,P as U,Q as tt,R as nt,S as N,T as ot,U as it,V as G,W as V,X as at,Y as rt,Z as st,_ as ct,a as J,b as X,c as Z,d as $,e as ee,f as te,g as ne,h as x,i as _,j as oe,k as ie,l as m,m as ae,n as re,o as se,p as ce,q as ue,r as de,s as me,t as le,u as pe,v as Ye,w as L,x as je,y as Je,z as Xe}from"./chunk-EG6R7YAD.js";import{a as We,b as Qe,c as v,d as h}from"./chunk-ZKBZAK4L.js";import{a as Ke}from"./chunk-3JX3FIBG.js";import"./chunk-OHPYKFCM.js";export*from"@lark-base-open/base-site-channel/runtime";import{installLinkGuard as De}from"@lark-base-open/base-site-channel/runtime";function P(e={}){let t=!0,n,o=s=>{let c=h(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(!L(s,"link.open")){o(new v("link.open",1));return}n=De(e)}}).catch(s=>{t&&o(s)}),()=>{t=!1,n?.()}}export*from"@lark-base-open/base-site-channel/runtime-contract";import{SiteChatbotStreamError as Vt}from"@lark-base-open/base-site-channel/runtime";import*as u from"@lark-base-open/base-site-channel/runtime";var M=class extends u.SiteChatbotStreamAdapter{constructor(t){super({...t,channel:t.channel?x(t.channel):_})}},F=e=>({...e,channel:e?.channel?x(e.channel):_}),q=(e,t)=>u.callSiteAIFunction(e,F(t)),H=(e,t)=>u.invokeSiteAIFunctionStream(e,F(t)),z=(e,t)=>u.createSiteAIFunctionTask(e,F(t)),K=(e,t,n)=>u.getSiteAIFunctionTask(e,t,F(n));var be=new Set(["cancelled","failed","queued","running","succeeded"]);async function Ce(e){let t=await q(e);return e.input&&!e.messages?y(t):t}function xe(e){return H(e)}function r(e,t){for(let n of t){let o=e[n];if(typeof o=="string"&&o.trim())return o}}function _e(e,t){for(let n of t){let o=e[n];if(typeof o=="number"&&Number.isFinite(o))return o}}function Pe(e){let t=r(e,["capabilityType","capability_type","CapabilityType"]);return t==="image"||t==="video"?t:void 0}function Me(e){if(Array.isArray(e))return e.filter(D).map(t=>{let n=r(t,["size","Size"]),o=r(t,["token","Token"]),a=r(t,["url","URL"]);return{safetyStatus:r(t,["safetyStatus","safety_status","SafetyStatus"])??"",...n?{size:n}:{},...o?{token:o}:{},...a?{url:a}:{}}})}function Ee(e){if(!D(e))return;let t=e.durationSeconds??e.duration_seconds??e.DurationSeconds,n=r(e,["token","Token"]),o=r(e,["url","URL"]);return{...typeof t=="number"?{durationSeconds:t}:{},...n?{token:n}:{},...o?{url:o}:{}}}function T(e,t="INVALID_AI_FUNCTION_TASK"){let n=new Error(e);return n.name="SiteAIFunctionTaskError",n.code=t,n}function y(e){if(!D(e))throw T("AI Function task response has an invalid structure");let t=Oe(e);if(t)throw T(t.message,t.code);if("data"in e&&e.data!==void 0)return y(e.data);let n=r(e,["type","Type"]),o=r(e,["taskId","task_id","TaskID"]),a=e.status??e.Status;if(n!=="image_task"&&n!=="video_task"||!o||typeof a!="string"||!be.has(a))throw T("AI Function task response has an invalid structure");let s=Me(e.imageAssets??e.image_assets??e.ImageAssets),c=Ee(e.videoAsset??e.video_asset??e.VideoAsset),l=_e(e,["progress","Progress"]),A=Pe(e),I=r(e,["errCode","err_code","ErrCode"]),S=r(e,["errMessage","err_message","ErrMessage"]);return{...A?{capabilityType:A}:{},...I?{errCode:I}:{},...S?{errMessage:S}:{},...s?{imageAssets:s}:{},...l!==void 0?{progress:l}:{},...c?{videoAsset:c}:{},requestId:r(e,["requestId","request_id","RequestID"])??"",status:a,taskId:o,type:n}}function Oe(e){let t=e.code??e.Code;if(typeof t=="number"&&t!==0||typeof t=="string"&&t&&t!=="0")return{code:String(t),message:r(e,["msg","message","Message"])??"Failed to create the AI Function task"};let n=e.BaseResp??e.base_resp??e.baseResp;if(!D(n))return;let o=n.StatusCode??n.status_code??n.statusCode;if(typeof o=="number"&&o!==0||typeof o=="string"&&o&&o!=="0")return{code:String(o),message:r(n,["StatusMessage","status_message","statusMessage"])??"Failed to create the AI Function task"}}function we(e){return!!e.taskId.trim()&&(e.status==="queued"||e.status==="running")}async function ve(e){return y(await z(e))}async function Le(e,t){if(!t.trim())throw T("AI Function task ID must not be empty");return y(await K(e,t))}function D(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{Component as Ue,StrictMode as Ne,useEffect as Ge,useState as Ve}from"react";import{createRoot as qe}from"react-dom/client";import{installRouteSync as Be}from"@lark-base-open/base-site-channel/runtime";function E(e={}){return Be({...e,onDiagnostic:t=>{let n={source:"sdk",code:t.code,category:t.code==="PATH_ROUTING_UNSUPPORTED"?"protocol":"unknown",retryable:t.code==="ROUTE_SYNC_UNAVAILABLE",message:t.message,redaction:"\u539F\u59CB\u9519\u8BEF\u6D88\u606F\u548C\u4E1A\u52A1\u53C2\u6570\u5DF2\u7701\u7565"};e.onDiagnostic?e.onDiagnostic(n):console.warn("[Base Database SDK]",n.message)}})}import{Fragment as He,jsx as d,jsxs as ze}from"react/jsx-runtime";var O=new WeakSet,b=class extends Ue{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 Mt(e){let t,n,o=new Promise((i,p)=>{t=i,n=p});o.catch(()=>{});let a=!1,s=!1,c=!1,l,A=()=>{},I=()=>{},S=()=>{},C=i=>{try{e.onDiagnostic?.(h(i))}catch{}},f=i=>{C(i),!(a||s||c)&&(c=!0,n(i),e.reportLifecycle!==!1&&m.reportLoadFailed("APP_BOOT_FAILED",{appSdk:"0.
|
|
1
|
+
import{A as Ze,B as Se,C as fe,D as ge,E as Ae,F as Ie,G as ye,H as ke,I as Re,J as he,K as Fe,L as Te,M as $e,N as B,O as et,P as U,Q as tt,R as nt,S as N,T as ot,U as it,V as G,W as V,X as at,Y as rt,Z as st,_ as ct,a as J,b as X,c as Z,d as $,e as ee,f as te,g as ne,h as x,i as _,j as oe,k as ie,l as m,m as ae,n as re,o as se,p as ce,q as ue,r as de,s as me,t as le,u as pe,v as Ye,w as L,x as je,y as Je,z as Xe}from"./chunk-EG6R7YAD.js";import{a as We,b as Qe,c as v,d as h}from"./chunk-ZKBZAK4L.js";import{a as Ke}from"./chunk-3JX3FIBG.js";import"./chunk-OHPYKFCM.js";export*from"@lark-base-open/base-site-channel/runtime";import{installLinkGuard as De}from"@lark-base-open/base-site-channel/runtime";function P(e={}){let t=!0,n,o=s=>{let c=h(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(!L(s,"link.open")){o(new v("link.open",1));return}n=De(e)}}).catch(s=>{t&&o(s)}),()=>{t=!1,n?.()}}export*from"@lark-base-open/base-site-channel/runtime-contract";import{SiteChatbotStreamError as Vt}from"@lark-base-open/base-site-channel/runtime";import*as u from"@lark-base-open/base-site-channel/runtime";var M=class extends u.SiteChatbotStreamAdapter{constructor(t){super({...t,channel:t.channel?x(t.channel):_})}},F=e=>({...e,channel:e?.channel?x(e.channel):_}),q=(e,t)=>u.callSiteAIFunction(e,F(t)),H=(e,t)=>u.invokeSiteAIFunctionStream(e,F(t)),z=(e,t)=>u.createSiteAIFunctionTask(e,F(t)),K=(e,t,n)=>u.getSiteAIFunctionTask(e,t,F(n));var be=new Set(["cancelled","failed","queued","running","succeeded"]);async function Ce(e){let t=await q(e);return e.input&&!e.messages?y(t):t}function xe(e){return H(e)}function r(e,t){for(let n of t){let o=e[n];if(typeof o=="string"&&o.trim())return o}}function _e(e,t){for(let n of t){let o=e[n];if(typeof o=="number"&&Number.isFinite(o))return o}}function Pe(e){let t=r(e,["capabilityType","capability_type","CapabilityType"]);return t==="image"||t==="video"?t:void 0}function Me(e){if(Array.isArray(e))return e.filter(D).map(t=>{let n=r(t,["size","Size"]),o=r(t,["token","Token"]),a=r(t,["url","URL"]);return{safetyStatus:r(t,["safetyStatus","safety_status","SafetyStatus"])??"",...n?{size:n}:{},...o?{token:o}:{},...a?{url:a}:{}}})}function Ee(e){if(!D(e))return;let t=e.durationSeconds??e.duration_seconds??e.DurationSeconds,n=r(e,["token","Token"]),o=r(e,["url","URL"]);return{...typeof t=="number"?{durationSeconds:t}:{},...n?{token:n}:{},...o?{url:o}:{}}}function T(e,t="INVALID_AI_FUNCTION_TASK"){let n=new Error(e);return n.name="SiteAIFunctionTaskError",n.code=t,n}function y(e){if(!D(e))throw T("AI Function task response has an invalid structure");let t=Oe(e);if(t)throw T(t.message,t.code);if("data"in e&&e.data!==void 0)return y(e.data);let n=r(e,["type","Type"]),o=r(e,["taskId","task_id","TaskID"]),a=e.status??e.Status;if(n!=="image_task"&&n!=="video_task"||!o||typeof a!="string"||!be.has(a))throw T("AI Function task response has an invalid structure");let s=Me(e.imageAssets??e.image_assets??e.ImageAssets),c=Ee(e.videoAsset??e.video_asset??e.VideoAsset),l=_e(e,["progress","Progress"]),A=Pe(e),I=r(e,["errCode","err_code","ErrCode"]),S=r(e,["errMessage","err_message","ErrMessage"]);return{...A?{capabilityType:A}:{},...I?{errCode:I}:{},...S?{errMessage:S}:{},...s?{imageAssets:s}:{},...l!==void 0?{progress:l}:{},...c?{videoAsset:c}:{},requestId:r(e,["requestId","request_id","RequestID"])??"",status:a,taskId:o,type:n}}function Oe(e){let t=e.code??e.Code;if(typeof t=="number"&&t!==0||typeof t=="string"&&t&&t!=="0")return{code:String(t),message:r(e,["msg","message","Message"])??"Failed to create the AI Function task"};let n=e.BaseResp??e.base_resp??e.baseResp;if(!D(n))return;let o=n.StatusCode??n.status_code??n.statusCode;if(typeof o=="number"&&o!==0||typeof o=="string"&&o&&o!=="0")return{code:String(o),message:r(n,["StatusMessage","status_message","statusMessage"])??"Failed to create the AI Function task"}}function we(e){return!!e.taskId.trim()&&(e.status==="queued"||e.status==="running")}async function ve(e){return y(await z(e))}async function Le(e,t){if(!t.trim())throw T("AI Function task ID must not be empty");return y(await K(e,t))}function D(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{Component as Ue,StrictMode as Ne,useEffect as Ge,useState as Ve}from"react";import{createRoot as qe}from"react-dom/client";import{installRouteSync as Be}from"@lark-base-open/base-site-channel/runtime";function E(e={}){return Be({...e,onDiagnostic:t=>{let n={source:"sdk",code:t.code,category:t.code==="PATH_ROUTING_UNSUPPORTED"?"protocol":"unknown",retryable:t.code==="ROUTE_SYNC_UNAVAILABLE",message:t.message,redaction:"\u539F\u59CB\u9519\u8BEF\u6D88\u606F\u548C\u4E1A\u52A1\u53C2\u6570\u5DF2\u7701\u7565"};e.onDiagnostic?e.onDiagnostic(n):console.warn("[Base Database SDK]",n.message)}})}import{Fragment as He,jsx as d,jsxs as ze}from"react/jsx-runtime";var O=new WeakSet,b=class extends Ue{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 Mt(e){let t,n,o=new Promise((i,p)=>{t=i,n=p});o.catch(()=>{});let a=!1,s=!1,c=!1,l,A=()=>{},I=()=>{},S=()=>{},C=i=>{try{e.onDiagnostic?.(h(i))}catch{}},f=i=>{C(i),!(a||s||c)&&(c=!0,n(i),e.reportLifecycle!==!1&&m.reportLoadFailed("APP_BOOT_FAILED",{appSdk:"0.6.0-durable.1"}).catch(C))},g;try{g=typeof e.root=="string"?document.querySelector(e.root):e.root??document.querySelector("#root")}catch(i){return f(i),{ready:o,dispose(){a=!0}}}if(!g)return f(new Error("APP_ROOT_NOT_FOUND")),{ready:o,dispose(){a=!0}};if(O.has(g))throw new Error("APP_ALREADY_STARTED");O.add(g);let W=()=>{a||(a=!0,A(),I(),S(),l?.unmount(),O.delete(g),G.clear(),!s&&!c&&n(new Error("APP_DISPOSED")))},Q=()=>{queueMicrotask(()=>{a||c||s||(s=!0,e.reportLifecycle===!1?t():m.ready({appSdk:"0.6.0-durable.1"}).then(t,i=>{C(i),n(i)}))})};function Y({locale:i,theme:p}){let[k,R]=Ve();Ge(()=>(S=m.subscribeModeChanged(R),Q(),()=>S()),[]);let j=e.app,w=ze(He,{children:[d(j,{}),e.platformUI===!1?null:d(V,{})]});return d(N,{runtime:m,theme:p,styleScope:e.styleScope,locale:i,mode:k,onDiagnostic:e.onDiagnostic,children:e.providers?e.providers(w):w})}try{l=qe(g);let i=e.slots?.loading;i&&l.render(d(b,{failed:f,fallback:e.slots?.error,children:d(i,{})})),m.getRuntimeContext().then(p=>{if(a||c)return;let k=e.locale&&e.locale!=="host"?e.locale:B(p.locale,"en");document.documentElement.lang=U(k),e.linkGuard!==!1&&(A=P({onDiagnostic:e.onDiagnostic})),e.routeSync!==!1&&(I=E({context:p,onDiagnostic:e.onDiagnostic}));let R=d(b,{failed:f,fallback:e.slots?.error,children:d(Y,{locale:k,theme:e.theme&&e.theme!=="host"?e.theme:p.colorScheme==="dark"?"dark":"light"})});l.render(e.strictMode===!1?R:d(Ne,{children:R}))}).catch(f)}catch(i){f(i)}return{ready:o,dispose:W}}export{ct as AttachmentImage,N as BaseAppProvider,We as CAPABILITY_CATALOG,v as CapabilityUnavailableError,ke as DataNotReadyError,at as DatabaseUserMenu,Qe as DiagnosticCode,V as FloatingButton,Ke as SDKError,J as SITE_RUNTIME_PROTOCOL_VERSION,M as SiteChatbotStreamAdapter,Vt as SiteChatbotStreamError,X as SiteRuntimeApi,oe as SiteRuntimeClient,ee as SiteRuntimeErrorCode,Z as SiteRuntimeEvent,$ as SiteRuntimeFunction,$e as UiLanguageContext,st as UserSelectorEditor,rt as UserSelectorPanel,Te as buildAttachmentCoverUrl,ye as buildDatabaseInvokeFunctionPath,Ie as buildDatabaseInvokeGetPath,Ce as callSiteAIFunction,h as classifyRuntimeError,ve as createSiteAIFunctionTask,ie as createSiteRuntimeClient,le as createSiteRuntimeFetch,pe as fetch,ge as fetchAttachmentCover,Ae as fetchAttachmentDownloadUrl,je as getCapabilities,se as getCurrentUser,Se as getDatabaseContext,Je as getRuntimeCapabilities,Le as getSiteAIFunctionTask,et as getUiLanguage,U as getUiLocale,L as hasCapability,we as hasRunnableMediaTask,tt as initializeUiLanguage,P as installLinkGuard,E as installRouteSync,re as invokeApi,Re as invokeDatabaseFunction,he as invokeDatabaseMutationBatch,ae as invokeHttp,xe as invokeSiteAIFunctionStream,ne as isValidSiteFunctionName,ce as logout,y as normalizeSiteAIMediaTask,Fe as openAttachmentDownload,me as openLink,Xe as queryCapability,Ye as readCapabilities,te as readSiteAITextDelta,ue as requestEdit,Ze as requireCapability,fe as resolveDatabaseContext,B as selectUiLanguage,m as siteRuntime,Mt as startBaseApp,de as uploadAttachment,ot as useBaseApp,it as useOptionalBaseApp,nt as useUiLanguage};
|
package/docs/codegen.md
CHANGED
|
@@ -28,3 +28,5 @@ export const files = await generateFunctionClients(data);
|
|
|
28
28
|
直接调用要求输入、输出映射都包含该 Function ID;缺失输出映射不能退回到调用方自行指定泛型。Mutation 标记仅根据真实 `functionType=5` 生成,不能按输出结构判断。批量 helper 的 ID 必须同时存在于 Mutation 标记、输入和输出映射中,每组参数与结果均按 ID 推断;无输出 Schema 时结果为 `DatabaseMutationResult`,有 Schema 时保留精确类型。ID 与参数必须保持关联,不能用任意字符串或返回泛型回退;页面仍须检查顶层业务码、缺失记录和忽略字段。FaaS 未声明输出 Schema 时映射值为 `unknown`,页面须先校验或显式断言 `data` 的业务结构。0.2.0 的直接调用与 0.3.0 的批量调用分别收紧了公开类型契约;升级后重新生成契约并按 [迁移指南](upgrade.md) 修改调用处。
|
|
29
29
|
|
|
30
30
|
生成完成后运行 `base-database-cli check --json` 检查契约与生成文件是否一致。
|
|
31
|
+
|
|
32
|
+
Durable Function 使用 `functionType=6`,`functions` 和 `inputs` 均可保留该类型。`inputSchema` 是任务控制命令的 Schema(例如 `action: start`、`input` 和 `idempotencyKey`),不直接用 Workflow 的业务输入替代。生成的客户端沿用 Function 调用入口;有输出 Schema 时保留其类型,没有时为 `unknown`。Durable 不生成 Mutation 标记,也不能通过 Mutation 批量接口调用。
|
package/docs/durable.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# Base Site Durable SDK
|
|
2
|
+
|
|
3
|
+
供 Base Site 的 Durable Function 源码使用。Workflow 定义执行顺序和等待,Activity 执行网络请求、站点 Function 调用等业务操作。执行由 DevCenter 管理的 Worker 承载。
|
|
4
|
+
|
|
5
|
+
Durable 是 App SDK 的两个子入口。预发布版本 0.6.0-durable.0 使用 npm 的 durable 标签。使用前需确认目标平台已部署匹配的 Durable 运行时。
|
|
6
|
+
|
|
7
|
+
## 构建与安装
|
|
8
|
+
|
|
9
|
+
安装此预发布版本:`npm install @lark-base-open/base-database-app-sdk@0.6.0-durable.0`。
|
|
10
|
+
|
|
11
|
+
本地开发 SDK 时,在 SDK 根目录执行 `npm ci`、`npm run build`、`npm pack`。构建完成类型检查、JS 编译和公开声明生成。在使用项目中通过 `npm install <tarball-path>` 安装。Temporal 是可选 peer。开发时若直接加载 Durable 模块,需要安装 `@temporalio/workflow@1.24.0` 与 `@temporalio/activity@1.24.0`;只做公开类型检查不需要加载它们。托管 Worker 负责提供匹配版本,当前固定为 1.24.0。
|
|
12
|
+
|
|
13
|
+
Durable 使用 `/durable/workflow` 和 `/durable/activity` 两个入口。Workflow API 在 Temporal Workflow 执行上下文内使用,Activity API 在托管 Worker 的 Activity 上下文内使用;普通 Node 进程中的 import 成功不代表任务可以执行。
|
|
14
|
+
|
|
15
|
+
## 编排与步骤
|
|
16
|
+
|
|
17
|
+
`workflow.ts`:
|
|
18
|
+
|
|
19
|
+
<!-- example: durable-workflow.ts -->
|
|
20
|
+
```ts
|
|
21
|
+
import { callStep, reportProgress, sleep } from '@lark-base-open/base-database-app-sdk/durable/workflow';
|
|
22
|
+
|
|
23
|
+
export default async function task(input: { value: number }) {
|
|
24
|
+
const result = await callStep<number>('double', input, { key: 'double-input' });
|
|
25
|
+
reportProgress({ processed: 1, total: 1 });
|
|
26
|
+
await sleep(1000);
|
|
27
|
+
return result;
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
`activities.ts`:
|
|
32
|
+
|
|
33
|
+
<!-- example: durable-activities.ts -->
|
|
34
|
+
```ts
|
|
35
|
+
export async function double(input: { value: number }): Promise<number> {
|
|
36
|
+
return input.value * 2;
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
在对应 Function 的 `meta.json` 中声明 `double` Activity 的 timeout 和 retry.maximumAttempts。输入 Schema、发布方式和任务调用接口由 Site/DevCenter 契约管理。
|
|
41
|
+
|
|
42
|
+
`callStep` 的 key 在同一次 Workflow 中必须唯一;等待使用 SDK 的 `sleep` 或 `waitForEvent`,外部 I/O 放入 Activity。暂停在 SDK 边界生效,不中断已经开始执行的 Activity。
|
|
43
|
+
|
|
44
|
+
## 站点能力
|
|
45
|
+
|
|
46
|
+
Activity 通过 `invokeFunction(functionId, input, { key })` 调用同一站点的普通 Function,input 与普通调用请求体一致,例如 `{ params: { city: '北京' } }`。key 表示同一个业务调用,Activity 重试时保持不变。平台注入调用通道和执行凭证,业务源码不传 token。
|
|
47
|
+
|
|
48
|
+
请求结果未知时 Activity 可能重试。稳定 key 不等于业务端已经去重,写操作仍须由 Function 实现幂等处理。
|
|
49
|
+
|
|
50
|
+
## 类型维护
|
|
51
|
+
|
|
52
|
+
公开声明由 TypeScript 源码生成,内部启动器接口不出现在公开声明中。修改源码后执行 `npm run build`。平台私有传输实现不进入 SDK tarball。
|
|
53
|
+
|
|
54
|
+
SDK 的构建、声明与打包测试由本目录独立维护。执行端消费本包的 tarball;平台凭证传输和 Worker 管理不进入此包。
|
package/docs/exports.md
CHANGED
|
@@ -43,3 +43,15 @@
|
|
|
43
43
|
值:`CodegenError`、`SUPPORTED_CONTRACT_FORMAT_VERSIONS`、`generateFunctionClients`、`validateContractData`。
|
|
44
44
|
|
|
45
45
|
类型与值完整清单:`ClientContract`、`CodegenError`、`FunctionContractData`、`FunctionInputContract`、`GeneratedFile`、`SUPPORTED_CONTRACT_FORMAT_VERSIONS`、`generateFunctionClients`、`validateContractData`。
|
|
46
|
+
|
|
47
|
+
## durable/workflow
|
|
48
|
+
|
|
49
|
+
值:`callStep`、`reportProgress`、`sleep`、`waitForEvent`。
|
|
50
|
+
|
|
51
|
+
类型与值完整清单:`callStep`、`reportProgress`、`sleep`、`waitForEvent`。
|
|
52
|
+
|
|
53
|
+
## durable/activity
|
|
54
|
+
|
|
55
|
+
值:`cancellationSignal`、`getAttempt`、`invokeFunction`。
|
|
56
|
+
|
|
57
|
+
类型与值完整清单:`cancellationSignal`、`getAttempt`、`invokeFunction`。
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { callStep, reportProgress, sleep } from '@lark-base-open/base-database-app-sdk/durable/workflow';
|
|
2
|
+
|
|
3
|
+
export default async function task(input: { value: number }) {
|
|
4
|
+
const result = await callStep<number>('double', input, { key: 'double-input' });
|
|
5
|
+
reportProgress({ processed: 1, total: 1 });
|
|
6
|
+
await sleep(1000);
|
|
7
|
+
return result;
|
|
8
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lark-base-open/base-database-app-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0-durable.1",
|
|
4
4
|
"description": "Base Database 页面与服务端 SDK、平台组件及测试工具",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": [
|
|
@@ -54,6 +54,26 @@
|
|
|
54
54
|
"types": "./dist/codegen.d.cts",
|
|
55
55
|
"default": "./dist/codegen.cjs"
|
|
56
56
|
}
|
|
57
|
+
},
|
|
58
|
+
"./durable/workflow": {
|
|
59
|
+
"import": {
|
|
60
|
+
"types": "./dist/durable/workflow.d.cts",
|
|
61
|
+
"default": "./dist/durable/workflow.cjs"
|
|
62
|
+
},
|
|
63
|
+
"require": {
|
|
64
|
+
"types": "./dist/durable/workflow.d.cts",
|
|
65
|
+
"default": "./dist/durable/workflow.cjs"
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
"./durable/activity": {
|
|
69
|
+
"import": {
|
|
70
|
+
"types": "./dist/durable/activity.d.cts",
|
|
71
|
+
"default": "./dist/durable/activity.cjs"
|
|
72
|
+
},
|
|
73
|
+
"require": {
|
|
74
|
+
"types": "./dist/durable/activity.d.cts",
|
|
75
|
+
"default": "./dist/durable/activity.cjs"
|
|
76
|
+
}
|
|
57
77
|
}
|
|
58
78
|
},
|
|
59
79
|
"files": [
|
|
@@ -77,11 +97,19 @@
|
|
|
77
97
|
"@tanstack/react-query": "5.104.1",
|
|
78
98
|
"msw": "2.11.6",
|
|
79
99
|
"react": "^19.2.0",
|
|
80
|
-
"react-dom": "^19.2.0"
|
|
100
|
+
"react-dom": "^19.2.0",
|
|
101
|
+
"@temporalio/activity": "1.24.0",
|
|
102
|
+
"@temporalio/workflow": "1.24.0"
|
|
81
103
|
},
|
|
82
104
|
"peerDependenciesMeta": {
|
|
83
105
|
"msw": {
|
|
84
106
|
"optional": true
|
|
107
|
+
},
|
|
108
|
+
"@temporalio/activity": {
|
|
109
|
+
"optional": true
|
|
110
|
+
},
|
|
111
|
+
"@temporalio/workflow": {
|
|
112
|
+
"optional": true
|
|
85
113
|
}
|
|
86
114
|
},
|
|
87
115
|
"typesVersions": {
|
|
@@ -94,6 +122,12 @@
|
|
|
94
122
|
],
|
|
95
123
|
"codegen": [
|
|
96
124
|
"dist/codegen.d.cts"
|
|
125
|
+
],
|
|
126
|
+
"durable/workflow": [
|
|
127
|
+
"dist/durable/workflow.d.ts"
|
|
128
|
+
],
|
|
129
|
+
"durable/activity": [
|
|
130
|
+
"dist/durable/activity.d.ts"
|
|
97
131
|
]
|
|
98
132
|
}
|
|
99
133
|
}
|