@zerodep-dev/flow-ts-engine 0.0.0-stage → 1.0.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 +202 -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,335 @@
1
+ /**
2
+ * 引擎的表(docs/decisions/0001 第 4 节),用 easy-query 的实体写,只认 PostgreSQL(PGlite 同样可用),按 PG 的习惯建:
3
+ * - 主键 bigint 自增;文字一律 text(PG 里 varchar(n) 不更快,长度上限只会误伤);时刻一律 timestamptz(绝对时刻,不受会话时区影响);
4
+ * - 状态用 PG 的原生枚举;定义、变量、运行状态、事件数据是 jsonb,候选人与正在处理的节点是 text[];
5
+ * - 开着的待办、到期的作业是部分索引,候选人与单据数据是 GIN 索引;
6
+ * - 表之间只有逻辑外键(实体的关系),不建库里的外键约束:实例、待办、事件只追加或由引擎自己维护,删数据由归档做。
7
+ * 接入方的数据库里由 `engine.createTables()` 建(开发、测试)或自己的迁移脚本建(生产)
8
+ */
9
+ import { col, defineSchema, entity, type Db } from '@zerodep-dev/easy-query-ts';
10
+ import type { ProcessDefinition } from '@zerodep-dev/flow-ts-model';
11
+ import type { RunState } from '../runtime/state.ts';
12
+
13
+ /** 文字列:PG 的 text */
14
+ const text = () => col.string().dbType('text');
15
+
16
+ /** 时刻列:PG 的 timestamptz */
17
+ const instant = () => col.datetime({ timeZone: true });
18
+
19
+ /** 已发布的版本:一行一个版本,发布后不改(只有 enabled 会变);流程工程的版本带着全部源码与编译结果 */
20
+ export const FlowDefinition = entity(
21
+ 'flow_definition',
22
+ {
23
+ id: col.bigint().primaryKey().generated(),
24
+ processKey: text(),
25
+ version: col.int(),
26
+ name: text(),
27
+ // json 不是 jsonb:jsonb 按键的长短、字母重排对象的键,单据字段的先后(清单里键的顺序)就丢了
28
+ model: col.json().$type<ProcessDefinition>().dbType('json'),
29
+ enabled: col.boolean(),
30
+ publishedBy: text().nullable(),
31
+ publishedAt: instant(),
32
+ /** 发布说明 */
33
+ note: text().nullable(),
34
+ /** 流程工程的源码(路径 → 源码);只发布了定义时为空 */
35
+ files: col.json().$type<Record<string, string>>().nullable(),
36
+ /** 编译好的模块(路径 → JS),执行时加载 */
37
+ modules: col.json().$type<Record<string, string>>().nullable(),
38
+ },
39
+ {
40
+ comment: '流程的已发布版本',
41
+ indexes: [{ columns: ['processKey', 'version'], unique: true }],
42
+ },
43
+ );
44
+
45
+ /** 实例的状态 */
46
+ export const INSTANCE_STATUSES = [
47
+ /** 发起前存的草稿:不进流程,只有发起人看得到 */
48
+ 'draft',
49
+ 'active',
50
+ 'suspended',
51
+ 'completed',
52
+ 'terminated',
53
+ 'withdrawn',
54
+ ] as const;
55
+
56
+ /** 流程实例;rev 每个命令加一(前端据此知道看到的是不是最新) */
57
+ export const FlowInstance = entity(
58
+ 'flow_instance',
59
+ {
60
+ id: col.bigint().primaryKey().generated(),
61
+ definitionId: col.bigint(),
62
+ processKey: text(),
63
+ version: col.int(),
64
+ businessKey: text().nullable(),
65
+ title: text().nullable(),
66
+ status: col.enum(INSTANCE_STATUSES).native('flow_instance_status'),
67
+ result: text().nullable(),
68
+ /** 正在处理的节点 */
69
+ current: col.array(text()),
70
+ /** 单据的值(流程变量) */
71
+ variables: col.json().$type<Record<string, unknown>>(),
72
+ state: col.json().$type<RunState>(),
73
+ startedBy: text(),
74
+ startedAt: instant(),
75
+ endedAt: instant().nullable(),
76
+ /** 调用它的父实例与节点(调用流程) */
77
+ parentId: col.bigint().nullable(),
78
+ parentNode: text().nullable(),
79
+ /** 调用节点在父实例里的第几轮(退回、跳转后重新进入调用节点时,旧一轮的子实例不算) */
80
+ parentRound: col.int().nullable(),
81
+ rev: col.int(),
82
+ },
83
+ {
84
+ comment: '流程实例',
85
+ indexes: [
86
+ { columns: ['startedBy', 'startedAt'] },
87
+ { columns: ['processKey', 'status'] },
88
+ { columns: ['businessKey'], where: 'business_key IS NOT NULL' },
89
+ { columns: ['parentId'], where: 'parent_id IS NOT NULL' },
90
+ // 按单据字段查(报表、按金额筛待办):variables @> '{"amount": …}'
91
+ { columns: ['variables'], using: 'gin' },
92
+ ],
93
+ },
94
+ );
95
+
96
+ /** 待办的状态:open 等人处理,waiting 在等加签的人办完,done 处理了,canceled 不用处理了 */
97
+ export const WORK_ITEM_STATES = ['open', 'waiting', 'done', 'canceled'] as const;
98
+
99
+ /** 落到谁:pool 收件箱里等认领,claimed 认领了,direct 直接落到人,designated 收件箱的负责人指定的 */
100
+ export const ASSIGNMENTS = ['pool', 'claimed', 'direct', 'designated'] as const;
101
+
102
+ /**
103
+ * 待办:单表加状态,不拆历史表。收件箱的候选存成标记数组(`user:1001`、`role:finance`、`department:d1`、`group:岗位:p1`),
104
+ * 查待办是 `candidates && 这个人的标记`,走 GIN 索引不连表;改派、加签只改这一列
105
+ */
106
+ export const FlowWorkItem = entity(
107
+ 'flow_work_item',
108
+ {
109
+ id: col.bigint().primaryKey().generated(),
110
+ instanceId: col.bigint(),
111
+ node: text(),
112
+ nodeName: text(),
113
+ /** 这个节点第几轮(退回、循环后再到这里加一) */
114
+ round: col.int(),
115
+ state: col.enum(WORK_ITEM_STATES).native('flow_work_item_state'),
116
+ assignment: col.enum(ASSIGNMENTS).native('flow_assignment'),
117
+ /** 处理人;收件箱里还没人认领时为空 */
118
+ assignee: text().nullable(),
119
+ /** 怎样来的:start、forward、return、transfer…… */
120
+ arrival: text(),
121
+ /** 会签:同一节点同一轮的待办是一组,seq 是第几个参与人 */
122
+ signGroup: text().nullable(),
123
+ signSeq: col.int().nullable(),
124
+ createdAt: instant(),
125
+ dueAt: instant().nullable(),
126
+ completedAt: instant().nullable(),
127
+ completedBy: text().nullable(),
128
+ outcome: text().nullable(),
129
+ comment: text().nullable(),
130
+ /** 收件箱的候选标记;直接落到人的待办是空数组 */
131
+ candidates: col.array(text()),
132
+ /** 收件箱的负责人:很久没人认领、或被指定的人申请改派时由他指定承办人 */
133
+ designator: text().nullable(),
134
+ /** 在等负责人指定(他的“待我指定”);申请改派时处理人不变,重新指定之前仍由他处理 */
135
+ awaitingDesignation: col.boolean(),
136
+ /** 票签的票数:只有 votes 规则的会签待办有,别处为空 */
137
+ weight: col.int().nullable(),
138
+ /** 上次催办的时刻:同一份待办一小时内只催一次 */
139
+ remindedAt: instant().nullable(),
140
+ /** 转办、改派:从谁手里交过来的 */
141
+ fromUser: text().nullable(),
142
+ /** 代理:本该是谁的(他设了代理,到达时交给了代理人 assignee,docs/decisions/0010 第 3 节) */
143
+ proxyFor: text().nullable(),
144
+ /** 加签、委托:是哪一份待办加的(arrival 是 delegate、addSign.before / after) */
145
+ parentItemId: col.bigint().nullable(),
146
+ /** 后加签:处理人选的结果先挂在这里,加签的人都办完才生效 */
147
+ pendingOutcome: text().nullable(),
148
+ /** 处理前暂存的单据值与意见(只有处理人看得到,处理完清掉) */
149
+ draft: col
150
+ .json()
151
+ .$type<{ values: Record<string, unknown>; comment: string | null }>()
152
+ .nullable(),
153
+ },
154
+ {
155
+ comment: '待办',
156
+ indexes: [
157
+ { columns: ['instanceId'] },
158
+ { columns: ['assignee'], where: "state = 'open'" },
159
+ { columns: ['candidates'], using: 'gin', where: "state = 'open'" },
160
+ { columns: ['completedBy', 'completedAt'], where: "state = 'done'" },
161
+ { columns: ['designator'], where: 'awaiting_designation' },
162
+ { columns: ['parentItemId'], where: 'parent_item_id IS NOT NULL' },
163
+ ],
164
+ },
165
+ );
166
+
167
+ /** 流转记录:只追加 */
168
+ export const FlowEvent = entity(
169
+ 'flow_event',
170
+ {
171
+ id: col.bigint().primaryKey().generated(),
172
+ instanceId: col.bigint(),
173
+ workItemId: col.bigint().nullable(),
174
+ type: text(),
175
+ at: instant(),
176
+ actor: text().nullable(),
177
+ node: text().nullable(),
178
+ edge: text().nullable(),
179
+ outcome: text().nullable(),
180
+ comment: text().nullable(),
181
+ data: col.json().$type<Record<string, unknown>>().nullable(),
182
+ },
183
+ // 时间线按实例取、按编号排:一个索引两件事都管
184
+ { comment: '流转记录(只追加)', indexes: [{ columns: ['instanceId', 'id'] }] },
185
+ );
186
+
187
+ /** 作业的状态 */
188
+ export const JOB_STATES = ['pending', 'failed'] as const;
189
+
190
+ /** 作业:定时、时限、提醒、异步的自动节点;多个进程用 FOR UPDATE SKIP LOCKED 各抢各的,租约过期的可以再抢 */
191
+ export const FlowJob = entity(
192
+ 'flow_job',
193
+ {
194
+ id: col.bigint().primaryKey().generated(),
195
+ kind: text(),
196
+ instanceId: col.bigint(),
197
+ workItemId: col.bigint().nullable(),
198
+ /** 排它时节点在第几轮:节点重新到达后,旧的作业不再生效 */
199
+ node: text().nullable(),
200
+ round: col.int().nullable(),
201
+ dueAt: instant(),
202
+ payload: col.json().$type<Record<string, unknown>>(),
203
+ attempts: col.int(),
204
+ state: col.enum(JOB_STATES).native('flow_job_state'),
205
+ lockedBy: text().nullable(),
206
+ lockedUntil: instant().nullable(),
207
+ lastError: text().nullable(),
208
+ },
209
+ {
210
+ comment: '作业(定时、时限、提醒、异步动作)',
211
+ indexes: [
212
+ { columns: ['dueAt'], where: "state = 'pending'" },
213
+ { columns: ['instanceId'] },
214
+ { columns: ['id'], where: "state = 'failed'", name: 'flow_job_failed_idx' },
215
+ ],
216
+ },
217
+ );
218
+
219
+ /**
220
+ * 通知:站内信箱兼发件箱(docs/decisions/0010)。与推进同一个事务写入,所以“提交了才有通知”;
221
+ * readAt 是收件人读过,sentAt 是外部投递(邮件、IM,引擎选项的 notifications.deliver)送到了,没送到的到点作业重试。
222
+ * 只存事件与当时的标题、环节名,文案由界面按事件拼(语言包);流程配了模板时 message 是渲染好的文字
223
+ */
224
+ export const FlowNotification = entity(
225
+ 'flow_notification',
226
+ {
227
+ id: col.bigint().primaryKey().generated(),
228
+ recipient: text(),
229
+ /** 到达、退回、催办、快到期、超时、抄送、结束(模型包的 NotifyEvent) */
230
+ event: text(),
231
+ instanceId: col.bigint(),
232
+ workItemId: col.bigint().nullable(),
233
+ node: text().nullable(),
234
+ nodeName: text().nullable(),
235
+ processKey: text(),
236
+ /** 当时实例的标题 */
237
+ title: text().nullable(),
238
+ /** 流程配了模板时渲染好的文字 */
239
+ message: text().nullable(),
240
+ /** 谁的动作引起的(催办的人、抄送的人);作业、系统引起的为空 */
241
+ sender: text().nullable(),
242
+ createdAt: instant(),
243
+ readAt: instant().nullable(),
244
+ sentAt: instant().nullable(),
245
+ attempts: col.int(),
246
+ lastError: text().nullable(),
247
+ },
248
+ {
249
+ comment: '通知(站内信箱兼发件箱)',
250
+ indexes: [
251
+ { columns: ['recipient', 'id'] },
252
+ { columns: ['recipient'], where: 'read_at IS NULL' },
253
+ { columns: ['id'], where: 'sent_at IS NULL' },
254
+ ],
255
+ },
256
+ );
257
+
258
+ /**
259
+ * 代理规则(docs/decisions/0010 第 3 节):principal 不在的这段时间(startsAt 到 endsAt,结束为空是一直到撤销),
260
+ * 这些流程(processKeys 为空是全部)新到他手上的待办交给 agent
261
+ */
262
+ export const FlowProxy = entity(
263
+ 'flow_proxy',
264
+ {
265
+ id: col.bigint().primaryKey().generated(),
266
+ principal: text(),
267
+ agent: text(),
268
+ processKeys: col.array(text()),
269
+ startsAt: instant(),
270
+ endsAt: instant().nullable(),
271
+ note: text().nullable(),
272
+ createdAt: instant(),
273
+ /** 谁设的(本人,或替他设的管理员) */
274
+ createdBy: text(),
275
+ cancelledAt: instant().nullable(),
276
+ },
277
+ {
278
+ comment: '代理规则',
279
+ indexes: [
280
+ { columns: ['principal'], where: 'cancelled_at IS NULL' },
281
+ { columns: ['agent'], where: 'cancelled_at IS NULL' },
282
+ ],
283
+ },
284
+ );
285
+
286
+ /** 抄送 */
287
+ export const FlowCc = entity(
288
+ 'flow_cc',
289
+ {
290
+ id: col.bigint().primaryKey().generated(),
291
+ instanceId: col.bigint(),
292
+ /** 抄送节点;手动抄送时为空 */
293
+ node: text().nullable(),
294
+ recipient: text(),
295
+ /** 谁抄送的;抄送节点时为空 */
296
+ sender: text().nullable(),
297
+ message: text().nullable(),
298
+ at: instant(),
299
+ readAt: instant().nullable(),
300
+ },
301
+ { comment: '抄送', indexes: [{ columns: ['recipient', 'id'] }, { columns: ['instanceId'] }] },
302
+ );
303
+
304
+ /** 引擎的 schema;关联是逻辑外键(只在查询里导航,库里不建约束) */
305
+ export const flowSchema = defineSchema(
306
+ {
307
+ FlowDefinition,
308
+ FlowInstance,
309
+ FlowWorkItem,
310
+ FlowEvent,
311
+ FlowJob,
312
+ FlowCc,
313
+ FlowNotification,
314
+ FlowProxy,
315
+ },
316
+ {
317
+ FlowInstance: (r) => ({
318
+ definition: r.one('FlowDefinition', { from: 'definitionId', to: 'id' }),
319
+ parent: r.one('FlowInstance', { from: 'parentId', to: 'id' }),
320
+ }),
321
+ FlowWorkItem: (r) => ({
322
+ instance: r.one('FlowInstance', { from: 'instanceId', to: 'id' }),
323
+ parentItem: r.one('FlowWorkItem', { from: 'parentItemId', to: 'id' }),
324
+ }),
325
+ FlowEvent: (r) => ({ instance: r.one('FlowInstance', { from: 'instanceId', to: 'id' }) }),
326
+ FlowJob: (r) => ({ instance: r.one('FlowInstance', { from: 'instanceId', to: 'id' }) }),
327
+ FlowCc: (r) => ({ instance: r.one('FlowInstance', { from: 'instanceId', to: 'id' }) }),
328
+ FlowNotification: (r) => ({
329
+ instance: r.one('FlowInstance', { from: 'instanceId', to: 'id' }),
330
+ }),
331
+ },
332
+ );
333
+
334
+ /** 引擎用的 Db */
335
+ export type FlowDb = Db<typeof flowSchema>;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * 引擎的错误:带代号,HTTP 适配器按代号给状态码,界面按代号给提示
3
+ *
4
+ * try { await engine.run(command, actor) } catch (error) { if (error instanceof FlowError && error.code === 'already-handled') … }
5
+ */
6
+
7
+ /** 错误的代号 */
8
+ export type FlowErrorCode =
9
+ /** 找不到流程、实例、待办 */
10
+ | 'not-found'
11
+ /** 待办已经处理过、取消了,或被别人认领了 */
12
+ | 'already-handled'
13
+ /** 实例已经结束或暂停 */
14
+ | 'instance-not-active'
15
+ /** 这个人不能做这件事:不是候选人、不是发起人、没有权限 */
16
+ | 'forbidden'
17
+ /** 命令的参数不对:结果不在节点上、意见必填…… */
18
+ | 'invalid-input'
19
+ /** 流程定义有错(发布时校验不过,或推进时选不出边) */
20
+ | 'invalid-definition'
21
+ /** 处理人解析不出来,且节点要求报错 */
22
+ | 'no-assignee'
23
+ /** 守卫拒绝了这次提交 */
24
+ | 'guard-rejected'
25
+ /** 接入方的扩展(同步的动作)出错 */
26
+ | 'extension-failed'
27
+ /** 引擎之外的错误(客户端经端点收到的:数据库连不上、程序出错) */
28
+ | 'internal';
29
+
30
+ /** 引擎的错误 */
31
+ export class FlowError extends Error {
32
+ readonly code: FlowErrorCode;
33
+ /** 附加信息:校验问题、哪个字段…… */
34
+ readonly details: Readonly<Record<string, unknown>>;
35
+
36
+ constructor(code: FlowErrorCode, message: string, details: Record<string, unknown> = {}) {
37
+ super(message);
38
+ this.name = 'FlowError';
39
+ this.code = code;
40
+ this.details = details;
41
+ }
42
+ }
package/src/engine.ts ADDED
@@ -0,0 +1,247 @@
1
+ /**
2
+ * 流程引擎(docs/decisions/0001 第 5 节):一个入口 run(command, actor),每个命令一个事务,第一条语句锁住实例行;
3
+ * 查询(待办、已办、实例详情)与作业(定时、异步的自动节点)也从这里给出。
4
+ *
5
+ * 这个文件只放对外的接口 FlowEngine 与组装:引擎核心在 core/context.ts,各部分按职责分在
6
+ * commands/(发起、处理、动作、实例操作、外部消息、命令分发)、runtime/(推进现场、处理人、会签、调用流程、预测下一步)、
7
+ * publish/(发布与版本、流程工程)、queries/(查询)、jobs/(作业)。
8
+ *
9
+ * const engine = createFlowEngine({ adapter: pglite(db), org, extensions });
10
+ * await engine.createTables();
11
+ * await engine.publish(purchase);
12
+ * const { workItems } = await engine.run({ type: 'start', process: 'purchase', variables: { amount: 120 } }, alice);
13
+ * await engine.run({ type: 'complete', workItem: workItems[0].id, outcome: 'approve' }, bob);
14
+ */
15
+ import {
16
+ type FlowProject,
17
+ type FormManifest,
18
+ type FormValues,
19
+ type ProcessDefinition,
20
+ } from '@zerodep-dev/flow-ts-model';
21
+ import { FlowCc, type FlowDb } from './core/entities.ts';
22
+ import { type InstanceRow } from './runtime/execution.ts';
23
+ import type {
24
+ Actor,
25
+ BatchResult,
26
+ FlowCommand,
27
+ InstanceSearch,
28
+ ListFilter,
29
+ ResultPage,
30
+ FlowEngineOptions,
31
+ RunResult,
32
+ SignalInput,
33
+ } from './types.ts';
34
+ import { createCore } from './core/context.ts';
35
+ import { createCalls } from './runtime/calls.ts';
36
+ import { createStarts } from './commands/start.ts';
37
+ import { createTasks } from './commands/complete.ts';
38
+ import { createOps } from './commands/operate.ts';
39
+ import { createAdmin } from './commands/admin.ts';
40
+ import { createSignals } from './commands/signal.ts';
41
+ import { createCommands } from './commands/dispatch.ts';
42
+ import { createPublishing } from './publish/publish.ts';
43
+ import { createQueries } from './queries/queries.ts';
44
+ import { createJobs } from './jobs/jobs.ts';
45
+ import { createNotifications } from './notify/inbox.ts';
46
+ import { createProxies } from './proxy/proxies.ts';
47
+ import { createStats } from './queries/stats.ts';
48
+ import type {
49
+ TodoItem,
50
+ WorkItemDetail,
51
+ StartView,
52
+ CcItem,
53
+ Incident,
54
+ InstanceDetail,
55
+ PublishOptions,
56
+ CatalogEntry,
57
+ CheckResult,
58
+ MigrationCandidate,
59
+ NotificationView,
60
+ ProxyInput,
61
+ ProxyView,
62
+ FlowStats,
63
+ StatsFilter,
64
+ VersionInfo,
65
+ TypedProcess,
66
+ } from './views.ts';
67
+
68
+ /** 流程引擎 */
69
+ export interface FlowEngine {
70
+ /** 建引擎的表(开发、测试;生产用自己的迁移脚本) */
71
+ createTables(): Promise<void>;
72
+ /**
73
+ * 发布一个版本:流程定义,或流程工程(编译、加载、单据并进变量、类型检查)。
74
+ * 校验不过报 invalid-definition:details.problems 是定义的问题,details.types 是类型错误
75
+ */
76
+ publish(
77
+ input: ProcessDefinition | FlowProject,
78
+ options?: PublishOptions,
79
+ ): Promise<{ key: string; version: number }>;
80
+ /** 检查(工作室边改边查):与发布同样编译、校验、类型检查,不发布、不报错,问题都在结果里 */
81
+ check(input: ProcessDefinition | FlowProject): Promise<CheckResult>;
82
+ /** 版本:全部流程、列出、取某版的工程(在线编辑)、回滚、启停 */
83
+ readonly versions: {
84
+ /** 全部流程(含停用的):每个流程最新的一版,带版本数;按流程的键排 */
85
+ catalog(): Promise<CatalogEntry[]>;
86
+ list(key: string): Promise<VersionInfo[]>;
87
+ /** 某个版本的工程(不写版本时是最新的);只发布过定义的,工程里只有 process.json */
88
+ project(key: string, version?: number): Promise<FlowProject>;
89
+ /** 回滚:把那个版本的工程原样发布成新版本,运行中的实例留在各自的版本上 */
90
+ rollback(
91
+ key: string,
92
+ version: number,
93
+ options?: Omit<PublishOptions, 'note'>,
94
+ ): Promise<{ key: string; version: number }>;
95
+ /** 启停:停用时这个流程的版本都不能再发起(运行中的照常走完);启用时最新一版能发起 */
96
+ setEnabled(key: string, enabled: boolean): Promise<void>;
97
+ /**
98
+ * 迁移预览:这个流程在别的版本上、还没结束的单子,各自正在用的节点在第 version 版里有没有同名同类型的节点。
99
+ * 迁移本身是实例上的 migrate 命令(对应不上的在 nodes 里写对应)
100
+ */
101
+ migrationPreview(key: string, version: number): Promise<MigrationCandidate[]>;
102
+ };
103
+ /** 按单据类型用一个流程:发起、处理时变量写错字段是编译错误(`engine.process<typeof form>('purchase')`) */
104
+ process<Form extends FormManifest>(key: string): TypedProcess<FormValues<Form>>;
105
+ /** 执行一个命令 */
106
+ run(command: FlowCommand, actor: Actor): Promise<RunResult>;
107
+ /** 发起前存的草稿:不进流程、只有自己看得到,只查值不查必填;`start` 带 draft 时从它发起 */
108
+ readonly drafts: {
109
+ /** 存(给 draft 时改那一份,否则按 process 新建) */
110
+ save(
111
+ input: {
112
+ readonly draft?: number;
113
+ readonly process?: string;
114
+ readonly variables?: Readonly<Record<string, unknown>>;
115
+ readonly businessKey?: string;
116
+ },
117
+ actor: Actor,
118
+ ): Promise<InstanceRow>;
119
+ list(actor: Actor): Promise<InstanceRow[]>;
120
+ get(id: number, actor: Actor): Promise<InstanceRow>;
121
+ discard(id: number, actor: Actor): Promise<boolean>;
122
+ };
123
+ /** 批量执行(批量认领、批量处理):每条一个事务,各自成败,结果按顺序给出 */
124
+ runMany(commands: readonly FlowCommand[], actor: Actor): Promise<BatchResult[]>;
125
+ /** 外部事件(对方盖章、付款到账):在等它的实例往下走,返回这些实例的结果 */
126
+ signal(input: SignalInput, actor: Actor): Promise<RunResult[]>;
127
+ readonly query: {
128
+ /** 我的待办:落到我的、我能认领的 */
129
+ todo(actor: Actor): Promise<TodoItem[]>;
130
+ /** 我处理过的,新的在前 */
131
+ done(actor: Actor, filter?: ListFilter): Promise<TodoItem[]>;
132
+ /** 等我指定承办人的(我是收件箱的负责人,很久没人认领) */
133
+ designations(actor: Actor): Promise<TodoItem[]>;
134
+ /** 实例详情:实例、全部待办、流转记录;给了 actor 时只给经手的人与管理员看(同 search 的 involved),别人是 forbidden */
135
+ instance(id: number, actor?: Actor): Promise<InstanceDetail>;
136
+ /** 待办详情 */
137
+ workItem(id: number, actor: Actor): Promise<WorkItemDetail>;
138
+ /** 我发起的实例,新的在前 */
139
+ started(actor: Actor, filter?: ListFilter): Promise<InstanceRow[]>;
140
+ /** 查单据:按范围、流程、状态、发起时间、文字筛,新的在前,分页 */
141
+ search(actor: Actor, filter?: InstanceSearch): Promise<ResultPage<InstanceRow>>;
142
+ /** 抄送给我的,没读的在前 */
143
+ cc(actor: Actor): Promise<CcItem[]>;
144
+ /** 失败的作业(异常);给实例时只看这个实例的 */
145
+ incidents(instance?: number): Promise<Incident[]>;
146
+ /** 能发起的流程:每个流程最新的启用版本 */
147
+ processes(): Promise<ProcessDefinition[]>;
148
+ /** 发起视图:发起页按它渲染单据、列出要选处理人的下一步 */
149
+ startView(key: string, actor: Actor): Promise<StartView>;
150
+ };
151
+ /** 重试失败的作业 */
152
+ retryJob(job: number, actor: Actor): Promise<boolean>;
153
+ /** 把抄送给我的这个实例标成已读,返回标了几条 */
154
+ readCc(instance: number, actor: Actor): Promise<number>;
155
+ /**
156
+ * 流程工程的视图(views/*.tsx,编好的模块表格式,加上它们 import 的工程文件):页面用 linkProject 加载、渲染;
157
+ * 不写版本是最新的一版。谁都能取(是界面代码)
158
+ */
159
+ views(key: string, version?: number): Promise<Record<string, string>>;
160
+ readonly jobs: {
161
+ /** 执行到点的作业,返回执行了几个;顺带重试发件箱里没送到的通知。Nitro 的定时任务或接入方自己定时调用 */
162
+ runDue(options?: { limit?: number; worker?: string }): Promise<number>;
163
+ };
164
+ /** 通知(docs/decisions/0010):我的通知、没读的有几条、标为已读 */
165
+ readonly notifications: {
166
+ list(
167
+ actor: Actor,
168
+ filter?: { unreadOnly?: boolean; limit?: number },
169
+ ): Promise<NotificationView[]>;
170
+ unread(actor: Actor): Promise<number>;
171
+ /** 给了编号只标这些(只能标自己的),不给时全部;返回标了几条 */
172
+ read(actor: Actor, ids?: readonly number[]): Promise<number>;
173
+ };
174
+ /**
175
+ * 代理(docs/decisions/0010 第 3 节):不在的时候新到手上的待办交给代理人。list 是我设的、别人交给我的(没结束的);
176
+ * save 设一条(管理员可以替别人设);cancel 撤销
177
+ */
178
+ readonly proxies: {
179
+ list(actor: Actor): Promise<{ mine: ProxyView[]; forMe: ProxyView[] }>;
180
+ save(actor: Actor, input: ProxyInput): Promise<ProxyView>;
181
+ cancel(actor: Actor, id: number): Promise<boolean>;
182
+ };
183
+ /** 监控与统计(docs/decisions/0010 第 4 节):发起、结束、各流程时长、瓶颈环节、谁压着待办、异常;端点只给管理员 */
184
+ readonly stats: {
185
+ overview(filter?: StatsFilter): Promise<FlowStats>;
186
+ };
187
+ /** 引擎用的 Db(查询自己的表、和业务表做报表) */
188
+ readonly db: FlowDb;
189
+ }
190
+
191
+ /** 建一个引擎:先建核心,再按依赖的先后装上各部分 */
192
+ export function createFlowEngine(options: FlowEngineOptions): FlowEngine {
193
+ const core = createCore(options);
194
+ core.calls = createCalls(core);
195
+ core.starts = createStarts(core);
196
+ core.tasks = createTasks(core);
197
+ core.ops = createOps(core);
198
+ core.admin = createAdmin(core);
199
+ core.signals = createSignals(core);
200
+ core.commands = createCommands(core);
201
+ core.publishing = createPublishing(core);
202
+ core.queries = createQueries(core);
203
+ core.jobs = createJobs(core);
204
+ core.notifications = createNotifications(core);
205
+ core.proxies = createProxies(core);
206
+ core.stats = createStats(core);
207
+ const { db, now } = core;
208
+
209
+ function process<Form extends FormManifest>(key: string): TypedProcess<FormValues<Form>> {
210
+ return {
211
+ start: (input, actor) => core.commands.run({ type: 'start', process: key, ...input }, actor),
212
+ complete: (input, actor) => core.commands.run({ type: 'complete', ...input }, actor),
213
+ };
214
+ }
215
+
216
+ const readCc = (instance: number, actor: Actor) =>
217
+ db
218
+ .update(FlowCc)
219
+ .set({ readAt: now() })
220
+ .where((c) => [c.instanceId.eq(instance), c.recipient.eq(actor.id), c.readAt.isNull()])
221
+ .execute();
222
+
223
+ return {
224
+ db,
225
+ signal: core.signals.signal,
226
+ retryJob: core.jobs.retryJob,
227
+ readCc,
228
+ views: core.publishing.views,
229
+ createTables: () => db.createTables(),
230
+ drafts: core.starts.drafts,
231
+ runMany: core.commands.runMany,
232
+ versions: core.publishing.versions,
233
+ process,
234
+ publish: core.publishing.publish,
235
+ check: core.publishing.check,
236
+ run: core.commands.run,
237
+ query: core.queries.query,
238
+ jobs: { runDue: core.jobs.runDue },
239
+ notifications: {
240
+ list: core.notifications.list,
241
+ unread: core.notifications.unread,
242
+ read: core.notifications.read,
243
+ },
244
+ proxies: core.proxies,
245
+ stats: core.stats,
246
+ };
247
+ }