@zerodep-dev/flow-ts-engine 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/LICENSE +21 -0
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/client/client.d.ts +112 -0
  4. package/dist/client/client.d.ts.map +1 -0
  5. package/dist/client/client.js +67 -0
  6. package/dist/client/client.js.map +1 -0
  7. package/dist/client/endpoint.d.ts +20 -0
  8. package/dist/client/endpoint.d.ts.map +1 -0
  9. package/dist/client/endpoint.js +153 -0
  10. package/dist/client/endpoint.js.map +1 -0
  11. package/dist/client/http.d.ts +30 -0
  12. package/dist/client/http.d.ts.map +1 -0
  13. package/dist/client/http.js +67 -0
  14. package/dist/client/http.js.map +1 -0
  15. package/dist/client/index.d.ts +12 -0
  16. package/dist/client/index.d.ts.map +1 -0
  17. package/dist/client/index.js +11 -0
  18. package/dist/client/index.js.map +1 -0
  19. package/dist/client/port.d.ts +24 -0
  20. package/dist/client/port.d.ts.map +1 -0
  21. package/dist/client/port.js +53 -0
  22. package/dist/client/port.js.map +1 -0
  23. package/dist/client/protocol.d.ts +26 -0
  24. package/dist/client/protocol.d.ts.map +1 -0
  25. package/dist/client/protocol.js +13 -0
  26. package/dist/client/protocol.js.map +1 -0
  27. package/dist/commands/admin.d.ts +41 -0
  28. package/dist/commands/admin.d.ts.map +1 -0
  29. package/dist/commands/admin.js +228 -0
  30. package/dist/commands/admin.js.map +1 -0
  31. package/dist/commands/complete.d.ts +36 -0
  32. package/dist/commands/complete.d.ts.map +1 -0
  33. package/dist/commands/complete.js +289 -0
  34. package/dist/commands/complete.js.map +1 -0
  35. package/dist/commands/dispatch.d.ts +11 -0
  36. package/dist/commands/dispatch.d.ts.map +1 -0
  37. package/dist/commands/dispatch.js +77 -0
  38. package/dist/commands/dispatch.js.map +1 -0
  39. package/dist/commands/operate.d.ts +14 -0
  40. package/dist/commands/operate.d.ts.map +1 -0
  41. package/dist/commands/operate.js +72 -0
  42. package/dist/commands/operate.js.map +1 -0
  43. package/dist/commands/operations.d.ts +75 -0
  44. package/dist/commands/operations.d.ts.map +1 -0
  45. package/dist/commands/operations.js +417 -0
  46. package/dist/commands/operations.js.map +1 -0
  47. package/dist/commands/signal.d.ts +9 -0
  48. package/dist/commands/signal.d.ts.map +1 -0
  49. package/dist/commands/signal.js +78 -0
  50. package/dist/commands/signal.js.map +1 -0
  51. package/dist/commands/start.d.ts +41 -0
  52. package/dist/commands/start.d.ts.map +1 -0
  53. package/dist/commands/start.js +186 -0
  54. package/dist/commands/start.js.map +1 -0
  55. package/dist/commands/submission.d.ts +20 -0
  56. package/dist/commands/submission.d.ts.map +1 -0
  57. package/dist/commands/submission.js +29 -0
  58. package/dist/commands/submission.js.map +1 -0
  59. package/dist/core/channels.d.ts +13 -0
  60. package/dist/core/channels.d.ts.map +1 -0
  61. package/dist/core/channels.js +13 -0
  62. package/dist/core/channels.js.map +1 -0
  63. package/dist/core/context.d.ts +76 -0
  64. package/dist/core/context.d.ts.map +1 -0
  65. package/dist/core/context.js +148 -0
  66. package/dist/core/context.js.map +1 -0
  67. package/dist/core/entities.d.ts +392 -0
  68. package/dist/core/entities.d.ts.map +1 -0
  69. package/dist/core/entities.js +282 -0
  70. package/dist/core/entities.js.map +1 -0
  71. package/dist/core/errors.d.ts +35 -0
  72. package/dist/core/errors.d.ts.map +1 -0
  73. package/dist/core/errors.js +18 -0
  74. package/dist/core/errors.js.map +1 -0
  75. package/dist/engine.d.ts +146 -0
  76. package/dist/engine.d.ts.map +1 -0
  77. package/dist/engine.js +85 -0
  78. package/dist/engine.js.map +1 -0
  79. package/dist/extensions.d.ts +198 -0
  80. package/dist/extensions.d.ts.map +1 -0
  81. package/dist/extensions.js +7 -0
  82. package/dist/extensions.js.map +1 -0
  83. package/dist/index.d.ts +19 -0
  84. package/dist/index.d.ts.map +1 -0
  85. package/dist/index.js +15 -0
  86. package/dist/index.js.map +1 -0
  87. package/dist/jobs/jobs.d.ts +27 -0
  88. package/dist/jobs/jobs.d.ts.map +1 -0
  89. package/dist/jobs/jobs.js +299 -0
  90. package/dist/jobs/jobs.js.map +1 -0
  91. package/dist/notify/collect.d.ts +38 -0
  92. package/dist/notify/collect.d.ts.map +1 -0
  93. package/dist/notify/collect.js +100 -0
  94. package/dist/notify/collect.js.map +1 -0
  95. package/dist/notify/inbox.d.ts +26 -0
  96. package/dist/notify/inbox.d.ts.map +1 -0
  97. package/dist/notify/inbox.js +87 -0
  98. package/dist/notify/inbox.js.map +1 -0
  99. package/dist/org/directory.d.ts +74 -0
  100. package/dist/org/directory.d.ts.map +1 -0
  101. package/dist/org/directory.js +254 -0
  102. package/dist/org/directory.js.map +1 -0
  103. package/dist/org/entities.d.ts +69 -0
  104. package/dist/org/entities.d.ts.map +1 -0
  105. package/dist/org/entities.js +39 -0
  106. package/dist/org/entities.js.map +1 -0
  107. package/dist/org/index.d.ts +5 -0
  108. package/dist/org/index.d.ts.map +1 -0
  109. package/dist/org/index.js +5 -0
  110. package/dist/org/index.js.map +1 -0
  111. package/dist/proxy/proxies.d.ts +18 -0
  112. package/dist/proxy/proxies.d.ts.map +1 -0
  113. package/dist/proxy/proxies.js +102 -0
  114. package/dist/proxy/proxies.js.map +1 -0
  115. package/dist/publish/project.d.ts +45 -0
  116. package/dist/publish/project.d.ts.map +1 -0
  117. package/dist/publish/project.js +176 -0
  118. package/dist/publish/project.js.map +1 -0
  119. package/dist/publish/publish.d.ts +42 -0
  120. package/dist/publish/publish.d.ts.map +1 -0
  121. package/dist/publish/publish.js +274 -0
  122. package/dist/publish/publish.js.map +1 -0
  123. package/dist/queries/queries.d.ts +24 -0
  124. package/dist/queries/queries.d.ts.map +1 -0
  125. package/dist/queries/queries.js +326 -0
  126. package/dist/queries/queries.js.map +1 -0
  127. package/dist/queries/stats.d.ts +9 -0
  128. package/dist/queries/stats.d.ts.map +1 -0
  129. package/dist/queries/stats.js +189 -0
  130. package/dist/queries/stats.js.map +1 -0
  131. package/dist/runtime/assignees.d.ts +32 -0
  132. package/dist/runtime/assignees.d.ts.map +1 -0
  133. package/dist/runtime/assignees.js +93 -0
  134. package/dist/runtime/assignees.js.map +1 -0
  135. package/dist/runtime/calls.d.ts +18 -0
  136. package/dist/runtime/calls.d.ts.map +1 -0
  137. package/dist/runtime/calls.js +182 -0
  138. package/dist/runtime/calls.js.map +1 -0
  139. package/dist/runtime/countersign.d.ts +26 -0
  140. package/dist/runtime/countersign.d.ts.map +1 -0
  141. package/dist/runtime/countersign.js +63 -0
  142. package/dist/runtime/countersign.js.map +1 -0
  143. package/dist/runtime/execution.d.ts +150 -0
  144. package/dist/runtime/execution.d.ts.map +1 -0
  145. package/dist/runtime/execution.js +792 -0
  146. package/dist/runtime/execution.js.map +1 -0
  147. package/dist/runtime/next-steps.d.ts +56 -0
  148. package/dist/runtime/next-steps.d.ts.map +1 -0
  149. package/dist/runtime/next-steps.js +145 -0
  150. package/dist/runtime/next-steps.js.map +1 -0
  151. package/dist/runtime/state.d.ts +26 -0
  152. package/dist/runtime/state.d.ts.map +1 -0
  153. package/dist/runtime/state.js +32 -0
  154. package/dist/runtime/state.js.map +1 -0
  155. package/dist/testing/scenarios.d.ts +35 -0
  156. package/dist/testing/scenarios.d.ts.map +1 -0
  157. package/dist/testing/scenarios.js +63 -0
  158. package/dist/testing/scenarios.js.map +1 -0
  159. package/dist/testing/simulate.d.ts +55 -0
  160. package/dist/testing/simulate.d.ts.map +1 -0
  161. package/dist/testing/simulate.js +122 -0
  162. package/dist/testing/simulate.js.map +1 -0
  163. package/dist/testing/testing.d.ts +31 -0
  164. package/dist/testing/testing.d.ts.map +1 -0
  165. package/dist/testing/testing.js +54 -0
  166. package/dist/testing/testing.js.map +1 -0
  167. package/dist/types.d.ts +283 -0
  168. package/dist/types.d.ts.map +1 -0
  169. package/dist/types.js +2 -0
  170. package/dist/types.js.map +1 -0
  171. package/dist/views.d.ts +317 -0
  172. package/dist/views.d.ts.map +1 -0
  173. package/dist/views.js +9 -0
  174. package/dist/views.js.map +1 -0
  175. package/package.json +76 -3
  176. package/src/client/client.ts +194 -0
  177. package/src/client/endpoint.ts +174 -0
  178. package/src/client/http.ts +99 -0
  179. package/src/client/index.ts +12 -0
  180. package/src/client/port.ts +78 -0
  181. package/src/client/protocol.ts +36 -0
  182. package/src/commands/admin.ts +308 -0
  183. package/src/commands/complete.ts +368 -0
  184. package/src/commands/dispatch.ts +106 -0
  185. package/src/commands/operate.ts +110 -0
  186. package/src/commands/operations.ts +524 -0
  187. package/src/commands/signal.ts +96 -0
  188. package/src/commands/start.ts +255 -0
  189. package/src/commands/submission.ts +51 -0
  190. package/src/core/channels.ts +14 -0
  191. package/src/core/context.ts +252 -0
  192. package/src/core/entities.ts +335 -0
  193. package/src/core/errors.ts +42 -0
  194. package/src/engine.ts +247 -0
  195. package/src/extensions.ts +231 -0
  196. package/src/index.ts +77 -0
  197. package/src/jobs/jobs.ts +320 -0
  198. package/src/notify/collect.ts +155 -0
  199. package/src/notify/inbox.ts +107 -0
  200. package/src/org/directory.ts +332 -0
  201. package/src/org/entities.ts +62 -0
  202. package/src/org/index.ts +21 -0
  203. package/src/proxy/proxies.ts +132 -0
  204. package/src/publish/project.ts +230 -0
  205. package/src/publish/publish.ts +314 -0
  206. package/src/queries/queries.ts +427 -0
  207. package/src/queries/stats.ts +207 -0
  208. package/src/runtime/assignees.ts +121 -0
  209. package/src/runtime/calls.ts +196 -0
  210. package/src/runtime/countersign.ts +83 -0
  211. package/src/runtime/execution.ts +915 -0
  212. package/src/runtime/next-steps.ts +213 -0
  213. package/src/runtime/state.ts +55 -0
  214. package/src/testing/scenarios.ts +95 -0
  215. package/src/testing/simulate.ts +190 -0
  216. package/src/testing/testing.ts +84 -0
  217. package/src/types.ts +286 -0
  218. package/src/views.ts +334 -0
  219. package/README.md +0 -3
