@lark-base-open/base-database-app-sdk 0.6.0-durable.1 → 0.6.0-durable.2
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 +2 -19
- package/README.md +3 -5
- 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/page.js +1 -1
- package/dist/server.cjs +1 -1
- package/dist/server.d.cts +135 -1
- package/dist/server.d.ts +135 -1
- package/dist/server.js +1 -1
- package/docs/codegen.md +1 -1
- package/docs/durable.md +35 -42
- package/docs/exports.md +2 -14
- package/examples/durable.ts +23 -0
- package/package.json +2 -36
- package/dist/durable/activity.cjs +0 -25
- package/dist/durable/activity.d.cts +0 -6
- package/dist/durable/activity.d.ts +0 -6
- package/dist/durable/workflow.cjs +0 -107
- package/dist/durable/workflow.d.cts +0 -15
- package/dist/durable/workflow.d.ts +0 -15
- package/examples/durable-activities.ts +0 -3
- package/examples/durable-workflow.ts +0 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,21 +1,10 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
## [0.6.0-durable.
|
|
4
|
-
|
|
5
|
-
### Fixed
|
|
6
|
-
|
|
7
|
-
- 修复 Durable Function 契约生成失败,codegen 直接接受 `functionType: 6` 并保留控制命令参数与输出类型。
|
|
8
|
-
|
|
9
|
-
## [0.6.0-durable.0] - 2026-11-03
|
|
3
|
+
## [0.6.0-durable.2] - 2026-11-05
|
|
10
4
|
|
|
11
5
|
### Added
|
|
12
6
|
|
|
13
|
-
-
|
|
14
|
-
- 提供 Durable 使用文档和可编译的 Workflow/Activity 示例。
|
|
15
|
-
|
|
16
|
-
### Compatibility
|
|
17
|
-
|
|
18
|
-
- Durable 入口需要平台提供匹配的托管运行时;Temporal 1.24.0 作为可选 peer 依赖提供。
|
|
7
|
+
- 支持 Durable Function。
|
|
19
8
|
|
|
20
9
|
## 0.5.2 - 2026-10-30
|
|
21
10
|
|
|
@@ -45,12 +34,6 @@
|
|
|
45
34
|
- 页面启动时向平台报告所用的 SDK 版本,便于排查问题。
|
|
46
35
|
- 页面出现未处理的错误时,错误信息会上报给平台;内容会截断,并去掉链接里的参数。
|
|
47
36
|
|
|
48
|
-
## [0.5.0-durable.0] - 2026-10-26
|
|
49
|
-
|
|
50
|
-
### Added
|
|
51
|
-
|
|
52
|
-
- 新增 Durable Workflow 与 Activity 入口,支持持久化步骤、等待、进度和站点 Function 调用。
|
|
53
|
-
|
|
54
37
|
## 0.4.2 - 2026-10-26
|
|
55
38
|
|
|
56
39
|
### 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.6.0-durable.
|
|
5
|
+
安装:`npm install @lark-base-open/base-database-app-sdk@0.6.0-durable.2`。从旧版本升级前请阅读 [变更记录](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
|
|
|
@@ -34,8 +34,6 @@ SDK 文档说明本版本 API、组件、兼容语义与可编译示例。业务
|
|
|
34
34
|
|
|
35
35
|
新建工程可显式开启 `styleScope: 'components'` 隔离业务样式;主题和迁移契约见 [启动说明](docs/start-base-app.md)。
|
|
36
36
|
|
|
37
|
-
## Durable Function
|
|
37
|
+
## Durable Function(开发分支)
|
|
38
38
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
使用前需确认平台部署了匹配的 Durable 运行时;Temporal 为可选 peer,仅 Durable 开发和执行环境安装匹配版本,普通页面和普通 Function 不依赖它。ESM import 与 CJS require 共享 Durable 模块。
|
|
39
|
+
`/server` 提供 `defineDurableFunction`、`durable` 和错误类型,见 [Durable 文档](docs/durable.md)。本分支接口尚未发布,本地联调使用构建后的 tarball。长时任务在站点 Function 内执行,由平台逐步推进,不需要安装额外执行引擎依赖。
|
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
|
|
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)}
|
|
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;
|
|
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;
|
|
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
|
|
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)}
|
|
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};
|
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.6.0-durable.
|
|
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.2"}).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.2"}).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/dist/server.cjs
CHANGED
|
@@ -1 +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 r of L(s))!W.call(t,r)&&r!==o&&k(t,r,{get:()=>s[r],enumerable:!(e=U(s,r))||e.enumerable});return t};var z=t=>V(k({},"__esModule",{value:!0}),t);var v={};J(v,{SDKError:()=>f,bindFunctionRuntime:()=>j,createServerContext:()=>_,defineFunction:()=>K,normalizeRecordsResult:()=>x});module.exports=z(v);var F=Symbol.for("@lark-base-open/base-database-app-sdk/SDKError/v1"),f=class extends Error{constructor(o,e,r,n){super(e);this.code=o;this.name="SDKError",this.safeMessage=e;let c=typeof r=="object"?r:{};this.upstreamCode=typeof r=="string"?r: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??n??!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),R=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((r,n)=>r!==String(n))))throw 0;s.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;o(n.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(R)&&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,r=e.ignored_fields??[];if(!Array.isArray(r)||!r.every(a=>d(a)&&["id","name","reason"].every(i=>typeof a[i]=="string")))return o();let n=e.record_not_found??[];if(!D(n))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(!R(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),n.some(a=>!c.includes(a)||u.includes(a))||!r.length&&c.some(a=>!u.includes(a)&&!n.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)||n.includes(i))||n.some(i=>!c.includes(i))||a.length+n.length!==c.length)return o();u=a}else{if(a.length!==c.length||a.some((i,p)=>i!==c[p])||n.some(i=>!c.includes(i)))return o();u=a.filter(i=>!n.includes(i))}}let l=y===void 0?{}:{attachments:y};return n.length||r.length?{status:"partial",appliedIds:u,notFoundIds:n,ignoredFields:r,...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,r,n,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(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(S(n),e==="create"){if(!Array.isArray(n)||!n.every(d))throw 0;a=n.length,y={create_records:n}}else if(e==="update"){if(!d(n)||!Object.values(n).every(d))throw 0;l=Object.keys(n),a=l.length,y={update_records:n}}else if(e==="delete"){if(!Array.isArray(n)||!n.every(R))throw 0;l=n,a=n.length,y={record_id_list:n}}else{if(!d(n))throw 0;let i=Object.create(null),p=0;for(let[m,g]of Object.entries(n)){if(!R(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(b=>!["file_token",...e==="appendAttachments"?["image_width","image_height"]:[]].includes(b)))throw 0;for(let b of["image_width","image_height"])if(h[b]!==void 0&&(typeof h[b]!="number"||!Number.isInteger(h[b])||h[b]<=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(R)||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(r.baseToken)}/tables/${encodeURIComponent(r.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,(r,n,c)=>o(e,r,n,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,r){let n=Object.defineProperty({...r},P,{value:o});return t.call(this,e,n)}}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 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 f(`SDK_${o}_INVALID`,o==="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(s,o)=>{try{let e=await N(t.input,s,"INPUT"),r=await t.handler(e,_(o)),n=await N(t.output,r,"OUTPUT");return S(n),{code:0,msg:"success",data:n}}catch(e){let r=e instanceof f?e:new f("SDK_HANDLER_FAILED","\u51FD\u6570\u6267\u884C\u5931\u8D25");console.error(JSON.stringify({source:"sdk",code:r.code,paths:r.paths,retryable:r.retryable,outcome:r.outcome}));let n={code:r.wireCode,msg:r.safeMessage};return e instanceof f||Object.defineProperty(n,Symbol.for("base-site.function-error"),{value:e}),n}}}0&&(module.exports={SDKError,bindFunctionRuntime,createServerContext,defineFunction,normalizeRecordsResult});
|
|
1
|
+
"use strict";var W=Object.defineProperty;var pe=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var fe=Object.prototype.hasOwnProperty;var me=(e,n)=>{for(var r in n)W(e,r,{get:n[r],enumerable:!0})},ge=(e,n,r,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of de(n))!fe.call(e,o)&&o!==r&&W(e,o,{get:()=>n[o],enumerable:!(t=pe(n,o))||t.enumerable});return e};var ye=e=>ge(W({},"__esModule",{value:!0}),e);var De={};me(De,{DurableError:()=>E,NonRetryableError:()=>N,SDKError:()=>R,StepFailedError:()=>P,bindFunctionRuntime:()=>ee,createServerContext:()=>C,defineDurableFunction:()=>ae,defineFunction:()=>re,durable:()=>ue,normalizeRecordsResult:()=>V});module.exports=ye(De);var G=Symbol.for("@lark-base-open/base-database-app-sdk/SDKError/v1"),R=class extends Error{constructor(r,t,o,s){super(t);this.code=r;this.name="SDKError",this.safeMessage=t;let c=typeof o=="object"?o:{};this.upstreamCode=typeof o=="string"?o:void 0,this.wireCode=Number.isSafeInteger(c.wireCode)&&c.wireCode!==0?c.wireCode:r==="SDK_TIMEOUT"?504:r==="SDK_CANCELLED"?499:r==="SDK_INPUT_INVALID"?400:500,this.retryable=c.retryable??s??!1,this.outcome=c.outcome??"failed",this.paths=c.paths??[]}[G]=!0;static[Symbol.hasInstance](r){return this!==R?Function.prototype[Symbol.hasInstance].call(this,r):r!==null&&typeof r=="object"&&r[G]===!0}wireCode;safeMessage;retryable;outcome;paths;upstreamCode};var x=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_=e=>typeof e=="string"&&/^rec[A-Za-z0-9]{1,32}$/.test(e);function k(e){let n=new Set,r=t=>{if(!(t===null||typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))){if(typeof t!="object"||!t||n.has(t)||Array.isArray(t)&&Object.getPrototypeOf(t)!==Array.prototype||!Array.isArray(t)&&Object.getPrototypeOf(t)!==Object.prototype&&Object.getPrototypeOf(t)!==null||Array.isArray(t)&&(Object.keys(t).length!==t.length||Object.keys(t).some((o,s)=>o!==String(s))))throw 0;n.add(t);for(let o of Reflect.ownKeys(t)){if(Array.isArray(t)&&o==="length")continue;if(typeof o!="string")throw 0;let s=Object.getOwnPropertyDescriptor(t,o);if(!s.enumerable||!("value"in s))throw 0;r(s.value)}n.delete(t)}};try{r(e)}catch{throw new R("SDK_OUTPUT_NOT_JSON","\u8F93\u51FA\u5FC5\u987B\u662F\u65E0\u635F JSON \u503C")}}function M(e,n,r){return{status:"unknown",code:e,retryable:!1,...n?{requestedIds:[...n]}:{},...r?{logid:r}:{}}}var be=e=>typeof e=="number"&&[401,403,404,91403,1254302,1254043,1254044].includes(e),z=e=>({status:"failed",code:"SDK_RECORDS_REJECTED",upstreamCode:e,retryable:!1,appliedIds:[]}),Z=e=>Array.isArray(e)&&e.every(_)&&new Set(e).size===e.length;function V(e,n){let r=()=>M("SDK_RECORDS_RESULT_UNKNOWN",n.requestedIds);if(x(e)&&be(e.code))return z(e.code);if(!x(e)||e.code!==0||!x(e.data))return r();let t=e.data,o=t.ignored_fields??[];if(!Array.isArray(o)||!o.every(a=>x(a)&&["id","name","reason"].every(u=>typeof a[u]=="string")))return r();let s=t.record_not_found??[];if(!Z(s))return r();let c=n.requestedIds??[],d,w;if(n.operation==="appendAttachments"||n.operation==="removeAttachments"){if(!x(t.attachments))return r();try{k(t.attachments)}catch{return r()}for(let[a,u]of Object.entries(t.attachments)){if(!_(a)||!c.includes(a)||!x(u)||!Object.keys(u).length)return r();for(let[m,g]of Object.entries(u))if(!/^fld[A-Za-z0-9]+$/.test(m)||!Array.isArray(g)||!g.every(S=>x(S)&&typeof S.file_token=="string"&&S.file_token.length>0))return r()}if(d=Object.keys(t.attachments),s.some(a=>!c.includes(a)||d.includes(a))||!o.length&&c.some(a=>!d.includes(a)&&!s.includes(a)))return r();w=t.attachments}else{if(!Z(t.record_id_list))return r();let a=t.record_id_list;if(n.operation==="create"){if(a.length!==n.count||Object.hasOwn(t,"record_not_found"))return r();d=a}else if(n.operation==="update"){if(a.some(u=>!c.includes(u)||s.includes(u))||s.some(u=>!c.includes(u))||a.length+s.length!==c.length)return r();d=a}else{if(a.length!==c.length||a.some((u,m)=>u!==c[m])||s.some(u=>!c.includes(u)))return r();d=a.filter(u=>!s.includes(u))}}let p=w===void 0?{}:{attachments:w};return s.length||o.length?{status:"partial",appliedIds:d,notFoundIds:s,ignoredFields:o,...p}:{status:"success",appliedIds:d,notFoundIds:[],ignoredFields:[],...p}}var Y={create:"records/batch_create",update:"records/batch_update",delete:"records/batch_delete",appendAttachments:"append_attachments",removeAttachments:"remove_attachments"},K=e=>({status:"failed",code:e,retryable:!1,appliedIds:[]});function xe(e){if(e?.platformEnv==="online")return e.brand==="feishu"?"https://open.feishu.cn":e.brand==="lark"?"https://open.larksuite.com":void 0;if(e?.brand==="feishu"){if(e.platformEnv==="pre")return"https://open.feishu-pre.cn";if(e.platformEnv==="boe")return"https://open.feishu-boe.cn"}}function X(e,n){let r=async(t,o,s,c)=>{if(!n)return K("SDK_RUNTIME_PROFILE_MISSING");let d=xe(n);if(!d)return K("SDK_RUNTIME_PROFILE_UNSUPPORTED");if(c?.signal?.aborted)return K("SDK_CANCELLED");let w,p,a;try{if(!x(o)||typeof o.baseToken!="string"||typeof o.tableId!="string"||!/^[A-Za-z0-9]+$/.test(o.baseToken)||!/^tbl[A-Za-z0-9]+$/.test(o.tableId))throw 0;if(k(s),t==="create"){if(!Array.isArray(s)||!s.every(x))throw 0;a=s.length,w={create_records:s}}else if(t==="update"){if(!x(s)||!Object.values(s).every(x))throw 0;p=Object.keys(s),a=p.length,w={update_records:s}}else if(t==="delete"){if(!Array.isArray(s)||!s.every(_))throw 0;p=s,a=s.length,w={record_id_list:s}}else{if(!x(s))throw 0;let u=Object.create(null),m=0;for(let[g,S]of Object.entries(s)){if(!_(g)||!x(S))throw 0;for(let[I,f]of Object.entries(S)){if(!I.trim()||!Array.isArray(f))throw 0;for(let h of f){if(!x(h)||typeof h.file_token!="string"||!h.file_token.trim()||Object.keys(h).some(D=>!["file_token",...t==="appendAttachments"?["image_width","image_height"]:[]].includes(D)))throw 0;for(let D of["image_width","image_height"])if(h[D]!==void 0&&(typeof h[D]!="number"||!Number.isInteger(h[D])||h[D]<=0))throw 0}m+=f.length,f.length&&(u[g]??=Object.create(null),u[g][I]=f)}}if(m>50)throw 0;if(!m)return{status:"success",appliedIds:[],notFoundIds:[],ignoredFields:[],noop:!0};p=Object.keys(u),w={attachments:u}}if(a!==void 0&&(a<1||a>200)||p&&(!p.every(_)||new Set(p).size!==p.length))throw 0}catch{return K("SDK_RECORDS_INPUT_INVALID")}try{let u=await e.fetch(`${d}/open-apis/bitable/v1/apps/${encodeURIComponent(o.baseToken)}/tables/${encodeURIComponent(o.tableId)}/${Y[t]}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(w),signal:c?.signal}),m=u.headers.get("x-tt-logid")??void 0;if([401,403,404].includes(u.status))return z(u.status);if(!u.ok)return M("SDK_RECORDS_HTTP_ERROR",p,m);let g=V(await u.json(),{operation:t,requestedIds:p,count:a});return g.status==="unknown"&&m?{...g,logid:m}:g}catch(u){let m=u instanceof Error?u.name:"";return M(m==="AbortError"?"SDK_CANCELLED":m==="TimeoutError"?"SDK_TIMEOUT":"SDK_RECORDS_RESULT_UNKNOWN",p)}};return Object.fromEntries(Object.keys(Y).map(t=>[t,(o,s,c)=>r(t,o,s,c)]))}var Q=Symbol("base-database-runtime-profile");function ee(e,n){let r=Object.freeze({platformEnv:n.platformEnv,brand:n.brand});return function(t,o){let s=Object.defineProperty({...o},Q,{value:r});return e.call(this,t,s)}}function C(e){return{...e,records:X(e,e[Q])}}async function te(e,n,r){let t;try{t=await e["~standard"].validate(n)}catch{throw new R("SDK_VALIDATOR_FAILED","Schema \u6821\u9A8C\u5668\u6267\u884C\u5931\u8D25")}if(t.issues){let o=t.issues.map(s=>(s.path??[]).map(c=>{let d=typeof c=="object"?c.key:c;return typeof d=="number"||typeof d=="string"?d:"[symbol]"}));throw new R(`SDK_${r}_INVALID`,r==="INPUT"?"\u8F93\u5165\u4E0D\u7B26\u5408\u5951\u7EA6":"\u8F93\u51FA\u4E0D\u7B26\u5408\u5951\u7EA6",{paths:o})}return t.value}function re(e){return async(n,r)=>{try{let t=await te(e.input,n,"INPUT"),o=await e.handler(t,C(r)),s=await te(e.output,o,"OUTPUT");return k(s),{code:0,msg:"success",data:s}}catch(t){let o=t instanceof R?t:new R("SDK_HANDLER_FAILED","\u51FD\u6570\u6267\u884C\u5931\u8D25");console.error(JSON.stringify({source:"sdk",code:o.code,paths:o.paths,retryable:o.retryable,outcome:o.outcome}));let s={code:o.wireCode,msg:o.safeMessage};return t instanceof R||Object.defineProperty(s,Symbol.for("base-site.function-error"),{value:t}),s}}}var ne="base-site.durable",oe="base-site.runtime";var E=class extends Error{constructor(r,t=r){super(t);this.reason=r;this.name="DurableError"}},N=class extends Error{constructor(n){super(n),this.name="NonRetryableError"}},P=class extends Error{constructor(r,t){super(t.message);this.key=r;this.error=t;this.name="StepFailedError"}};function j(e,n,r){let t="Unknown error",o="Error";try{e instanceof Error?(typeof e.message=="string"&&(t=e.message),typeof e.name=="string"&&(o=e.name)):typeof e=="string"&&(t=e)}catch{}t=t.slice(0,1024*4).replace(/([?&][^=&#\s]*?(?:token|ticket|code|secret|key|password|authorization)[^=&#\s]*=)[^&#\s]*/gi,"$1[REDACTED]").replace(/\bBearer\s+[^\s"'<>]+/gi,"Bearer [REDACTED]").replace(/[A-Za-z0-9_]{32,}/g,"[REDACTED]");let s="",c=0;for(let d of t){if(c+=new TextEncoder().encode(d).length,c>1024)break;s+=d}return{name:o,message:s,...n?{code:n}:{},...r?{key:r}:{},...e instanceof N?{retryable:!1}:{}}}function q(e){let n={ms:1,s:1e3,m:6e4,h:36e5,d:864e5},r=typeof e=="string"&&/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/.exec(e),t=typeof e=="number"?e:r?Number(r[1])*n[r[2]]:NaN;if(!Number.isSafeInteger(t)||t<0)throw new Error("Invalid duration");return t}function $(e){return k(e),e}function H(e){return new TextEncoder().encode(JSON.stringify(e)).length}var T=()=>new Promise(()=>{});function ae(e){let n={v:1,async execute(r,t){try{return await Ee(e,r,t)}catch(o){return{v:1,seq:r?.invocation?.seq??0,op:"fail",error:j(o,"HANDLER_ERROR")}}}};return{[Symbol.for(ne)]:n}}function Ee(e,n,r){return new Promise(t=>{let o={v:1,seq:n.invocation.seq},s=new Set,c=new Map(n.steps.map(i=>[i.key,i])),d,w=!1,p=!1,a,u,m,g,S=Math.min(r.deadline,n.invocation.deadline),I=i=>{p||((!a||i.op==="fail")&&(a=i),queueMicrotask(()=>{p||!a||(p=!0,clearTimeout(D),clearTimeout(m),r.signal.removeEventListener("abort",h),u?.abort(),t({...a,...d!==void 0?{progress:d}:{}}))}))},f=(i,y,l=new Error(i))=>I({...o,op:"fail",error:j(l,i,y)}),h=()=>g?g():f("REPLAY_TIMEOUT"),D=setTimeout(h,Math.max(0,S-Date.now())),J=(i,y)=>{if(p||a?.op==="fail")return;if(Date.now()>=S){h();return}if(typeof i!="string"||i.length<1||i.length>128||/[\x00-\x1f\x7f-\x9f]/.test(i)){f("DEFINITION_INVALID",void 0,new Error("Invalid step key"));return}if(s.has(i)){f("DUPLICATE_STEP_KEY",i);return}s.add(i);let l=c.get(i);if(l){if(l.kind!==y){f("DEFINITION_KIND_MISMATCH",i);return}if(!l.ok)throw new P(i,l.error);return{fresh:!1,value:y==="sleep"?void 0:l.timedOut?null:l.value}}if(w){f("PARALLEL_STEPS",i);return}if(c.size>=100){f("STEP_LIMIT",i);return}return w=!0,{fresh:!0}},ce={async run(i,y,l={}){let b=J(i,"run");if(!b)return T();if(!b.fresh)return b.value;let O,U=l.retries??3;try{if(O=l.timeout===void 0?S-Date.now():Math.min(q(l.timeout),S-Date.now()),!Number.isSafeInteger(U)||U<0||O<=0)throw new Error("Invalid step options")}catch(A){return f("DEFINITION_INVALID",i,A),T()}u=new AbortController;let le=u.signal,v=Date.now(),B=(A,L)=>I({...o,op:"step",key:i,ok:!1,error:j(A,L,i),policy:{retries:U},durationMs:Math.max(0,Date.now()-v)});return g=()=>{B(new Error("Step exceeded its deadline"),"STEP_TIMEOUT"),u?.abort()},m=setTimeout(g,O),Promise.resolve().then(async()=>{if(!(a||p))try{let A=await y({signal:le,attempt:n.invocation.attempt});if(Date.now()>=v+O){g?.();return}let L=$(A===void 0?null:A);if(H(L)>262144){B(new N("Step result exceeds 256KB"),"STEP_RESULT_TOO_LARGE");return}I({...o,op:"step",key:i,ok:!0,value:L,durationMs:Math.max(0,Date.now()-v)})}catch(A){Date.now()>=v+O?g?.():B(A)}}),T()},async sleep(i,y){let l=J(i,"sleep");if(!l)return T();if(l.fresh){try{let b=q(y);if(b<1e3||b>2592e6)throw new Error("Sleep duration must be between 1s and 30d");I({...o,op:"sleep",key:i,durationMs:b})}catch(b){f("DEFINITION_INVALID",i,b)}return T()}},async waitForEvent(i,y,l){if(!Object.hasOwn(e.events,y))return f("EVENT_UNDECLARED",i),T();let b=J(i,"wait");if(!b)return T();if(!b.fresh)return b.value;try{let O=q(l.timeout);if(O<1e3||O>2592e6)throw new Error("Event timeout must be between 1s and 30d");I({...o,op:"wait",key:i,event:y,timeoutMs:O})}catch(O){f("DEFINITION_INVALID",i,O)}return T()},progress(i){if(!p)try{let y=$(i);H(y)<=4096?d=JSON.parse(JSON.stringify(y)):console.warn("Durable progress exceeds 4KB; discarded")}catch{f("DEFINITION_INVALID",void 0,new Error("Progress must be JSON"))}}};if(r.signal.addEventListener("abort",h,{once:!0}),r.signal.aborted||S<=Date.now()){h();return}Promise.resolve().then(async()=>{try{let i;try{let l=await e.input["~standard"].validate(n.input);if(l.issues)throw new Error("Input schema validation failed");i=l.value}catch(l){f("INPUT_INVALID",void 0,l);return}if(p||a)return;if(Date.now()>=S){f("REPLAY_TIMEOUT");return}let y=await e.handler(i,ce,C(r.ctx));if(w||p||a)return;try{let l=await e.output["~standard"].validate(y);if(l.issues)throw new Error("Output schema validation failed");if(Date.now()>=S){f("REPLAY_TIMEOUT");return}let b=$(l.value);if(H(b)>262144)throw new Error("Output exceeds 256KB");I({...o,op:"done",output:b})}catch(l){f("OUTPUT_INVALID",void 0,l)}}catch(i){f("HANDLER_ERROR",i instanceof P?i.key:void 0,i)}})})}async function F(e){let n=globalThis[Symbol.for(oe)],r=n?.v===1?n.context.getStore()?.ctx:void 0;if(!r?.faasInvoke)throw new E("DURABLE_NO_CONTEXT");try{let t=await r.faasInvoke({method:"durable",params:JSON.stringify(e)});if(!t||t.code!==0)throw new E(t?.data?.reason??"INFRA_UNAVAILABLE");return t.data}catch(t){throw t instanceof E?t:new E("INFRA_UNAVAILABLE")}}var ue={start(e,n,r){return F({...r,action:"start",functionId:e,input:n})},get(e,n){return F({...n,action:"get",runId:e})},list(e){return F({...e,action:"list"})},cancel(e,n){return F({...n,action:"cancel",runId:e})},signal(e,n,r,t){return F({...t,action:"signal",runId:e,event:n,data:r})}};0&&(module.exports={DurableError,NonRetryableError,SDKError,StepFailedError,bindFunctionRuntime,createServerContext,defineDurableFunction,defineFunction,durable,normalizeRecordsResult});
|
package/dist/server.d.cts
CHANGED
|
@@ -35,6 +35,10 @@ interface RecordsClient {
|
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
interface RawFunctionContext {
|
|
38
|
+
faasInvoke?(request: {
|
|
39
|
+
method: "durable";
|
|
40
|
+
params: string;
|
|
41
|
+
}): Promise<unknown>;
|
|
38
42
|
fetch: typeof globalThis.fetch;
|
|
39
43
|
invokeFunction(p: {
|
|
40
44
|
projectId: string;
|
|
@@ -74,6 +78,136 @@ interface RecordsResultRequest {
|
|
|
74
78
|
}
|
|
75
79
|
declare function normalizeRecordsResult(body: unknown, request: RecordsResultRequest): WriteResult;
|
|
76
80
|
|
|
81
|
+
type JSONValue = null | boolean | number | string | JSONValue[] | {
|
|
82
|
+
[key: string]: JSONValue;
|
|
83
|
+
};
|
|
84
|
+
type RunStatus = "queued" | "running" | "sleeping" | "waiting" | "completed" | "failed" | "cancelled" | (string & {});
|
|
85
|
+
type StepKind = "run" | "sleep" | "wait";
|
|
86
|
+
type Trigger = {
|
|
87
|
+
kind: "server";
|
|
88
|
+
} | {
|
|
89
|
+
kind: "timer";
|
|
90
|
+
fireId: string;
|
|
91
|
+
};
|
|
92
|
+
interface OpError {
|
|
93
|
+
name?: string;
|
|
94
|
+
message: string;
|
|
95
|
+
code?: string;
|
|
96
|
+
key?: string;
|
|
97
|
+
retryable?: boolean;
|
|
98
|
+
}
|
|
99
|
+
interface Waiting {
|
|
100
|
+
event: string;
|
|
101
|
+
until: number;
|
|
102
|
+
}
|
|
103
|
+
interface StepView {
|
|
104
|
+
key: string;
|
|
105
|
+
kind: StepKind;
|
|
106
|
+
status: string;
|
|
107
|
+
attempts: number;
|
|
108
|
+
startedAt: number;
|
|
109
|
+
endedAt?: number;
|
|
110
|
+
}
|
|
111
|
+
interface RunSummary {
|
|
112
|
+
runId: string;
|
|
113
|
+
functionId: string;
|
|
114
|
+
status: RunStatus;
|
|
115
|
+
trigger: Trigger;
|
|
116
|
+
output: JSONValue;
|
|
117
|
+
error: OpError | null;
|
|
118
|
+
progress: JSONValue;
|
|
119
|
+
waiting: Waiting | null;
|
|
120
|
+
sleepingUntil: number | null;
|
|
121
|
+
createdAt: number;
|
|
122
|
+
updatedAt: number;
|
|
123
|
+
closedAt: number | null;
|
|
124
|
+
}
|
|
125
|
+
interface Run extends RunSummary {
|
|
126
|
+
input?: JSONValue;
|
|
127
|
+
steps: StepView[];
|
|
128
|
+
}
|
|
129
|
+
interface GetParams {
|
|
130
|
+
action: "get";
|
|
131
|
+
runId: string;
|
|
132
|
+
scope?: string;
|
|
133
|
+
}
|
|
134
|
+
interface ListParams {
|
|
135
|
+
action: "list";
|
|
136
|
+
functionId?: string;
|
|
137
|
+
status?: RunStatus;
|
|
138
|
+
scope?: string;
|
|
139
|
+
pageToken?: string;
|
|
140
|
+
pageSize?: number;
|
|
141
|
+
}
|
|
142
|
+
interface StartResponse {
|
|
143
|
+
runId: string;
|
|
144
|
+
status: RunStatus;
|
|
145
|
+
deduplicated: boolean;
|
|
146
|
+
}
|
|
147
|
+
interface ListResponse {
|
|
148
|
+
runs: RunSummary[];
|
|
149
|
+
nextPageToken: string;
|
|
150
|
+
}
|
|
151
|
+
interface CancelResponse {
|
|
152
|
+
status: RunStatus;
|
|
153
|
+
}
|
|
154
|
+
interface SignalResponse {
|
|
155
|
+
accepted: true;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
type Duration = number | string;
|
|
159
|
+
interface StepRunOptions {
|
|
160
|
+
timeout?: Duration;
|
|
161
|
+
retries?: number;
|
|
162
|
+
}
|
|
163
|
+
interface StepExecutionContext {
|
|
164
|
+
signal: AbortSignal;
|
|
165
|
+
attempt: number;
|
|
166
|
+
}
|
|
167
|
+
interface DurableStep<E extends Record<string, StandardSchemaV1>> {
|
|
168
|
+
run<T>(key: string, callback: (context: StepExecutionContext) => T | Promise<T>, options?: StepRunOptions): Promise<T>;
|
|
169
|
+
sleep(key: string, duration: Duration): Promise<void>;
|
|
170
|
+
waitForEvent<K extends keyof E & string>(key: string, event: K, options: {
|
|
171
|
+
timeout: Duration;
|
|
172
|
+
}): Promise<StandardSchemaV1.InferOutput<E[K]> | null>;
|
|
173
|
+
progress(value: JSONValue): void;
|
|
174
|
+
}
|
|
175
|
+
interface DefineDurableFunctionOptions<I extends StandardSchemaV1, O extends StandardSchemaV1, E extends Record<string, StandardSchemaV1>> {
|
|
176
|
+
input: I;
|
|
177
|
+
output: O;
|
|
178
|
+
events: E;
|
|
179
|
+
handler(input: StandardSchemaV1.InferOutput<I>, step: DurableStep<E>, ctx: ServerContext): StandardSchemaV1.InferInput<O> | Promise<StandardSchemaV1.InferInput<O>>;
|
|
180
|
+
}
|
|
181
|
+
interface DefinedDurableFunction {
|
|
182
|
+
readonly [key: symbol]: unknown;
|
|
183
|
+
}
|
|
184
|
+
declare function defineDurableFunction<I extends StandardSchemaV1, O extends StandardSchemaV1, E extends Record<string, StandardSchemaV1>>(definition: DefineDurableFunctionOptions<I, O, E>): DefinedDurableFunction;
|
|
185
|
+
|
|
186
|
+
declare const durable: {
|
|
187
|
+
start(functionId: string, input: JSONValue, options?: {
|
|
188
|
+
idempotencyKey?: string;
|
|
189
|
+
}): Promise<StartResponse>;
|
|
190
|
+
get(runId: string, options?: Pick<GetParams, "scope">): Promise<Run>;
|
|
191
|
+
list(options?: Omit<ListParams, "action">): Promise<ListResponse>;
|
|
192
|
+
cancel(runId: string, options?: Pick<GetParams, "scope">): Promise<CancelResponse>;
|
|
193
|
+
signal(runId: string, event: string, data: JSONValue, options: {
|
|
194
|
+
eventId: string;
|
|
195
|
+
}): Promise<SignalResponse>;
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
declare class DurableError extends Error {
|
|
199
|
+
readonly reason: string;
|
|
200
|
+
constructor(reason: string, message?: string);
|
|
201
|
+
}
|
|
202
|
+
declare class NonRetryableError extends Error {
|
|
203
|
+
constructor(message: string);
|
|
204
|
+
}
|
|
205
|
+
declare class StepFailedError extends Error {
|
|
206
|
+
readonly key: string;
|
|
207
|
+
readonly error: OpError;
|
|
208
|
+
constructor(key: string, error: OpError);
|
|
209
|
+
}
|
|
210
|
+
|
|
77
211
|
type LegacyFunctionHandler<Context = unknown> = (rawParams: unknown, context: Context) => unknown | Promise<unknown>;
|
|
78
212
|
|
|
79
|
-
export { AttachmentInput, Attachments, DefineFunctionOptions, DefinedFunction, Fields, FunctionEnvelope, FunctionEnvelope as FunctionResult, JsonValue, LegacyFunctionHandler, RawFunctionContext, RecordsClient, RecordsOperation, RecordsResultRequest, RuntimeBuildProfile, ServerContext, Target, WriteResult, bindFunctionRuntime, createServerContext, defineFunction, normalizeRecordsResult };
|
|
213
|
+
export { AttachmentInput, Attachments, DefineDurableFunctionOptions, DefineFunctionOptions, DefinedDurableFunction, DefinedFunction, DurableError, DurableStep, Duration, Fields, FunctionEnvelope, FunctionEnvelope as FunctionResult, JsonValue, LegacyFunctionHandler, NonRetryableError, RawFunctionContext, RecordsClient, RecordsOperation, RecordsResultRequest, RuntimeBuildProfile, ServerContext, StepExecutionContext, StepFailedError, StepRunOptions, Target, WriteResult, bindFunctionRuntime, createServerContext, defineDurableFunction, defineFunction, durable, normalizeRecordsResult };
|
package/dist/server.d.ts
CHANGED
|
@@ -35,6 +35,10 @@ interface RecordsClient {
|
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
interface RawFunctionContext {
|
|
38
|
+
faasInvoke?(request: {
|
|
39
|
+
method: "durable";
|
|
40
|
+
params: string;
|
|
41
|
+
}): Promise<unknown>;
|
|
38
42
|
fetch: typeof globalThis.fetch;
|
|
39
43
|
invokeFunction(p: {
|
|
40
44
|
projectId: string;
|
|
@@ -74,6 +78,136 @@ interface RecordsResultRequest {
|
|
|
74
78
|
}
|
|
75
79
|
declare function normalizeRecordsResult(body: unknown, request: RecordsResultRequest): WriteResult;
|
|
76
80
|
|
|
81
|
+
type JSONValue = null | boolean | number | string | JSONValue[] | {
|
|
82
|
+
[key: string]: JSONValue;
|
|
83
|
+
};
|
|
84
|
+
type RunStatus = "queued" | "running" | "sleeping" | "waiting" | "completed" | "failed" | "cancelled" | (string & {});
|
|
85
|
+
type StepKind = "run" | "sleep" | "wait";
|
|
86
|
+
type Trigger = {
|
|
87
|
+
kind: "server";
|
|
88
|
+
} | {
|
|
89
|
+
kind: "timer";
|
|
90
|
+
fireId: string;
|
|
91
|
+
};
|
|
92
|
+
interface OpError {
|
|
93
|
+
name?: string;
|
|
94
|
+
message: string;
|
|
95
|
+
code?: string;
|
|
96
|
+
key?: string;
|
|
97
|
+
retryable?: boolean;
|
|
98
|
+
}
|
|
99
|
+
interface Waiting {
|
|
100
|
+
event: string;
|
|
101
|
+
until: number;
|
|
102
|
+
}
|
|
103
|
+
interface StepView {
|
|
104
|
+
key: string;
|
|
105
|
+
kind: StepKind;
|
|
106
|
+
status: string;
|
|
107
|
+
attempts: number;
|
|
108
|
+
startedAt: number;
|
|
109
|
+
endedAt?: number;
|
|
110
|
+
}
|
|
111
|
+
interface RunSummary {
|
|
112
|
+
runId: string;
|
|
113
|
+
functionId: string;
|
|
114
|
+
status: RunStatus;
|
|
115
|
+
trigger: Trigger;
|
|
116
|
+
output: JSONValue;
|
|
117
|
+
error: OpError | null;
|
|
118
|
+
progress: JSONValue;
|
|
119
|
+
waiting: Waiting | null;
|
|
120
|
+
sleepingUntil: number | null;
|
|
121
|
+
createdAt: number;
|
|
122
|
+
updatedAt: number;
|
|
123
|
+
closedAt: number | null;
|
|
124
|
+
}
|
|
125
|
+
interface Run extends RunSummary {
|
|
126
|
+
input?: JSONValue;
|
|
127
|
+
steps: StepView[];
|
|
128
|
+
}
|
|
129
|
+
interface GetParams {
|
|
130
|
+
action: "get";
|
|
131
|
+
runId: string;
|
|
132
|
+
scope?: string;
|
|
133
|
+
}
|
|
134
|
+
interface ListParams {
|
|
135
|
+
action: "list";
|
|
136
|
+
functionId?: string;
|
|
137
|
+
status?: RunStatus;
|
|
138
|
+
scope?: string;
|
|
139
|
+
pageToken?: string;
|
|
140
|
+
pageSize?: number;
|
|
141
|
+
}
|
|
142
|
+
interface StartResponse {
|
|
143
|
+
runId: string;
|
|
144
|
+
status: RunStatus;
|
|
145
|
+
deduplicated: boolean;
|
|
146
|
+
}
|
|
147
|
+
interface ListResponse {
|
|
148
|
+
runs: RunSummary[];
|
|
149
|
+
nextPageToken: string;
|
|
150
|
+
}
|
|
151
|
+
interface CancelResponse {
|
|
152
|
+
status: RunStatus;
|
|
153
|
+
}
|
|
154
|
+
interface SignalResponse {
|
|
155
|
+
accepted: true;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
type Duration = number | string;
|
|
159
|
+
interface StepRunOptions {
|
|
160
|
+
timeout?: Duration;
|
|
161
|
+
retries?: number;
|
|
162
|
+
}
|
|
163
|
+
interface StepExecutionContext {
|
|
164
|
+
signal: AbortSignal;
|
|
165
|
+
attempt: number;
|
|
166
|
+
}
|
|
167
|
+
interface DurableStep<E extends Record<string, StandardSchemaV1>> {
|
|
168
|
+
run<T>(key: string, callback: (context: StepExecutionContext) => T | Promise<T>, options?: StepRunOptions): Promise<T>;
|
|
169
|
+
sleep(key: string, duration: Duration): Promise<void>;
|
|
170
|
+
waitForEvent<K extends keyof E & string>(key: string, event: K, options: {
|
|
171
|
+
timeout: Duration;
|
|
172
|
+
}): Promise<StandardSchemaV1.InferOutput<E[K]> | null>;
|
|
173
|
+
progress(value: JSONValue): void;
|
|
174
|
+
}
|
|
175
|
+
interface DefineDurableFunctionOptions<I extends StandardSchemaV1, O extends StandardSchemaV1, E extends Record<string, StandardSchemaV1>> {
|
|
176
|
+
input: I;
|
|
177
|
+
output: O;
|
|
178
|
+
events: E;
|
|
179
|
+
handler(input: StandardSchemaV1.InferOutput<I>, step: DurableStep<E>, ctx: ServerContext): StandardSchemaV1.InferInput<O> | Promise<StandardSchemaV1.InferInput<O>>;
|
|
180
|
+
}
|
|
181
|
+
interface DefinedDurableFunction {
|
|
182
|
+
readonly [key: symbol]: unknown;
|
|
183
|
+
}
|
|
184
|
+
declare function defineDurableFunction<I extends StandardSchemaV1, O extends StandardSchemaV1, E extends Record<string, StandardSchemaV1>>(definition: DefineDurableFunctionOptions<I, O, E>): DefinedDurableFunction;
|
|
185
|
+
|
|
186
|
+
declare const durable: {
|
|
187
|
+
start(functionId: string, input: JSONValue, options?: {
|
|
188
|
+
idempotencyKey?: string;
|
|
189
|
+
}): Promise<StartResponse>;
|
|
190
|
+
get(runId: string, options?: Pick<GetParams, "scope">): Promise<Run>;
|
|
191
|
+
list(options?: Omit<ListParams, "action">): Promise<ListResponse>;
|
|
192
|
+
cancel(runId: string, options?: Pick<GetParams, "scope">): Promise<CancelResponse>;
|
|
193
|
+
signal(runId: string, event: string, data: JSONValue, options: {
|
|
194
|
+
eventId: string;
|
|
195
|
+
}): Promise<SignalResponse>;
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
declare class DurableError extends Error {
|
|
199
|
+
readonly reason: string;
|
|
200
|
+
constructor(reason: string, message?: string);
|
|
201
|
+
}
|
|
202
|
+
declare class NonRetryableError extends Error {
|
|
203
|
+
constructor(message: string);
|
|
204
|
+
}
|
|
205
|
+
declare class StepFailedError extends Error {
|
|
206
|
+
readonly key: string;
|
|
207
|
+
readonly error: OpError;
|
|
208
|
+
constructor(key: string, error: OpError);
|
|
209
|
+
}
|
|
210
|
+
|
|
77
211
|
type LegacyFunctionHandler<Context = unknown> = (rawParams: unknown, context: Context) => unknown | Promise<unknown>;
|
|
78
212
|
|
|
79
|
-
export { AttachmentInput, Attachments, DefineFunctionOptions, DefinedFunction, Fields, FunctionEnvelope, FunctionEnvelope as FunctionResult, JsonValue, LegacyFunctionHandler, RawFunctionContext, RecordsClient, RecordsOperation, RecordsResultRequest, RuntimeBuildProfile, ServerContext, Target, WriteResult, bindFunctionRuntime, createServerContext, defineFunction, normalizeRecordsResult };
|
|
213
|
+
export { AttachmentInput, Attachments, DefineDurableFunctionOptions, DefineFunctionOptions, DefinedDurableFunction, DefinedFunction, DurableError, DurableStep, Duration, Fields, FunctionEnvelope, FunctionEnvelope as FunctionResult, JsonValue, LegacyFunctionHandler, NonRetryableError, RawFunctionContext, RecordsClient, RecordsOperation, RecordsResultRequest, RuntimeBuildProfile, ServerContext, StepExecutionContext, StepFailedError, StepRunOptions, Target, WriteResult, bindFunctionRuntime, createServerContext, defineDurableFunction, defineFunction, durable, normalizeRecordsResult };
|
package/dist/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as h}from"./chunk-3JX3FIBG.js";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 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 h("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(b)&&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(!b(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(b))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(!b(f)||!d(g))throw 0;for(let[A,w]of Object.entries(g)){if(!A.trim()||!Array.isArray(w))throw 0;for(let y of w){if(!d(y)||typeof y.file_token!="string"||!y.file_token.trim()||Object.keys(y).some(R=>!["file_token",...e==="appendAttachments"?["image_width","image_height"]:[]].includes(R)))throw 0;for(let R of["image_width","image_height"])if(y[R]!==void 0&&(typeof y[R]!="number"||!Number.isInteger(y[R])||y[R]<=0))throw 0}p+=w.length,w.length&&(o[f]??=Object.create(null),o[f][A]=w)}}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(b)||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 h("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 h(`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 h?e:new h("SDK_HANDLER_FAILED","\u51FD\u6570\u6267\u884C\u5931\u8D25");console.error(JSON.stringify({source:"sdk",code:r.code,paths:r.paths,retryable:r.retryable,outcome:r.outcome}));let n={code:r.wireCode,msg:r.safeMessage};return e instanceof h||Object.defineProperty(n,Symbol.for("base-site.function-error"),{value:e}),n}}}export{h as SDKError,N as bindFunctionRuntime,k as createServerContext,K as defineFunction,_ as normalizeRecordsResult};
|
|
1
|
+
import{a as I}from"./chunk-3JX3FIBG.js";var S=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),N=e=>typeof e=="string"&&/^rec[A-Za-z0-9]{1,32}$/.test(e);function P(e){let r=new Set,n=t=>{if(!(t===null||typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))){if(typeof t!="object"||!t||r.has(t)||Array.isArray(t)&&Object.getPrototypeOf(t)!==Array.prototype||!Array.isArray(t)&&Object.getPrototypeOf(t)!==Object.prototype&&Object.getPrototypeOf(t)!==null||Array.isArray(t)&&(Object.keys(t).length!==t.length||Object.keys(t).some((s,o)=>s!==String(o))))throw 0;r.add(t);for(let s of Reflect.ownKeys(t)){if(Array.isArray(t)&&s==="length")continue;if(typeof s!="string")throw 0;let o=Object.getOwnPropertyDescriptor(t,s);if(!o.enumerable||!("value"in o))throw 0;n(o.value)}r.delete(t)}};try{n(e)}catch{throw new I("SDK_OUTPUT_NOT_JSON","\u8F93\u51FA\u5FC5\u987B\u662F\u65E0\u635F JSON \u503C")}}function V(e,r,n){return{status:"unknown",code:e,retryable:!1,...r?{requestedIds:[...r]}:{},...n?{logid:n}:{}}}var se=e=>typeof e=="number"&&[401,403,404,91403,1254302,1254043,1254044].includes(e),B=e=>({status:"failed",code:"SDK_RECORDS_REJECTED",upstreamCode:e,retryable:!1,appliedIds:[]}),H=e=>Array.isArray(e)&&e.every(N)&&new Set(e).size===e.length;function W(e,r){let n=()=>V("SDK_RECORDS_RESULT_UNKNOWN",r.requestedIds);if(S(e)&&se(e.code))return B(e.code);if(!S(e)||e.code!==0||!S(e.data))return n();let t=e.data,s=t.ignored_fields??[];if(!Array.isArray(s)||!s.every(a=>S(a)&&["id","name","reason"].every(u=>typeof a[u]=="string")))return n();let o=t.record_not_found??[];if(!H(o))return n();let l=r.requestedIds??[],d,R;if(r.operation==="appendAttachments"||r.operation==="removeAttachments"){if(!S(t.attachments))return n();try{P(t.attachments)}catch{return n()}for(let[a,u]of Object.entries(t.attachments)){if(!N(a)||!l.includes(a)||!S(u)||!Object.keys(u).length)return n();for(let[m,g]of Object.entries(u))if(!/^fld[A-Za-z0-9]+$/.test(m)||!Array.isArray(g)||!g.every(b=>S(b)&&typeof b.file_token=="string"&&b.file_token.length>0))return n()}if(d=Object.keys(t.attachments),o.some(a=>!l.includes(a)||d.includes(a))||!s.length&&l.some(a=>!d.includes(a)&&!o.includes(a)))return n();R=t.attachments}else{if(!H(t.record_id_list))return n();let a=t.record_id_list;if(r.operation==="create"){if(a.length!==r.count||Object.hasOwn(t,"record_not_found"))return n();d=a}else if(r.operation==="update"){if(a.some(u=>!l.includes(u)||o.includes(u))||o.some(u=>!l.includes(u))||a.length+o.length!==l.length)return n();d=a}else{if(a.length!==l.length||a.some((u,m)=>u!==l[m])||o.some(u=>!l.includes(u)))return n();d=a.filter(u=>!o.includes(u))}}let p=R===void 0?{}:{attachments:R};return o.length||s.length?{status:"partial",appliedIds:d,notFoundIds:o,ignoredFields:s,...p}:{status:"success",appliedIds:d,notFoundIds:[],ignoredFields:[],...p}}var G={create:"records/batch_create",update:"records/batch_update",delete:"records/batch_delete",appendAttachments:"append_attachments",removeAttachments:"remove_attachments"},M=e=>({status:"failed",code:e,retryable:!1,appliedIds:[]});function ie(e){if(e?.platformEnv==="online")return e.brand==="feishu"?"https://open.feishu.cn":e.brand==="lark"?"https://open.larksuite.com":void 0;if(e?.brand==="feishu"){if(e.platformEnv==="pre")return"https://open.feishu-pre.cn";if(e.platformEnv==="boe")return"https://open.feishu-boe.cn"}}function Z(e,r){let n=async(t,s,o,l)=>{if(!r)return M("SDK_RUNTIME_PROFILE_MISSING");let d=ie(r);if(!d)return M("SDK_RUNTIME_PROFILE_UNSUPPORTED");if(l?.signal?.aborted)return M("SDK_CANCELLED");let R,p,a;try{if(!S(s)||typeof s.baseToken!="string"||typeof s.tableId!="string"||!/^[A-Za-z0-9]+$/.test(s.baseToken)||!/^tbl[A-Za-z0-9]+$/.test(s.tableId))throw 0;if(P(o),t==="create"){if(!Array.isArray(o)||!o.every(S))throw 0;a=o.length,R={create_records:o}}else if(t==="update"){if(!S(o)||!Object.values(o).every(S))throw 0;p=Object.keys(o),a=p.length,R={update_records:o}}else if(t==="delete"){if(!Array.isArray(o)||!o.every(N))throw 0;p=o,a=o.length,R={record_id_list:o}}else{if(!S(o))throw 0;let u=Object.create(null),m=0;for(let[g,b]of Object.entries(o)){if(!N(g)||!S(b))throw 0;for(let[O,f]of Object.entries(b)){if(!O.trim()||!Array.isArray(f))throw 0;for(let h of f){if(!S(h)||typeof h.file_token!="string"||!h.file_token.trim()||Object.keys(h).some(E=>!["file_token",...t==="appendAttachments"?["image_width","image_height"]:[]].includes(E)))throw 0;for(let E of["image_width","image_height"])if(h[E]!==void 0&&(typeof h[E]!="number"||!Number.isInteger(h[E])||h[E]<=0))throw 0}m+=f.length,f.length&&(u[g]??=Object.create(null),u[g][O]=f)}}if(m>50)throw 0;if(!m)return{status:"success",appliedIds:[],notFoundIds:[],ignoredFields:[],noop:!0};p=Object.keys(u),R={attachments:u}}if(a!==void 0&&(a<1||a>200)||p&&(!p.every(N)||new Set(p).size!==p.length))throw 0}catch{return M("SDK_RECORDS_INPUT_INVALID")}try{let u=await e.fetch(`${d}/open-apis/bitable/v1/apps/${encodeURIComponent(s.baseToken)}/tables/${encodeURIComponent(s.tableId)}/${G[t]}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(R),signal:l?.signal}),m=u.headers.get("x-tt-logid")??void 0;if([401,403,404].includes(u.status))return B(u.status);if(!u.ok)return V("SDK_RECORDS_HTTP_ERROR",p,m);let g=W(await u.json(),{operation:t,requestedIds:p,count:a});return g.status==="unknown"&&m?{...g,logid:m}:g}catch(u){let m=u instanceof Error?u.name:"";return V(m==="AbortError"?"SDK_CANCELLED":m==="TimeoutError"?"SDK_TIMEOUT":"SDK_RECORDS_RESULT_UNKNOWN",p)}};return Object.fromEntries(Object.keys(G).map(t=>[t,(s,o,l)=>n(t,s,o,l)]))}var Y=Symbol("base-database-runtime-profile");function ae(e,r){let n=Object.freeze({platformEnv:r.platformEnv,brand:r.brand});return function(t,s){let o=Object.defineProperty({...s},Y,{value:n});return e.call(this,t,o)}}function C(e){return{...e,records:Z(e,e[Y])}}async function X(e,r,n){let t;try{t=await e["~standard"].validate(r)}catch{throw new I("SDK_VALIDATOR_FAILED","Schema \u6821\u9A8C\u5668\u6267\u884C\u5931\u8D25")}if(t.issues){let s=t.issues.map(o=>(o.path??[]).map(l=>{let d=typeof l=="object"?l.key:l;return typeof d=="number"||typeof d=="string"?d:"[symbol]"}));throw new I(`SDK_${n}_INVALID`,n==="INPUT"?"\u8F93\u5165\u4E0D\u7B26\u5408\u5951\u7EA6":"\u8F93\u51FA\u4E0D\u7B26\u5408\u5951\u7EA6",{paths:s})}return t.value}function ue(e){return async(r,n)=>{try{let t=await X(e.input,r,"INPUT"),s=await e.handler(t,C(n)),o=await X(e.output,s,"OUTPUT");return P(o),{code:0,msg:"success",data:o}}catch(t){let s=t instanceof I?t:new I("SDK_HANDLER_FAILED","\u51FD\u6570\u6267\u884C\u5931\u8D25");console.error(JSON.stringify({source:"sdk",code:s.code,paths:s.paths,retryable:s.retryable,outcome:s.outcome}));let o={code:s.wireCode,msg:s.safeMessage};return t instanceof I||Object.defineProperty(o,Symbol.for("base-site.function-error"),{value:t}),o}}}var Q="base-site.durable",ee="base-site.runtime";var A=class extends Error{constructor(n,t=n){super(t);this.reason=n;this.name="DurableError"}},_=class extends Error{constructor(r){super(r),this.name="NonRetryableError"}},k=class extends Error{constructor(n,t){super(t.message);this.key=n;this.error=t;this.name="StepFailedError"}};function J(e,r,n){let t="Unknown error",s="Error";try{e instanceof Error?(typeof e.message=="string"&&(t=e.message),typeof e.name=="string"&&(s=e.name)):typeof e=="string"&&(t=e)}catch{}t=t.slice(0,1024*4).replace(/([?&][^=&#\s]*?(?:token|ticket|code|secret|key|password|authorization)[^=&#\s]*=)[^&#\s]*/gi,"$1[REDACTED]").replace(/\bBearer\s+[^\s"'<>]+/gi,"Bearer [REDACTED]").replace(/[A-Za-z0-9_]{32,}/g,"[REDACTED]");let o="",l=0;for(let d of t){if(l+=new TextEncoder().encode(d).length,l>1024)break;o+=d}return{name:s,message:o,...r?{code:r}:{},...n?{key:n}:{},...e instanceof _?{retryable:!1}:{}}}function z(e){let r={ms:1,s:1e3,m:6e4,h:36e5,d:864e5},n=typeof e=="string"&&/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/.exec(e),t=typeof e=="number"?e:n?Number(n[1])*r[n[2]]:NaN;if(!Number.isSafeInteger(t)||t<0)throw new Error("Invalid duration");return t}function q(e){return P(e),e}function $(e){return new TextEncoder().encode(JSON.stringify(e)).length}var T=()=>new Promise(()=>{});function ge(e){let r={v:1,async execute(n,t){try{return await ye(e,n,t)}catch(s){return{v:1,seq:n?.invocation?.seq??0,op:"fail",error:J(s,"HANDLER_ERROR")}}}};return{[Symbol.for(Q)]:r}}function ye(e,r,n){return new Promise(t=>{let s={v:1,seq:r.invocation.seq},o=new Set,l=new Map(r.steps.map(i=>[i.key,i])),d,R=!1,p=!1,a,u,m,g,b=Math.min(n.deadline,r.invocation.deadline),O=i=>{p||((!a||i.op==="fail")&&(a=i),queueMicrotask(()=>{p||!a||(p=!0,clearTimeout(E),clearTimeout(m),n.signal.removeEventListener("abort",h),u?.abort(),t({...a,...d!==void 0?{progress:d}:{}}))}))},f=(i,y,c=new Error(i))=>O({...s,op:"fail",error:J(c,i,y)}),h=()=>g?g():f("REPLAY_TIMEOUT"),E=setTimeout(h,Math.max(0,b-Date.now())),j=(i,y)=>{if(p||a?.op==="fail")return;if(Date.now()>=b){h();return}if(typeof i!="string"||i.length<1||i.length>128||/[\x00-\x1f\x7f-\x9f]/.test(i)){f("DEFINITION_INVALID",void 0,new Error("Invalid step key"));return}if(o.has(i)){f("DUPLICATE_STEP_KEY",i);return}o.add(i);let c=l.get(i);if(c){if(c.kind!==y){f("DEFINITION_KIND_MISMATCH",i);return}if(!c.ok)throw new k(i,c.error);return{fresh:!1,value:y==="sleep"?void 0:c.timedOut?null:c.value}}if(R){f("PARALLEL_STEPS",i);return}if(l.size>=100){f("STEP_LIMIT",i);return}return R=!0,{fresh:!0}},re={async run(i,y,c={}){let x=j(i,"run");if(!x)return T();if(!x.fresh)return x.value;let w,K=c.retries??3;try{if(w=c.timeout===void 0?b-Date.now():Math.min(z(c.timeout),b-Date.now()),!Number.isSafeInteger(K)||K<0||w<=0)throw new Error("Invalid step options")}catch(D){return f("DEFINITION_INVALID",i,D),T()}u=new AbortController;let oe=u.signal,v=Date.now(),U=(D,L)=>O({...s,op:"step",key:i,ok:!1,error:J(D,L,i),policy:{retries:K},durationMs:Math.max(0,Date.now()-v)});return g=()=>{U(new Error("Step exceeded its deadline"),"STEP_TIMEOUT"),u?.abort()},m=setTimeout(g,w),Promise.resolve().then(async()=>{if(!(a||p))try{let D=await y({signal:oe,attempt:r.invocation.attempt});if(Date.now()>=v+w){g?.();return}let L=q(D===void 0?null:D);if($(L)>262144){U(new _("Step result exceeds 256KB"),"STEP_RESULT_TOO_LARGE");return}O({...s,op:"step",key:i,ok:!0,value:L,durationMs:Math.max(0,Date.now()-v)})}catch(D){Date.now()>=v+w?g?.():U(D)}}),T()},async sleep(i,y){let c=j(i,"sleep");if(!c)return T();if(c.fresh){try{let x=z(y);if(x<1e3||x>2592e6)throw new Error("Sleep duration must be between 1s and 30d");O({...s,op:"sleep",key:i,durationMs:x})}catch(x){f("DEFINITION_INVALID",i,x)}return T()}},async waitForEvent(i,y,c){if(!Object.hasOwn(e.events,y))return f("EVENT_UNDECLARED",i),T();let x=j(i,"wait");if(!x)return T();if(!x.fresh)return x.value;try{let w=z(c.timeout);if(w<1e3||w>2592e6)throw new Error("Event timeout must be between 1s and 30d");O({...s,op:"wait",key:i,event:y,timeoutMs:w})}catch(w){f("DEFINITION_INVALID",i,w)}return T()},progress(i){if(!p)try{let y=q(i);$(y)<=4096?d=JSON.parse(JSON.stringify(y)):console.warn("Durable progress exceeds 4KB; discarded")}catch{f("DEFINITION_INVALID",void 0,new Error("Progress must be JSON"))}}};if(n.signal.addEventListener("abort",h,{once:!0}),n.signal.aborted||b<=Date.now()){h();return}Promise.resolve().then(async()=>{try{let i;try{let c=await e.input["~standard"].validate(r.input);if(c.issues)throw new Error("Input schema validation failed");i=c.value}catch(c){f("INPUT_INVALID",void 0,c);return}if(p||a)return;if(Date.now()>=b){f("REPLAY_TIMEOUT");return}let y=await e.handler(i,re,C(n.ctx));if(R||p||a)return;try{let c=await e.output["~standard"].validate(y);if(c.issues)throw new Error("Output schema validation failed");if(Date.now()>=b){f("REPLAY_TIMEOUT");return}let x=q(c.value);if($(x)>262144)throw new Error("Output exceeds 256KB");O({...s,op:"done",output:x})}catch(c){f("OUTPUT_INVALID",void 0,c)}}catch(i){f("HANDLER_ERROR",i instanceof k?i.key:void 0,i)}})})}async function F(e){let r=globalThis[Symbol.for(ee)],n=r?.v===1?r.context.getStore()?.ctx:void 0;if(!n?.faasInvoke)throw new A("DURABLE_NO_CONTEXT");try{let t=await n.faasInvoke({method:"durable",params:JSON.stringify(e)});if(!t||t.code!==0)throw new A(t?.data?.reason??"INFRA_UNAVAILABLE");return t.data}catch(t){throw t instanceof A?t:new A("INFRA_UNAVAILABLE")}}var xe={start(e,r,n){return F({...n,action:"start",functionId:e,input:r})},get(e,r){return F({...r,action:"get",runId:e})},list(e){return F({...e,action:"list"})},cancel(e,r){return F({...r,action:"cancel",runId:e})},signal(e,r,n,t){return F({...t,action:"signal",runId:e,event:r,data:n})}};export{A as DurableError,_ as NonRetryableError,I as SDKError,k as StepFailedError,ae as bindFunctionRuntime,C as createServerContext,ge as defineDurableFunction,ue as defineFunction,xe as durable,W as normalizeRecordsResult};
|
package/docs/codegen.md
CHANGED
|
@@ -29,4 +29,4 @@ export const files = await generateFunctionClients(data);
|
|
|
29
29
|
|
|
30
30
|
生成完成后运行 `base-database-cli check --json` 检查契约与生成文件是否一致。
|
|
31
31
|
|
|
32
|
-
|
|
32
|
+
Page 客户端只接受 SQL、FaaS 与 Mutation(`functionType=1|2|5`)。Durable Function 不生成页面调用入口;在 server 代码中通过 `/server` 的 `durable` 客户端控制任务。
|
package/docs/durable.md
CHANGED
|
@@ -1,54 +1,47 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 长时任务 SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
从 `/server` 导入 `defineDurableFunction`、`durable`、`NonRetryableError`、`StepFailedError` 与 `DurableError`。长时任务放在 `server/durable/<id>`,与普通 Function 共用依赖与构建。
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
`defineDurableFunction({ input, output, events, handler })` 返回默认导出对象。handler 参数为 `(input, step, ctx)`;契约使用 Standard Schema(如 zod)。每轮推进按当前契约解析 input,default、transform 均生效;不合规时以 INPUT_INVALID 失败。handler 返回后校验 output。
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
- `step.run(key, callback, { timeout?, retries? })`:回调接收 `{ signal, attempt }`。默认重试 3 次(最多 4 次尝试),按 1 秒起、倍增至最多 60 秒的间隔退避;抛出 `NonRetryableError` 禁止重试。失败耗尽后重放抛出 `StepFailedError`,业务可捕获补偿。错误仅包含 key、error;重试次数见 durable.get 返回的 step 列表。
|
|
8
|
+
- `step.sleep(key, duration)`:持久化等待。时长支持毫秒数以及 `ms`、`s`、`m`、`h`、`d` 后缀。
|
|
9
|
+
- `step.waitForEvent(key, event, { timeout })`:等待声明的事件,超时返回 null。sleep/wait 时长范围为 1 秒至 30 天。
|
|
10
|
+
- `step.progress(value)`:记录本轮最后一个有效 JSON 进度,超过 4KB 丢弃。
|
|
8
11
|
|
|
9
|
-
|
|
12
|
+
每个 key 在流程中唯一;循环使用动态 key。只支持顺序 await,不支持 Promise.all。每轮只执行第一个未记录步骤;该 await 不恢复,平台记录结果后重新调用整个 handler。步骤外代码每轮重放,随机值、时间与外部副作用放进 step.run。步骤至少执行一次,写入仍需业务幂等。step.run 结果与最终输出各最大 256KB;step.run 的 void 结果转为 null。最多记录 100 个步骤。
|
|
10
13
|
|
|
11
|
-
|
|
14
|
+
## 报销审批
|
|
12
15
|
|
|
13
|
-
|
|
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 -->
|
|
16
|
+
<!-- example: durable.ts -->
|
|
34
17
|
```ts
|
|
35
|
-
|
|
36
|
-
|
|
18
|
+
import { z } from 'zod';
|
|
19
|
+
import { defineDurableFunction } from '@lark-base-open/base-database-app-sdk/server';
|
|
20
|
+
|
|
21
|
+
export const input = z.object({ title: z.string(), amount: z.number().positive(), approverId: z.string() });
|
|
22
|
+
export const output = z.object({ expenseId: z.string(), status: z.enum(['paid', 'rejected', 'expired']) });
|
|
23
|
+
export const events = { approval: z.object({ approved: z.boolean() }) };
|
|
24
|
+
|
|
25
|
+
// 业务模块由应用提供;写入需以业务单号去重。
|
|
26
|
+
export function expenseApproval(service: {
|
|
27
|
+
createExpense(value: z.infer<typeof input>): Promise<{ id: string }>;
|
|
28
|
+
notifyApprover(id: string, approver: string): Promise<void>;
|
|
29
|
+
setStatus(id: string, status: 'paid' | 'rejected' | 'expired'): Promise<void>;
|
|
30
|
+
}) {
|
|
31
|
+
return defineDurableFunction({ input, output, events, handler: async (input, step) => {
|
|
32
|
+
const expense = await step.run('create', () => service.createExpense(input), { timeout: '30s', retries: 3 });
|
|
33
|
+
await step.run('notify', () => service.notifyApprover(expense.id, input.approverId));
|
|
34
|
+
step.progress({ stage: 'waiting_approval' });
|
|
35
|
+
const decision = await step.waitForEvent('wait-approval', 'approval', { timeout: '3d' });
|
|
36
|
+
const status = decision === null ? 'expired' : decision.approved ? 'paid' : 'rejected';
|
|
37
|
+
await step.run(status === 'paid' ? 'pay' : status === 'expired' ? 'expire' : 'reject', () => service.setStatus(expense.id, status));
|
|
38
|
+
return { expenseId: expense.id, status } as const;
|
|
39
|
+
} });
|
|
37
40
|
}
|
|
38
41
|
```
|
|
39
42
|
|
|
40
|
-
|
|
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
|
-
## 类型维护
|
|
43
|
+
## server 控制接口
|
|
51
44
|
|
|
52
|
-
|
|
45
|
+
`durable.start(functionId, input, { idempotencyKey? })`、`get(runId, { scope? })`、`list({ functionId?, status?, scope?, pageToken?, pageSize? })`、`cancel(runId, { scope? })`、`signal(runId, event, data, { eventId })` 只能在请求上下文中调用。默认只查询或取消当前调用人启动的任务,全站点可见性需显式 scope: 'site'。审批业务需自行鉴权。
|
|
53
46
|
|
|
54
|
-
|
|
47
|
+
调用失败抛出 `DurableError`,reason 为平台字符串错误码;缺少请求上下文时为 DURABLE_NO_CONTEXT。业务身份不会缓存在模块变量中。
|
package/docs/exports.md
CHANGED
|
@@ -10,9 +10,9 @@
|
|
|
10
10
|
|
|
11
11
|
## server
|
|
12
12
|
|
|
13
|
-
值:`SDKError`、`bindFunctionRuntime`、`createServerContext`、`defineFunction`、`normalizeRecordsResult`。
|
|
13
|
+
值:`DurableError`、`NonRetryableError`、`SDKError`、`StepFailedError`、`bindFunctionRuntime`、`createServerContext`、`defineDurableFunction`、`defineFunction`、`durable`、`normalizeRecordsResult`。
|
|
14
14
|
|
|
15
|
-
类型与值完整清单:`AttachmentInput`、`Attachments`、`DefineFunctionOptions`、`DefinedFunction`、`DiagnosticCategory`、`Fields`、`FunctionEnvelope`、`FunctionResult`、`JsonValue`、`LegacyFunctionHandler`、`RawFunctionContext`、`RecordsClient`、`RecordsOperation`、`RecordsResultRequest`、`RuntimeBuildProfile`、`RuntimeDiagnostic`、`SDKError`、`SDKErrorOptions`、`ServerContext`、`Target`、`WriteResult`、`bindFunctionRuntime`、`createServerContext`、`defineFunction`、`normalizeRecordsResult`。
|
|
15
|
+
类型与值完整清单:`AttachmentInput`、`Attachments`、`DefineDurableFunctionOptions`、`DefineFunctionOptions`、`DefinedDurableFunction`、`DefinedFunction`、`DiagnosticCategory`、`DurableError`、`DurableStep`、`Duration`、`Fields`、`FunctionEnvelope`、`FunctionResult`、`JsonValue`、`LegacyFunctionHandler`、`NonRetryableError`、`RawFunctionContext`、`RecordsClient`、`RecordsOperation`、`RecordsResultRequest`、`RuntimeBuildProfile`、`RuntimeDiagnostic`、`SDKError`、`SDKErrorOptions`、`ServerContext`、`StepExecutionContext`、`StepFailedError`、`StepRunOptions`、`Target`、`WriteResult`、`bindFunctionRuntime`、`createServerContext`、`defineDurableFunction`、`defineFunction`、`durable`、`normalizeRecordsResult`。
|
|
16
16
|
|
|
17
17
|
## shared
|
|
18
18
|
|
|
@@ -43,15 +43,3 @@
|
|
|
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,23 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { defineDurableFunction } from '@lark-base-open/base-database-app-sdk/server';
|
|
3
|
+
|
|
4
|
+
export const input = z.object({ title: z.string(), amount: z.number().positive(), approverId: z.string() });
|
|
5
|
+
export const output = z.object({ expenseId: z.string(), status: z.enum(['paid', 'rejected', 'expired']) });
|
|
6
|
+
export const events = { approval: z.object({ approved: z.boolean() }) };
|
|
7
|
+
|
|
8
|
+
// 业务模块由应用提供;写入需以业务单号去重。
|
|
9
|
+
export function expenseApproval(service: {
|
|
10
|
+
createExpense(value: z.infer<typeof input>): Promise<{ id: string }>;
|
|
11
|
+
notifyApprover(id: string, approver: string): Promise<void>;
|
|
12
|
+
setStatus(id: string, status: 'paid' | 'rejected' | 'expired'): Promise<void>;
|
|
13
|
+
}) {
|
|
14
|
+
return defineDurableFunction({ input, output, events, handler: async (input, step) => {
|
|
15
|
+
const expense = await step.run('create', () => service.createExpense(input), { timeout: '30s', retries: 3 });
|
|
16
|
+
await step.run('notify', () => service.notifyApprover(expense.id, input.approverId));
|
|
17
|
+
step.progress({ stage: 'waiting_approval' });
|
|
18
|
+
const decision = await step.waitForEvent('wait-approval', 'approval', { timeout: '3d' });
|
|
19
|
+
const status = decision === null ? 'expired' : decision.approved ? 'paid' : 'rejected';
|
|
20
|
+
await step.run(status === 'paid' ? 'pay' : status === 'expired' ? 'expire' : 'reject', () => service.setStatus(expense.id, status));
|
|
21
|
+
return { expenseId: expense.id, status } as const;
|
|
22
|
+
} });
|
|
23
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lark-base-open/base-database-app-sdk",
|
|
3
|
-
"version": "0.6.0-durable.
|
|
3
|
+
"version": "0.6.0-durable.2",
|
|
4
4
|
"description": "Base Database 页面与服务端 SDK、平台组件及测试工具",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": [
|
|
@@ -54,26 +54,6 @@
|
|
|
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
|
-
}
|
|
77
57
|
}
|
|
78
58
|
},
|
|
79
59
|
"files": [
|
|
@@ -97,19 +77,11 @@
|
|
|
97
77
|
"@tanstack/react-query": "5.104.1",
|
|
98
78
|
"msw": "2.11.6",
|
|
99
79
|
"react": "^19.2.0",
|
|
100
|
-
"react-dom": "^19.2.0"
|
|
101
|
-
"@temporalio/activity": "1.24.0",
|
|
102
|
-
"@temporalio/workflow": "1.24.0"
|
|
80
|
+
"react-dom": "^19.2.0"
|
|
103
81
|
},
|
|
104
82
|
"peerDependenciesMeta": {
|
|
105
83
|
"msw": {
|
|
106
84
|
"optional": true
|
|
107
|
-
},
|
|
108
|
-
"@temporalio/activity": {
|
|
109
|
-
"optional": true
|
|
110
|
-
},
|
|
111
|
-
"@temporalio/workflow": {
|
|
112
|
-
"optional": true
|
|
113
85
|
}
|
|
114
86
|
},
|
|
115
87
|
"typesVersions": {
|
|
@@ -122,12 +94,6 @@
|
|
|
122
94
|
],
|
|
123
95
|
"codegen": [
|
|
124
96
|
"dist/codegen.d.cts"
|
|
125
|
-
],
|
|
126
|
-
"durable/workflow": [
|
|
127
|
-
"dist/durable/workflow.d.ts"
|
|
128
|
-
],
|
|
129
|
-
"durable/activity": [
|
|
130
|
-
"dist/durable/activity.d.ts"
|
|
131
97
|
]
|
|
132
98
|
}
|
|
133
99
|
}
|
|
@@ -1,25 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,6 +0,0 @@
|
|
|
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>;
|
|
@@ -1,6 +0,0 @@
|
|
|
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>;
|
|
@@ -1,107 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,15 +0,0 @@
|
|
|
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 {};
|
|
@@ -1,15 +0,0 @@
|
|
|
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 {};
|
|
@@ -1,8 +0,0 @@
|
|
|
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
|
-
}
|