@@ -0,0 +1,231 @@
1
+ /**
2
+ * 扩展点:做事的人、组织、处理人解析器、守卫、动作、计算值、自定义节点与会签规则,以及流程工程的 logic.ts 用的 defineLogic、
3
+ * test.ts 用的 defineScenarios(场景测试)。
4
+ * 只依赖模型包、不碰库与实体:流程代码(logic.ts)只用到这些,工作室在浏览器里的语言服务也只带上这个文件与模型包。
5
+ * 引擎的入口照常导出它们(types.ts、publish/project.ts 从这里导入)。
6
+ */
7
+ import type {
8
+ Duration,
9
+ FieldTypeChecks,
10
+ FormManifest,
11
+ FormValues,
12
+ } from '@zerodep-dev/flow-ts-model';
13
+
14
+ /** 做事的人:编号与他的角色、部门(判断能不能认领收件箱里的待办);admin 能做管理员的事 */
15
+ export interface Actor {
16
+ readonly id: string;
17
+ readonly name?: string;
18
+ readonly roles?: readonly string[];
19
+ readonly departments?: readonly string[];
20
+ /** 接入方扩展的种类(岗位、项目组……),写成“种类:编号” */
21
+ readonly groups?: readonly string[];
22
+ readonly admin?: boolean;
23
+ }
24
+
25
+ /** 组织:角色、部门、扩展种类里有哪些人(会签展开参与人、抄送时用) */
26
+ export interface FlowOrg {
27
+ members(
28
+ source:
29
+ { readonly role: string } | { readonly department: string } | { readonly group: string },
30
+ ): readonly string[] | Promise<readonly string[]>;
31
+ /**
32
+ * 收件箱的负责人(节点写了 `unclaimed: { action: 'assignByManager' }`,很久没人认领时由他指定承办人):
33
+ * 参数是收件箱的候选(角色、部门、扩展种类),不知道时返回 undefined
34
+ */
35
+ inboxManager?(inbox: {
36
+ readonly kind: 'role' | 'department' | 'group';
37
+ readonly value: string;
38
+ }): string | undefined | Promise<string | undefined>;
39
+ }
40
+
41
+ /** 流程变量的默认形状(没有单据类型时) */
42
+ export type Variables = Readonly<Record<string, unknown>>;
43
+
44
+ /** 扩展函数拿到的:实例、流程变量、按字段名取值;V 是单据的值(流程工程里由 form.ts 推出) */
45
+ export interface ExtensionContext<V extends object = Variables> {
46
+ readonly instance: {
47
+ readonly id: number;
48
+ readonly processKey: string;
49
+ readonly businessKey: string | null;
50
+ readonly startedBy: string;
51
+ };
52
+ readonly variables: Readonly<V>;
53
+ /** 按字段名取值:流程变量、`sys.名字`、`fn.名字` */
54
+ read<K extends keyof V & string>(field: K): V[K] | undefined;
55
+ read(field: string): unknown;
56
+ /** 定义里写的参数 */
57
+ readonly args: Readonly<Record<string, unknown>>;
58
+ }
59
+
60
+ /** 处理人解析器:返回处理人的编号 */
61
+ export type Resolver<V extends object = Variables> = (
62
+ context: ExtensionContext<V>,
63
+ ) => readonly string[] | Promise<readonly string[]>;
64
+
65
+ /** 守卫:提交前检查,返回 true 放行,返回文字是拒绝的原因 */
66
+ export type Guard<V extends object = Variables> = (
67
+ context: ExtensionContext<V> & {
68
+ readonly node: string;
69
+ readonly outcome: string;
70
+ readonly actor: Actor;
71
+ },
72
+ ) => true | string | Promise<true | string>;
73
+
74
+ /** 自动节点的动作:可以给出结果(按它选出边)、改流程变量 */
75
+ export type Action<V extends object = Variables> = (
76
+ context: ExtensionContext<V> & { readonly node: string },
77
+ ) =>
78
+ | void
79
+ | { readonly outcome?: string; readonly variables?: Readonly<Partial<V>> }
80
+ | Promise<void | { readonly outcome?: string; readonly variables?: Readonly<Partial<V>> }>;
81
+
82
+ /** 计算值(条件里的 `fn.名字`):同步,按当时的变量算 */
83
+ export type ComputedValue<V extends object = Variables> = (
84
+ context: Omit<ExtensionContext<V>, 'args'>,
85
+ ) => unknown;
86
+
87
+ /** 自定义节点做完之后怎样往下:按结果走(没写结果走没写结果的出边),顺带改流程变量;或停下来等一个外部事件 */
88
+ export interface CustomNodeResult<V extends object = Variables> {
89
+ readonly outcome?: string | null;
90
+ readonly variables?: Readonly<Partial<V>>;
91
+ /** 停下来等的事件名(由 engine.signal 送来);不等时不写 */
92
+ readonly waitFor?: string;
93
+ }
94
+
95
+ /** 自定义节点拿到的:扩展的现场,加上节点上除共同字段以外的属性(定义里写的原样) */
96
+ export type CustomNodeContext<V extends object = Variables> = Omit<ExtensionContext<V>, 'args'> & {
97
+ readonly node: string;
98
+ readonly attributes: Readonly<Record<string, unknown>>;
99
+ };
100
+
101
+ /** 自定义节点类型(定义里 `type: 'x-名字'`):到达时做什么、等的事件到了怎样往下 */
102
+ export interface CustomNode<V extends object = Variables> {
103
+ arrive(context: CustomNodeContext<V>): CustomNodeResult<V> | Promise<CustomNodeResult<V>>;
104
+ /** 等的事件到了;不写时按事件带的结果往下走 */
105
+ received?(
106
+ context: CustomNodeContext<V>,
107
+ event: { readonly outcome: string | null; readonly data: Readonly<Record<string, unknown>> },
108
+ ): CustomNodeResult<V> | Promise<CustomNodeResult<V>>;
109
+ }
110
+
111
+ /**
112
+ * 自定义会签规则(定义里 `multi.complete: '名字'`):每有一个人处理完就问一次,返回结果就按它结束(其余开着的取消),
113
+ * 返回 undefined 再等;都处理完还没有结果时按 fallback,没写时按最后这个人选的。参与人一起处理(不是依次)
114
+ */
115
+ export type CountersignRule = (context: {
116
+ readonly node: string;
117
+ /** 刚处理完的人选的结果 */
118
+ readonly chosen: string;
119
+ /** 这个节点这一轮的全部待办(含刚处理完的) */
120
+ readonly items: readonly {
121
+ readonly assignee: string | null;
122
+ readonly state: string;
123
+ readonly outcome: string | null;
124
+ readonly weight: number | null;
125
+ }[];
126
+ /** 还有人没处理完 */
127
+ readonly someoneOpen: boolean;
128
+ }) => string | undefined;
129
+
130
+ /** 接入方注册的扩展:定义里按名字引用 */
131
+ export interface FlowExtensions<V extends object = Variables> {
132
+ readonly resolvers?: Readonly<Record<string, Resolver<V>>>;
133
+ readonly guards?: Readonly<Record<string, Guard<V>>>;
134
+ readonly actions?: Readonly<Record<string, Action<V>>>;
135
+ readonly functions?: Readonly<Record<string, ComputedValue<V>>>;
136
+ /** 自定义节点类型:键是 `x-` 开头的类型名 */
137
+ readonly nodes?: Readonly<Record<string, CustomNode<V>>>;
138
+ /** 自定义会签规则:键是定义里 `multi.complete` 写的名字 */
139
+ readonly countersign?: Readonly<Record<string, CountersignRule>>;
140
+ /**
141
+ * 接入方注册的字段类型:键是清单里的 `type`,值查一个值合不合(返回问题的代号)。
142
+ * 发布时清单校验认得这些类型;发起、处理、暂存时按它查值
143
+ */
144
+ readonly fieldTypes?: FieldTypeChecks;
145
+ }
146
+
147
+ /** 流程代码里的逻辑:按种类分组,定义里写 `logic.名字` 引用 */
148
+ export type FlowLogic<V extends object = Variables> = FlowExtensions<V>;
149
+
150
+ /**
151
+ * 写 logic.ts:给了单据时 ctx.variables、ctx.read 按单据的类型来
152
+ * ```ts
153
+ * import form from './form';
154
+ * export default defineLogic(form, {
155
+ * guards: { budget: ({ variables }) => Number(variables.amount) > 1e5 ? '超出预算' : true },
156
+ * });
157
+ * ```
158
+ */
159
+ export function defineLogic<const L extends FlowLogic>(logic: L): L;
160
+ export function defineLogic<Form extends FormManifest, const L extends FlowLogic<FormValues<Form>>>(
161
+ form: Form,
162
+ logic: L,
163
+ ): L;
164
+ export function defineLogic(first: unknown, second?: unknown): unknown {
165
+ return second ?? first;
166
+ }
167
+
168
+ // ---------- 场景测试(流程工程的 test.ts)----------
169
+
170
+ /** 试运行的一步 */
171
+ export type SimulationStep =
172
+ /** 处理某个节点上开着的待办(以它的处理人或管理员的身份) */
173
+ | {
174
+ readonly node: string;
175
+ readonly outcome: string;
176
+ readonly variables?: Readonly<Record<string, unknown>>;
177
+ readonly comment?: string;
178
+ readonly returnTo?: string;
179
+ }
180
+ /** 时间往后拨,执行到点的作业(定时、时限、提醒、异步动作) */
181
+ | { readonly wait: Duration }
182
+ /** 外部事件 */
183
+ | {
184
+ readonly signal: string;
185
+ readonly outcome?: string;
186
+ readonly data?: Readonly<Record<string, unknown>>;
187
+ };
188
+
189
+ /** 一个场景期望的结果:写了的才核对 */
190
+ export interface ScenarioExpect {
191
+ /** 最后实例的状态 */
192
+ readonly status?: 'active' | 'completed' | 'terminated' | 'withdrawn' | 'suspended';
193
+ /** 结束时的结果(结束节点的 result、terminate 的 result) */
194
+ readonly result?: string;
195
+ /** 停在这些节点(开着的待办所在的,不论先后) */
196
+ readonly at?: readonly string[];
197
+ /** 等这些人处理(开着的待办的处理人,不论先后) */
198
+ readonly waitingFor?: readonly string[];
199
+ /** 在这一步出错(发起是第 0 步),错误里有这段文字;不写 error 时出错就算不通过 */
200
+ readonly error?: { readonly step?: number; readonly message?: string };
201
+ }
202
+
203
+ /** 一个场景:谁发起、单据填什么、一步步怎么处理、期望什么 */
204
+ export interface Scenario<V extends object = Variables> {
205
+ /** 发起人的编号;不写时由运行的地方定 */
206
+ readonly initiator?: string;
207
+ readonly variables?: Partial<V>;
208
+ readonly steps?: readonly SimulationStep[];
209
+ readonly expect: ScenarioExpect;
210
+ }
211
+
212
+ /** 场景名 → 场景 */
213
+ export type Scenarios<V extends object = Variables> = Readonly<Record<string, Scenario<V>>>;
214
+
215
+ /**
216
+ * 写 test.ts:给了单据时 variables 按单据的类型来
217
+ * ```ts
218
+ * import form from './form';
219
+ * export default defineScenarios(form, {
220
+ * '小额直接通过': { variables: { amount: '800' }, steps: [{ node: 'review', outcome: 'pass' }], expect: { status: 'completed' } },
221
+ * });
222
+ * ```
223
+ */
224
+ export function defineScenarios<const S extends Scenarios>(scenarios: S): S;
225
+ export function defineScenarios<
226
+ Form extends FormManifest,
227
+ const S extends Scenarios<FormValues<Form>>,
228
+ >(form: Form, scenarios: S): S;
229
+ export function defineScenarios(first: unknown, second?: unknown): unknown {
230
+ return second ?? first;
231
+ }
package/src/index.ts ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * 流程引擎:createFlowEngine 建引擎,engine.run(command, actor) 执行命令;设计见 packages/flow/docs/decisions/0001-design.md
3
+ */
4
+ export { createFlowEngine, type FlowEngine } from './engine.ts';
5
+ export type {
6
+ CcItem,
7
+ Incident,
8
+ InstanceActions,
9
+ InstanceDetail,
10
+ OutcomeView,
11
+ PublishOptions,
12
+ ReturnTarget,
13
+ StartView,
14
+ TodoItem,
15
+ TypedProcess,
16
+ CatalogEntry,
17
+ CheckResult,
18
+ MigrationCandidate,
19
+ NotificationView,
20
+ ProxyInput,
21
+ ProxyView,
22
+ FlowStats,
23
+ StatsFilter,
24
+ VersionInfo,
25
+ WorkItemDetail,
26
+ WorkItemField,
27
+ } from './views.ts';
28
+ export { FlowError, type FlowErrorCode } from './core/errors.ts';
29
+ export { FLOW_CHANNEL, ORG_CHANNEL } from './core/channels.ts';
30
+ export { flowEndpoint, type FlowEndpoint, type FlowEndpointOptions } from './client/endpoint.ts';
31
+ export { flowHttpHandler, httpTransport, type HttpTransportOptions } from './client/http.ts';
32
+ export {
33
+ createFlowClient,
34
+ portTransport,
35
+ servePort,
36
+ type DraftInput,
37
+ type FlowClient,
38
+ type FlowRequest,
39
+ type FlowResponse,
40
+ type FlowTransport,
41
+ type MessagePortLike,
42
+ } from './client/index.ts';
43
+ export { type NextStep, type PickPrompt, type Picks } from './runtime/next-steps.ts';
44
+ export {
45
+ FlowCc,
46
+ FlowDefinition,
47
+ FlowEvent,
48
+ FlowInstance,
49
+ FlowJob,
50
+ FlowNotification,
51
+ FlowProxy,
52
+ FlowWorkItem,
53
+ flowSchema,
54
+ type FlowDb,
55
+ } from './core/entities.ts';
56
+ export {
57
+ BUILTIN_OPERATIONS,
58
+ type OperationContext,
59
+ type OperationField,
60
+ type OperationScope,
61
+ type OperationView,
62
+ type WorkItemOperation,
63
+ } from './commands/operations.ts';
64
+ export { defineLogic, defineScenarios, type FlowLogic } from './extensions.ts';
65
+ export {
66
+ buildProject,
67
+ compileProject,
68
+ linkProject,
69
+ type CompiledProject,
70
+ type HostModule,
71
+ type HostModules,
72
+ type LinkedProject,
73
+ type TransformCode,
74
+ } from './publish/project.ts';
75
+ export type { RunState } from './runtime/state.ts';
76
+ export type { InstanceRow, WorkItemRow } from './runtime/execution.ts';
77
+ export type * from './types.ts';
@@ -0,0 +1,320 @@
1
+ /**
2
+ * 作业:定时与超时、异步的自动节点;领取(SKIP LOCKED)、重试、失败记成异常、手动重试与跳过。
3
+ */
4
+ import { or, type Row } from '@zerodep-dev/easy-query-ts';
5
+ import { type ProcessDefinition, type TaskNode } from '@zerodep-dev/flow-ts-model';
6
+ import { parseCandidate } from '../runtime/assignees.ts';
7
+ import { FlowInstance, FlowJob, FlowWorkItem } from '../core/entities.ts';
8
+ import { FlowError } from '../core/errors.ts';
9
+ import { dueAt, Execution } from '../runtime/execution.ts';
10
+ import type { Actor, FlowCommand, RunResult } from '../types.ts';
11
+ import type { EngineCore } from '../core/context.ts';
12
+ import type { Incident } from '../views.ts';
13
+
14
+ /** 作业最多试几次(第一次加两次重试) */
15
+ const MAX_ATTEMPTS = 3;
16
+
17
+ /** 领到的作业锁多久:进程死掉后别的进程过了这段时间能接手 */
18
+ const LEASE_MS = 5 * 60_000;
19
+
20
+ /** 跳过失败的自动节点时能选的结果:它的出边上写的结果 */
21
+ function skipOutcomes(definition: ProcessDefinition, node: string | null): string[] {
22
+ if (!node) return [];
23
+ const outcomes = definition.edges
24
+ .filter((e) => e.from === node && e.outcome)
25
+ .map((e) => e.outcome!);
26
+ return [...new Set(outcomes)];
27
+ }
28
+
29
+ /** 时刻写成 ISO 文字,整秒时不带毫秒(同线上的写法) */
30
+ const isoSeconds = (at: Date): string => at.toISOString().replace('.000Z', 'Z');
31
+
32
+ /** 作业:装进引擎核心(core.jobs),别的模块经它调用 */
33
+ export function createJobs(core: EngineCore) {
34
+ const { options, db, now, definitionOf, withInstance, execution } = core;
35
+
36
+ /** 这个引擎的作业租约名:多个进程、多个标签页各不相同 */
37
+ const workerId = `worker-${crypto.randomUUID().slice(0, 8)}`;
38
+
39
+ async function runDue({ limit = 50, worker = workerId } = {}): Promise<number> {
40
+ const at = now();
41
+ // 一次抢一批:别人锁着的行跳过(SKIP LOCKED),各拿各的;租约写在行上,进程中途退出时租约过期后别人再抢
42
+ const due = await db.transaction(async (tx) => {
43
+ const rows = await tx
44
+ .queryable(FlowJob)
45
+ .where((j) => [
46
+ j.state.eq('pending'),
47
+ j.dueAt.le(at),
48
+ or(j.lockedUntil.isNull(), j.lockedUntil.lt(at)),
49
+ ])
50
+ .orderBy((j) => j.dueAt)
51
+ .limit(limit)
52
+ .forUpdateSkipLocked()
53
+ .toList();
54
+ if (rows.length > 0) {
55
+ await tx
56
+ .update(FlowJob)
57
+ .set({ lockedBy: worker, lockedUntil: new Date(at.getTime() + LEASE_MS) })
58
+ .where((j) => j.id.in(rows.map((row) => row.id)))
59
+ .execute();
60
+ }
61
+ return rows;
62
+ });
63
+ // 发件箱里没送到的通知:每次跑作业顺带再试
64
+ await core.notifications.deliverPending();
65
+ let ran = 0;
66
+ for (const job of due) {
67
+ try {
68
+ await withInstance(job.instanceId, null, async (exec, tx) => {
69
+ // 暂停的实例:作业往后推一小时,恢复后再做
70
+ if (exec.status === 'suspended') {
71
+ await tx
72
+ .update(FlowJob)
73
+ .set({ dueAt: new Date(at.getTime() + 3_600_000), lockedBy: null, lockedUntil: null })
74
+ .where((j) => j.id.eq(job.id))
75
+ .execute();
76
+ return;
77
+ }
78
+ await tx
79
+ .delete(FlowJob)
80
+ .where((j) => j.id.eq(job.id))
81
+ .execute();
82
+ await runJob(exec, job);
83
+ });
84
+ } catch (error) {
85
+ await jobFailed(job, error, at);
86
+ }
87
+ ran++;
88
+ }
89
+ return ran;
90
+ }
91
+
92
+ /** 一个作业:节点还在等、轮次没变才做 */
93
+ async function runJob(exec: Execution, job: Row<typeof FlowJob>) {
94
+ const node = job.node;
95
+ if (exec.status !== 'active' || !node || !exec.current.has(node)) return;
96
+ if (job.round !== null && exec.state.rounds[node] !== job.round) return;
97
+ if (job.kind === 'timer') {
98
+ exec.current.delete(node);
99
+ return exec.leave(node);
100
+ }
101
+ if (job.kind === 'action') {
102
+ const result = await exec.callAction(node);
103
+ exec.current.delete(node);
104
+ return exec.leave(node, result?.outcome ?? null);
105
+ }
106
+ if (job.kind === 'receiveTimeout') {
107
+ const waiting = exec.node(node);
108
+ if (waiting.type !== 'receive') return;
109
+ exec.addEvent('node.overdue', { node, actor: null, data: { dueAt: isoSeconds(job.dueAt) } });
110
+ if (waiting.overdue?.action === 'complete') {
111
+ exec.current.delete(node);
112
+ return exec.leave(node, waiting.overdue.outcome);
113
+ }
114
+ return;
115
+ }
116
+ if (job.kind === 'overdue' || job.kind === 'remind' || job.kind === 'unclaimed') {
117
+ return runDeadline(exec, job);
118
+ }
119
+ throw new FlowError('invalid-definition', `不认识的作业 ${job.kind}`);
120
+ }
121
+
122
+ /** 时限与提醒:待办还开着才做;超时按节点的 overdue 记一笔或自动处理 */
123
+ async function runDeadline(exec: Execution, job: Row<typeof FlowJob>) {
124
+ const item =
125
+ job.workItemId === null
126
+ ? undefined
127
+ : await exec.tx.queryable(FlowWorkItem).find(job.workItemId);
128
+ if (!item || item.state !== 'open') return;
129
+ const node = exec.node(item.node) as TaskNode;
130
+ const fields = { workItemId: item.id, node: node.id, actor: null };
131
+ if (job.kind === 'remind') {
132
+ exec.addEvent('workItem.reminded', {
133
+ ...fields,
134
+ data: { auto: true, reason: job.payload['reason'] },
135
+ });
136
+ return;
137
+ }
138
+ if (job.kind === 'unclaimed') {
139
+ if (item.assignee) return;
140
+ if (node.unclaimed?.action === 'assignByManager') {
141
+ // 转收件箱的负责人指定:记下负责人,进他的“待我指定”(不知道负责人时只记一笔)
142
+ const inbox = item.candidates
143
+ .filter((token) => !token.startsWith('-'))
144
+ .map(parseCandidate)
145
+ .find((c) => c.kind !== 'user');
146
+ const manager =
147
+ inbox && options.org?.inboxManager
148
+ ? await options.org.inboxManager(
149
+ inbox as Parameters<typeof options.org.inboxManager>[0],
150
+ )
151
+ : undefined;
152
+ await exec.tx
153
+ .update(FlowWorkItem)
154
+ .set({ designator: manager ?? null, awaitingDesignation: manager !== undefined })
155
+ .where((w) => [w.id.eq(item.id), w.state.eq('open'), w.assignee.isNull()])
156
+ .execute();
157
+ exec.addEvent('workItem.unclaimed', {
158
+ ...fields,
159
+ data: manager ? { designator: manager } : null,
160
+ });
161
+ return;
162
+ }
163
+ exec.addEvent('workItem.reminded', { ...fields, data: { auto: true, reason: 'unclaimed' } });
164
+ return;
165
+ }
166
+ exec.addEvent('workItem.overdue', {
167
+ ...fields,
168
+ data: { dueAt: item.dueAt ? isoSeconds(item.dueAt) : null },
169
+ });
170
+ if (node.overdue?.action === 'complete') {
171
+ await core.tasks.finishItem(exec, exec.tx, item, node, node.overdue.outcome, {
172
+ actor: null,
173
+ comment: null,
174
+ });
175
+ }
176
+ }
177
+
178
+ /** 作业失败:回滚了它的事务,这里记次数与错误,按 n² 分钟重试,用完标失败 */
179
+ /**
180
+ * 作业失败:它的事务已经回滚,这里另开事务记次数与错误。异步的自动节点按 retry.times 重试(间隔 retry.backoff,
181
+ * 不写时 n² 分钟),其余作业试 MAX_ATTEMPTS 次;用完标 failed、记 job.failed(data 里有作业编号),
182
+ * 自动节点写了 onFailure: 'error' 时同时暂停实例
183
+ */
184
+ async function jobFailed(job: Row<typeof FlowJob>, error: unknown, at: Date) {
185
+ const attempts = job.attempts + 1;
186
+ const message = error instanceof Error ? error.message : String(error);
187
+ await db.transaction(async (tx) => {
188
+ const instance = await tx.queryable(FlowInstance).find(job.instanceId);
189
+ const definition = instance ? await definitionOf(tx, instance.definitionId) : undefined;
190
+ const node = job.node ? definition?.nodes.find((n) => n.id === job.node) : undefined;
191
+ const service = job.kind === 'action' && node?.type === 'service' ? node : undefined;
192
+ const maxAttempts = service ? (service.retry?.times ?? 0) + 1 : MAX_ATTEMPTS;
193
+ const gaveUp = attempts >= maxAttempts;
194
+ const backoff = service?.retry?.backoff;
195
+ const delay = backoff
196
+ ? dueAt(backoff, at, () => undefined, options).getTime() - at.getTime()
197
+ : attempts * attempts * 60_000;
198
+ await tx
199
+ .update(FlowJob)
200
+ .set({
201
+ attempts,
202
+ lastError: message.slice(0, 2000),
203
+ lockedBy: null,
204
+ lockedUntil: null,
205
+ state: gaveUp ? 'failed' : 'pending',
206
+ dueAt: new Date(at.getTime() + delay),
207
+ })
208
+ .where((j) => j.id.eq(job.id))
209
+ .execute();
210
+ if (!gaveUp || !instance || !definition) return;
211
+ await tx.lock(FlowInstance, instance.id);
212
+ const row = await tx.queryable(FlowInstance).findOrThrow(instance.id);
213
+ const exec = await execution(tx, definition, row, null);
214
+ exec.addEvent('job.failed', {
215
+ node: job.node,
216
+ actor: null,
217
+ data: { jobId: job.id, kind: job.kind, error: message.slice(0, 500) },
218
+ });
219
+ if (service?.onFailure === 'error' && exec.status === 'active') {
220
+ exec.status = 'suspended';
221
+ exec.addEvent('instance.suspended', { actor: null, data: { reason: 'job.failed' } });
222
+ }
223
+ await exec.flush();
224
+ });
225
+ }
226
+
227
+ /** 失败的作业(异常):带节点、能不能跳过、能选的结果 */
228
+ async function incidents(instance?: number): Promise<Incident[]> {
229
+ const jobs = await db
230
+ .queryable(FlowJob)
231
+ .where((j) => [
232
+ j.state.eq('failed'),
233
+ ...(instance !== undefined ? [j.instanceId.eq(instance)] : []),
234
+ ])
235
+ .orderBy((j) => j.id)
236
+ .toList();
237
+ const rows: Incident[] = [];
238
+ for (const job of jobs) {
239
+ const row = await db.queryable(FlowInstance).findOrThrow(job.instanceId);
240
+ const definition = await definitionOf(db, row.definitionId);
241
+ const node = job.node ? definition.nodes.find((n) => n.id === job.node) : undefined;
242
+ rows.push({
243
+ jobId: job.id,
244
+ instanceId: job.instanceId,
245
+ instanceTitle: row.title,
246
+ kind: job.kind,
247
+ node: job.node,
248
+ nodeName: node?.name ?? null,
249
+ attempts: job.attempts,
250
+ error: job.lastError,
251
+ skippable: job.kind === 'action',
252
+ outcomes: skipOutcomes(definition, job.node),
253
+ });
254
+ }
255
+ return rows;
256
+ }
257
+
258
+ /** 重试失败的作业:回到待执行,马上到点(谁能重试由接入方在接口层或 intercept 里管) */
259
+ async function retryJob(id: number, _actor: Actor): Promise<boolean> {
260
+ const revived = await db
261
+ .update(FlowJob)
262
+ .set({ state: 'pending', attempts: 0, dueAt: now(), lockedBy: null, lockedUntil: null })
263
+ .where((j) => [j.id.eq(id), j.state.eq('failed')])
264
+ .execute();
265
+ if (revived === 0) throw new FlowError('not-found', `没有失败的作业 ${id}`);
266
+ return true;
267
+ }
268
+
269
+ /** 管理员跳过失败的异步动作:按指定的结果往下走(结果要是这个节点出边上写的) */
270
+ async function skipJob(
271
+ command: Extract<FlowCommand, { type: 'skipJob' }>,
272
+ actor: Actor,
273
+ ): Promise<RunResult> {
274
+ if (!actor.admin) throw new FlowError('forbidden', '只有管理员能跳过作业');
275
+ const job = await db.queryable(FlowJob).find(command.job);
276
+ if (!job || job.state !== 'failed' || job.kind !== 'action' || !job.node) {
277
+ throw new FlowError('not-found', `没有能跳过的失败作业 ${command.job}`);
278
+ }
279
+ const node = job.node;
280
+ return withInstance(
281
+ job.instanceId,
282
+ actor,
283
+ async (exec, tx) => {
284
+ if (exec.status !== 'active') {
285
+ throw new FlowError('instance-not-active', `实例 ${job.instanceId} 不在进行中`);
286
+ }
287
+ const outcomes = skipOutcomes(exec.definition, node);
288
+ if (!command.outcome && outcomes.length > 0) {
289
+ throw new FlowError('invalid-input', '跳过要选结果', {
290
+ field: 'outcome',
291
+ code: 'required',
292
+ });
293
+ }
294
+ if (command.outcome && !outcomes.includes(command.outcome)) {
295
+ throw new FlowError('invalid-input', `${node} 的出边上没有结果 ${command.outcome}`, {
296
+ field: 'outcome',
297
+ code: 'unknown-outcome',
298
+ });
299
+ }
300
+ await tx
301
+ .delete(FlowJob)
302
+ .where((j) => j.id.eq(job.id))
303
+ .execute();
304
+ exec.current.delete(node);
305
+ exec.addEvent('job.skipped', {
306
+ node,
307
+ outcome: command.outcome ?? null,
308
+ comment: command.reason ?? null,
309
+ });
310
+ await exec.leave(node, command.outcome ?? null);
311
+ },
312
+ command,
313
+ );
314
+ }
315
+
316
+ return { runDue, runJob, runDeadline, jobFailed, incidents, retryJob, skipJob };
317
+ }
318
+
319
+ /** createJobs 给出的函数 */
320
+ export type Jobs = ReturnType<typeof createJobs>;