@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,132 @@
1
+ /**
2
+ * 代理(docs/decisions/0010 第 3 节):某人不在(休假、出差)时设一段时间、哪些流程,新到他手上的待办交给代理人,
3
+ * 待办上记着本该是谁的(proxyFor)。到达时解析(Execution.insertItem),已经在手上的不动——要交出去用转办。
4
+ * 代理人自己也设了代理时顺着找下去(绕回来的就停在绕回之前的那个人);收件箱里的候选人设了代理时,代理人也加进候选。
5
+ */
6
+ import type { Row } from '@zerodep-dev/easy-query-ts';
7
+ import { FlowProxy, type FlowDb } from '../core/entities.ts';
8
+ import type { EngineCore } from '../core/context.ts';
9
+ import { FlowError } from '../core/errors.ts';
10
+ import type { Actor } from '../types.ts';
11
+ import type { ProxyInput, ProxyView } from '../views.ts';
12
+
13
+ /** 这一刻对这个流程生效的代理规则(新设的优先) */
14
+ async function activeRule(db: FlowDb, user: string, processKey: string, now: Date) {
15
+ const rules = await db
16
+ .queryable(FlowProxy)
17
+ .where((p) => [p.principal.eq(user), p.cancelledAt.isNull(), p.startsAt.le(now)])
18
+ .orderBy((p) => p.id.desc())
19
+ .toList();
20
+ return rules.find(
21
+ (r) =>
22
+ (r.endsAt === null || r.endsAt > now) &&
23
+ (r.processKeys.length === 0 || r.processKeys.includes(processKey)),
24
+ );
25
+ }
26
+
27
+ /** 这个人这一刻的代理人(顺着代理人的代理找到底);没设代理时为空 */
28
+ export async function agentOf(
29
+ db: FlowDb,
30
+ user: string,
31
+ processKey: string,
32
+ now: Date,
33
+ ): Promise<string | null> {
34
+ const seen = new Set([user]);
35
+ let current = user;
36
+ for (;;) {
37
+ const rule = await activeRule(db, current, processKey, now);
38
+ if (!rule || seen.has(rule.agent)) return current === user ? null : current;
39
+ seen.add(rule.agent);
40
+ current = rule.agent;
41
+ }
42
+ }
43
+
44
+ const proxyView = (row: Row<typeof FlowProxy>, now: Date): ProxyView => ({
45
+ id: row.id,
46
+ principal: row.principal,
47
+ agent: row.agent,
48
+ processKeys: row.processKeys,
49
+ startsAt: row.startsAt,
50
+ endsAt: row.endsAt,
51
+ note: row.note,
52
+ createdAt: row.createdAt,
53
+ active: row.startsAt <= now && (row.endsAt === null || row.endsAt > now),
54
+ });
55
+
56
+ /** 代理规则:装进引擎核心(core.proxies) */
57
+ export function createProxies(core: EngineCore) {
58
+ const { db, now } = core;
59
+
60
+ /** 只能管自己的;管理员可以替别人设 */
61
+ const ownerOf = (actor: Actor, principal: string | undefined) => {
62
+ const owner = principal ?? actor.id;
63
+ if (owner !== actor.id && !actor.admin)
64
+ throw new FlowError('forbidden', '只能设自己的代理', { principal: owner });
65
+ return owner;
66
+ };
67
+
68
+ /** 我设的、别人交给我的,还没结束的(没撤销、没过期),新设的在前 */
69
+ async function list(actor: Actor): Promise<{ mine: ProxyView[]; forMe: ProxyView[] }> {
70
+ const at = now();
71
+ const rows = (
72
+ await db
73
+ .queryable(FlowProxy)
74
+ .where((p) => [p.cancelledAt.isNull()])
75
+ .orderBy((p) => p.id.desc())
76
+ .toList()
77
+ ).filter(
78
+ (r) => (r.principal === actor.id || r.agent === actor.id) && (!r.endsAt || r.endsAt > at),
79
+ );
80
+ return {
81
+ mine: rows.filter((r) => r.principal === actor.id).map((r) => proxyView(r, at)),
82
+ forMe: rows.filter((r) => r.agent === actor.id).map((r) => proxyView(r, at)),
83
+ };
84
+ }
85
+
86
+ /** 设一条代理:开始不写是现在,结束不写是一直到撤销;流程不写是全部 */
87
+ async function save(actor: Actor, input: ProxyInput): Promise<ProxyView> {
88
+ const principal = ownerOf(actor, input.principal);
89
+ const at = now();
90
+ const startsAt = input.startsAt ?? at;
91
+ const endsAt = input.endsAt ?? null;
92
+ if (!input.agent) throw new FlowError('invalid-input', '要写代理人');
93
+ if (input.agent === principal) throw new FlowError('invalid-input', '代理人不能是自己');
94
+ if (endsAt && endsAt <= startsAt)
95
+ throw new FlowError('invalid-input', '结束要晚于开始', { startsAt, endsAt });
96
+ const values = {
97
+ principal,
98
+ agent: input.agent,
99
+ processKeys: [...(input.processKeys ?? [])],
100
+ startsAt,
101
+ endsAt,
102
+ note: input.note?.trim() || null,
103
+ createdAt: at,
104
+ createdBy: actor.id,
105
+ cancelledAt: null,
106
+ };
107
+ const id = Number(await db.insert(FlowProxy).values(values).returnId());
108
+ return proxyView({ id, ...values }, at);
109
+ }
110
+
111
+ /** 撤销(委托人自己或管理员);返回撤了没有 */
112
+ async function cancel(actor: Actor, id: number): Promise<boolean> {
113
+ const row = await db
114
+ .queryable(FlowProxy)
115
+ .where((p) => [p.id.eq(id)])
116
+ .first();
117
+ if (!row || row.cancelledAt) return false;
118
+ ownerOf(actor, row.principal);
119
+ return (
120
+ (await db
121
+ .update(FlowProxy)
122
+ .set({ cancelledAt: now() })
123
+ .where((p) => [p.id.eq(id), p.cancelledAt.isNull()])
124
+ .execute()) > 0
125
+ );
126
+ }
127
+
128
+ return { list, save, cancel };
129
+ }
130
+
131
+ /** 代理规则模块 */
132
+ export type Proxies = ReturnType<typeof createProxies>;
@@ -0,0 +1,230 @@
1
+ /**
2
+ * 流程工程的编译与加载(docs/decisions/0002-projects.md):发布时用选项里的 transform 把每个 .ts / .tsx 编成从模块表取导入的 JS
3
+ * (`@zerodep-dev/flow-ts-studio` 的 compileInPlace,或浏览器里 Worker 编译;引擎自己不带编译器),跟着版本存下来;
4
+ * 执行时由这里的链接器加载——相对路径在工程里找,包名先找引擎自带的(模型包、defineLogic),再找宿主登记的。
5
+ * Node 与浏览器同一套,不依赖打包器。
6
+ *
7
+ * 信任模型:只有管理员能写,代码在宿主里直接执行,不做沙箱。
8
+ */
9
+ import * as model from '@zerodep-dev/flow-ts-model';
10
+ import {
11
+ PROJECT_FILES,
12
+ upgradeDefinition,
13
+ type FlowProject,
14
+ type FormManifest,
15
+ type ProcessDefinition,
16
+ } from '@zerodep-dev/flow-ts-model';
17
+ import { FlowError } from '../core/errors.ts';
18
+ import { defineLogic, defineScenarios, type FlowLogic } from '../extensions.ts';
19
+
20
+ /** 宿主登记给流程代码 import 的模块:给出导出,或用到才加载;types 是给类型检查、在线编辑器的声明 */
21
+ export interface HostModule {
22
+ readonly exports?: object;
23
+ readonly load?: () => Promise<object>;
24
+ readonly types?: string;
25
+ }
26
+
27
+ /** 模块名 → 宿主模块 */
28
+ export type HostModules = Readonly<Record<string, HostModule>>;
29
+
30
+ /**
31
+ * TS / TSX → 模块表格式的 JS(组件库 browser-compile 的输出:导入读 `__modules['名字']`,导出写 `__exports`);path 用来报错
32
+ */
33
+ export type TransformCode = (source: string, path: string) => Promise<string>;
34
+
35
+ /** 编译好的工程:并进单据变量的定义、每个模块的 JS */
36
+ export interface CompiledProject {
37
+ readonly definition: ProcessDefinition;
38
+ readonly modules: Readonly<Record<string, string>>;
39
+ }
40
+
41
+ const isCode = (path: string) => /\.tsx?$/.test(path);
42
+
43
+ /**
44
+ * 编译:读 process.json、转换每个 .ts / .tsx;写得不对报 invalid-definition(field 是文件路径)。
45
+ * 只有 process.json 的工程(只发布过定义的版本、回滚到它)不用编译器
46
+ */
47
+ export async function compileProject(
48
+ project: FlowProject,
49
+ transform: TransformCode | undefined,
50
+ ): Promise<CompiledProject> {
51
+ if (!transform && Object.keys(project.files).some(isCode)) {
52
+ throw new FlowError(
53
+ 'invalid-definition',
54
+ '发布流程工程要在引擎选项里给 transform(@zerodep-dev/flow-ts-studio 的 compileInPlace)',
55
+ );
56
+ }
57
+ const json = project.files[PROJECT_FILES.process];
58
+ if (json === undefined) {
59
+ throw new FlowError('invalid-definition', `流程工程里要有 ${PROJECT_FILES.process}`, {
60
+ field: PROJECT_FILES.process,
61
+ });
62
+ }
63
+ const definition = attempt(PROJECT_FILES.process, () => upgradeDefinition(JSON.parse(json)));
64
+ const modules: Record<string, string> = {};
65
+ for (const [path, source] of Object.entries(project.files)) {
66
+ if (isCode(path)) modules[path] = await attemptAsync(path, () => transform!(source, path));
67
+ }
68
+ return { definition, modules };
69
+ }
70
+
71
+ /** 加载好的工程:取模块的导出;单据与逻辑是 form.ts、logic.ts 的默认导出 */
72
+ export interface LinkedProject {
73
+ module(path: string): Readonly<Record<string, unknown>>;
74
+ readonly form: FormManifest | undefined;
75
+ readonly logic: FlowLogic | undefined;
76
+ }
77
+
78
+ /** 引擎自带、流程代码总能 import 的模块 */
79
+ const BUILTIN: Readonly<Record<string, object>> = {
80
+ '@zerodep-dev/flow-ts-model': model,
81
+ '@zerodep-dev/flow-ts-engine': { defineLogic, defineScenarios },
82
+ };
83
+
84
+ /** 加载编译好的模块:先把用到的宿主模块都加载好(模块表是同步取的),工程里的模块用到时才执行 */
85
+ export async function linkProject(
86
+ modules: Readonly<Record<string, string>>,
87
+ host: HostModules = {},
88
+ ): Promise<LinkedProject> {
89
+ const external = new Map<string, object>();
90
+ for (const code of Object.values(modules)) {
91
+ for (const name of importedModules(code)) {
92
+ if (!name.startsWith('.') && !external.has(name))
93
+ external.set(name, await hostModule(name, host));
94
+ }
95
+ }
96
+ const loaded = new Map<string, Record<string, unknown>>();
97
+ const loading = new Set<string>();
98
+ const load = (path: string): Record<string, unknown> => {
99
+ const done = loaded.get(path);
100
+ if (done) return done;
101
+ if (loading.has(path))
102
+ throw new FlowError('invalid-definition', `${path} 循环 import 了自己`, { field: path });
103
+ loading.add(path);
104
+ const code = modules[path]!;
105
+ const table: Record<string, unknown> = {};
106
+ for (const name of importedModules(code)) {
107
+ if (name.startsWith('.')) {
108
+ const target = resolve(path, name, modules);
109
+ Object.defineProperty(table, name, { get: () => load(target), enumerable: true });
110
+ } else table[name] = external.get(name);
111
+ }
112
+ const exports = attempt(path, () => evaluate(code, table));
113
+ loading.delete(path);
114
+ loaded.set(path, exports);
115
+ return exports;
116
+ };
117
+ const defaultOf = (path: string) =>
118
+ modules[path] === undefined ? undefined : (load(path)['default'] as never);
119
+ return {
120
+ module: load,
121
+ form: defaultOf(PROJECT_FILES.form),
122
+ logic: defaultOf(PROJECT_FILES.logic),
123
+ };
124
+ }
125
+
126
+ /** 引擎加载的模块:除去视图(views/ 下的在页面里渲染,import 的是组件库这类引擎没有的模块) */
127
+ export const engineModules = (modules: Readonly<Record<string, string>>) =>
128
+ Object.fromEntries(Object.entries(modules).filter(([path]) => !model.isViewFile(path)));
129
+
130
+ /**
131
+ * 页面要的模块:视图,加上它们相对路径 import 到的工程文件(单据……);页面用 linkProject 加载,宿主模块是组件库、vue 这些
132
+ */
133
+ export function viewModules(modules: Readonly<Record<string, string>>): Record<string, string> {
134
+ const picked: Record<string, string> = {};
135
+ const queue = Object.keys(modules).filter(model.isViewFile);
136
+ while (queue.length) {
137
+ const path = queue.shift()!;
138
+ if (picked[path] !== undefined) continue;
139
+ picked[path] = modules[path]!;
140
+ for (const name of importedModules(picked[path]))
141
+ if (name.startsWith('.')) queue.push(resolve(path, name, modules));
142
+ }
143
+ return picked;
144
+ }
145
+
146
+ /** 编译、加载,把单据(form.ts 的字段清单)内联进定义的 form.manifest */
147
+ export async function buildProject(
148
+ project: FlowProject,
149
+ transform?: TransformCode,
150
+ host?: HostModules,
151
+ ): Promise<CompiledProject & { readonly linked: LinkedProject }> {
152
+ const compiled = await compileProject(project, transform);
153
+ const linked = await linkProject(engineModules(compiled.modules), host);
154
+ const manifest = linked.form;
155
+ if (!manifest) return { ...compiled, linked };
156
+ const { definition } = compiled;
157
+ const form = { ...(definition.form ?? { key: definition.key }), manifest };
158
+ return { ...compiled, definition: { ...definition, form }, linked };
159
+ }
160
+
161
+ /** 模块表格式的代码导入了哪些模块(按出现的先后,不重复) */
162
+ function importedModules(code: string): string[] {
163
+ const names = new Set<string>();
164
+ for (const match of code.matchAll(/__modules\[("(?:[^"\\]|\\.)*")]/g))
165
+ names.add(JSON.parse(match[1]!) as string);
166
+ return [...names];
167
+ }
168
+
169
+ /** 执行模块表格式的代码,返回导出;执行的是管理员写的代码,不做隔离 */
170
+ function evaluate(code: string, modules: Readonly<Record<string, unknown>>) {
171
+ const exports: Record<string, unknown> = {};
172
+ // oxlint-disable-next-line no-implied-eval -- 见文件头的信任模型
173
+ new Function('__modules', '__exports', code)(modules, exports);
174
+ return exports;
175
+ }
176
+
177
+ async function hostModule(name: string, host: HostModules): Promise<object> {
178
+ const builtin = BUILTIN[name];
179
+ if (builtin) return builtin;
180
+ const entry = host[name];
181
+ if (!entry) {
182
+ throw new FlowError('invalid-definition', `流程代码 import 了没有登记的模块 ${name}`, {
183
+ field: name,
184
+ });
185
+ }
186
+ return entry.exports ?? (await entry.load!());
187
+ }
188
+
189
+ /** 相对路径 → 工程里的文件:照写的找,再试 .ts、.tsx、/index.ts */
190
+ function resolve(from: string, specifier: string, modules: Readonly<Record<string, string>>) {
191
+ const parts = from.split('/').slice(0, -1);
192
+ for (const part of specifier.split('/')) {
193
+ if (part === '..') parts.pop();
194
+ else if (part !== '.') parts.push(part);
195
+ }
196
+ const base = parts.join('/');
197
+ const found = [base, `${base}.ts`, `${base}.tsx`, `${base}/index.ts`].find(
198
+ (path) => modules[path] !== undefined,
199
+ );
200
+ if (!found) {
201
+ throw new FlowError('invalid-definition', `${from} import 的 ${specifier} 在工程里找不到`, {
202
+ field: from,
203
+ });
204
+ }
205
+ return found;
206
+ }
207
+
208
+ async function attemptAsync<T>(path: string, work: () => Promise<T>): Promise<T> {
209
+ try {
210
+ return await work();
211
+ } catch (error) {
212
+ return attempt(path, () => {
213
+ throw error;
214
+ });
215
+ }
216
+ }
217
+
218
+ /** 做一步,出错时报 invalid-definition,带上是哪个文件 */
219
+ function attempt<T>(path: string, work: () => T): T {
220
+ try {
221
+ return work();
222
+ } catch (error) {
223
+ if (error instanceof FlowError) throw error;
224
+ throw new FlowError(
225
+ 'invalid-definition',
226
+ `${path} 写得不对:${error instanceof Error ? error.message : String(error)}`,
227
+ { field: path },
228
+ );
229
+ }
230
+ }
@@ -0,0 +1,314 @@
1
+ /**
2
+ * 发布与版本:校验定义、清单与逻辑,编译流程工程,记版本;检查(不发布);全部流程、列出版本、取源码、回滚、启停、迁移预览。
3
+ */
4
+ import {
5
+ processGraph,
6
+ validateManifest,
7
+ type FlowProject,
8
+ type Problem,
9
+ type ProcessDefinition,
10
+ validateProcess,
11
+ } from '@zerodep-dev/flow-ts-model';
12
+ import type { Ref } from '@zerodep-dev/easy-query-ts';
13
+ import { FlowDefinition, FlowInstance, FlowWorkItem, type flowSchema } from '../core/entities.ts';
14
+ import { FlowError } from '../core/errors.ts';
15
+ import { FLOW_CHANNEL } from '../core/channels.ts';
16
+ import { buildProject, viewModules } from './project.ts';
17
+ import type { FlowLogic } from '../extensions.ts';
18
+ import type { TypeProblem } from '../types.ts';
19
+ import type { EngineCore } from '../core/context.ts';
20
+ import type { CatalogEntry, CheckResult, MigrationCandidate, PublishOptions } from '../views.ts';
21
+ import type { FlowEngine } from '../engine.ts';
22
+
23
+ /** 版本行 → 工程:只发布过定义的,工程里只有 process.json(去掉版本号) */
24
+ function projectOf(row: {
25
+ readonly model: ProcessDefinition;
26
+ readonly files: Record<string, string> | null;
27
+ }): FlowProject {
28
+ if (row.files) return { files: row.files };
29
+ const { version: _, ...definition } = row.model;
30
+ return { files: { 'process.json': JSON.stringify(definition, null, 2) } };
31
+ }
32
+
33
+ /** 定义里 `logic.名字` 的引用要在 logic.ts 对应的那一类里有 */
34
+ function logicProblems(definition: ProcessDefinition, logic: FlowLogic | undefined) {
35
+ const problems: Problem[] = [];
36
+ const check = (kind: keyof FlowLogic, ref: unknown, path: string) => {
37
+ if (typeof ref !== 'string' || !ref.startsWith('logic.')) return;
38
+ const name = ref.slice(6);
39
+ if (!logic?.[kind]?.[name])
40
+ problems.push({
41
+ severity: 'error',
42
+ code: 'logic.missing',
43
+ field: path,
44
+ params: { kind, name },
45
+ });
46
+ };
47
+ const walk = (value: unknown, path: string, node?: { readonly type?: unknown }) => {
48
+ if (typeof value === 'string') {
49
+ if (value.startsWith('fn.logic.')) check('functions', value.slice(3), path);
50
+ return;
51
+ }
52
+ if (Array.isArray(value)) {
53
+ value.forEach((item, i) => walk(item, `${path}[${i}]`, node));
54
+ return;
55
+ }
56
+ if (typeof value !== 'object' || value === null) return;
57
+ const record = value as Record<string, unknown>;
58
+ const here = 'type' in record ? (record as { type?: unknown }) : node;
59
+ for (const [key, item] of Object.entries(record)) {
60
+ const at = `${path}.${key}`;
61
+ if (key === 'resolver') check('resolvers', item, at);
62
+ else if (key === 'guards' && Array.isArray(item))
63
+ item.forEach((guard, i) => check('guards', guard, `${at}[${i}]`));
64
+ else if (key === 'action' && here?.type === 'service') check('actions', item, at);
65
+ else walk(item, at, here);
66
+ }
67
+ };
68
+ walk(definition, '$');
69
+ return problems;
70
+ }
71
+
72
+ /** 发布与版本:装进引擎核心(core.publishing),别的模块经它调用 */
73
+ export function createPublishing(core: EngineCore) {
74
+ const { options, db, now, logics } = core;
75
+
76
+ /** 编译、链接、校验、类型检查:发布与检查(check)共用;编译出错照常抛 */
77
+ async function inspect(input: ProcessDefinition | FlowProject) {
78
+ const project = 'files' in input ? input : undefined;
79
+ const built = project
80
+ ? await buildProject(project, options.transform, options.modules)
81
+ : undefined;
82
+ const definition = built?.definition ?? (input as ProcessDefinition);
83
+ const fieldTypes = options.extensions?.fieldTypes ?? {};
84
+ const problems: Problem[] = [
85
+ ...validateProcess(definition).filter((problem) => problem.severity === 'error'),
86
+ ...logicProblems(definition, built?.linked.logic),
87
+ // 内联的单据:清单自己合不合规(注册的字段类型算认得的)
88
+ ...(definition.form?.manifest
89
+ ? validateManifest(definition.form.manifest, {
90
+ isFieldType: (type) => Object.hasOwn(fieldTypes, type),
91
+ })
92
+ : []),
93
+ ];
94
+ // 定义有错时不做类型检查(多半是一样的错,也省一次检查)
95
+ const types: readonly TypeProblem[] =
96
+ problems.length === 0 && project && options.checkTypes
97
+ ? await options.checkTypes(project, options.modules ?? {})
98
+ : [];
99
+ return { project, built, definition, problems, types };
100
+ }
101
+
102
+ async function check(input: ProcessDefinition | FlowProject): Promise<CheckResult> {
103
+ try {
104
+ const { definition, problems, types } = await inspect(input);
105
+ return { definition, problems, types, error: null };
106
+ } catch (error) {
107
+ if (!(error instanceof FlowError)) throw error;
108
+ const field = typeof error.details['field'] === 'string' ? error.details['field'] : null;
109
+ return {
110
+ definition: null,
111
+ problems: [],
112
+ types: [],
113
+ error: { message: error.message, field },
114
+ };
115
+ }
116
+ }
117
+
118
+ async function publish(
119
+ input: ProcessDefinition | FlowProject,
120
+ { actor, note }: PublishOptions = {},
121
+ ): Promise<{ key: string; version: number }> {
122
+ const { project, built, definition, problems, types } = await inspect(input);
123
+ if (problems.length > 0) {
124
+ throw new FlowError(
125
+ 'invalid-definition',
126
+ `流程 ${definition.key} 有 ${problems.length} 处错误`,
127
+ { problems },
128
+ );
129
+ }
130
+ if (types.length > 0) {
131
+ const [first] = types;
132
+ throw new FlowError(
133
+ 'invalid-definition',
134
+ `流程 ${definition.key} 有 ${types.length} 处类型错误,第一处:${first!.file}:${first!.line} ${first!.message}`,
135
+ { types },
136
+ );
137
+ }
138
+ return db.transaction(async (tx) => {
139
+ // 同一个流程的发布串行:版本号不撞
140
+ await tx.advisoryLock(`flow.publish:${definition.key}`);
141
+ const latest = await tx
142
+ .queryable(FlowDefinition)
143
+ .where((d) => d.processKey.eq(definition.key))
144
+ .orderBy((d) => d.version.desc())
145
+ .first();
146
+ const version = (latest?.version ?? 0) + 1;
147
+ const id = Number(
148
+ await tx
149
+ .insert(FlowDefinition)
150
+ .values({
151
+ processKey: definition.key,
152
+ version,
153
+ name: definition.name,
154
+ model: { ...definition, version },
155
+ enabled: true,
156
+ publishedBy: actor?.id ?? null,
157
+ publishedAt: now(),
158
+ note: note ?? null,
159
+ files: project ? { ...project.files } : null,
160
+ modules: built ? { ...built.modules } : null,
161
+ })
162
+ .returnId(),
163
+ );
164
+ logics.set(id, Promise.resolve(built?.linked.logic));
165
+ await tx.notify(FLOW_CHANNEL, JSON.stringify({ process: definition.key }));
166
+ return { key: definition.key, version };
167
+ });
168
+ }
169
+
170
+ const versionColumns = (d: Ref<typeof flowSchema, 'FlowDefinition'>) => ({
171
+ id: d.id,
172
+ key: d.processKey,
173
+ version: d.version,
174
+ name: d.name,
175
+ enabled: d.enabled,
176
+ publishedBy: d.publishedBy,
177
+ publishedAt: d.publishedAt,
178
+ note: d.note,
179
+ });
180
+
181
+ const versions: FlowEngine['versions'] = {
182
+ catalog: async () => {
183
+ const rows = await db
184
+ .queryable(FlowDefinition)
185
+ .orderBy((d) => [d.processKey, d.version.desc()])
186
+ .select(versionColumns)
187
+ .toList();
188
+ const entries = new Map<string, CatalogEntry>();
189
+ for (const row of rows) {
190
+ const entry = entries.get(row.key);
191
+ if (!entry) entries.set(row.key, { ...row, versions: 1, startable: row.enabled });
192
+ else
193
+ entries.set(row.key, {
194
+ ...entry,
195
+ versions: entry.versions + 1,
196
+ startable: entry.startable || row.enabled,
197
+ });
198
+ }
199
+ return [...entries.values()];
200
+ },
201
+ list: async (key) =>
202
+ (
203
+ await db
204
+ .queryable(FlowDefinition)
205
+ .where((d) => d.processKey.eq(key))
206
+ .orderBy((d) => d.version.desc())
207
+ .select(versionColumns)
208
+ .toList()
209
+ ).map(({ key: _key, ...info }) => info),
210
+ project: async (key, version) => projectOf(await versionRow(key, version)),
211
+ rollback: async (key, version, rest) =>
212
+ publish(projectOf(await versionRow(key, version)), {
213
+ ...rest,
214
+ note: `回滚到第 ${version} 版`,
215
+ }),
216
+ migrationPreview: async (key, version) => {
217
+ const target = processGraph((await versionRow(key, version)).model);
218
+ const instances = await db
219
+ .queryable(FlowInstance)
220
+ .where((i) => [
221
+ i.processKey.eq(key),
222
+ i.version.ne(version),
223
+ i.status.in(['active', 'suspended']),
224
+ ])
225
+ .orderBy((i) => i.id)
226
+ .toList();
227
+ const live = instances.length
228
+ ? await db
229
+ .queryable(FlowWorkItem)
230
+ .where((w) => [
231
+ w.instanceId.in(instances.map((i) => i.id)),
232
+ w.state.in(['open', 'waiting']),
233
+ ])
234
+ .select((w) => ({ instanceId: w.instanceId, node: w.node }))
235
+ .toList()
236
+ : [];
237
+ const candidates: MigrationCandidate[] = [];
238
+ for (const instance of instances) {
239
+ const from = processGraph(await core.definitionOf(db, instance.definitionId));
240
+ // 同 migrate 命令:正在处理的节点与开着的待办所在的节点
241
+ const inUse = new Set([
242
+ ...instance.current,
243
+ ...live.filter((w) => w.instanceId === instance.id).map((w) => w.node),
244
+ ]);
245
+ const nodes = [...inUse].map((node) => {
246
+ const before = from.node(node);
247
+ const after = target.node(node);
248
+ return {
249
+ node,
250
+ name: before?.name ?? node,
251
+ target: before && after && before.type === after.type ? node : null,
252
+ // 手动对应时能选的:目标版本里同类型的节点(migrate 命令的 nodes 照此核对)
253
+ choices: target.definition.nodes
254
+ .filter((n) => n.type === before?.type)
255
+ .map((n) => ({ node: n.id, name: n.name ?? n.id })),
256
+ };
257
+ });
258
+ candidates.push({
259
+ instance: instance.id,
260
+ title: instance.title,
261
+ status: instance.status,
262
+ version: instance.version,
263
+ nodes,
264
+ ready: nodes.every((n) => n.target !== null),
265
+ });
266
+ }
267
+ return candidates;
268
+ },
269
+ setEnabled: async (key, enabled) => {
270
+ const latest = await versionRow(key);
271
+ await db.notify(FLOW_CHANNEL, JSON.stringify({ process: key }));
272
+ await db
273
+ .update(FlowDefinition)
274
+ .set({ enabled: false })
275
+ .where((d) => d.processKey.eq(key))
276
+ .execute();
277
+ if (enabled)
278
+ await db
279
+ .update(FlowDefinition)
280
+ .set({ enabled: true })
281
+ .where((d) => d.id.eq(latest.id))
282
+ .execute();
283
+ },
284
+ };
285
+
286
+ async function versionRow(key: string, version?: number) {
287
+ const row = await db
288
+ .queryable(FlowDefinition)
289
+ .where((d) => [
290
+ d.processKey.eq(key),
291
+ ...(version === undefined ? [] : [d.version.eq(version)]),
292
+ ])
293
+ .orderBy((d) => d.version.desc())
294
+ .first();
295
+ if (!row) {
296
+ throw new FlowError(
297
+ 'not-found',
298
+ `没有流程 ${key}${version === undefined ? '' : ` 的第 ${version} 版`}`,
299
+ );
300
+ }
301
+ return row;
302
+ }
303
+
304
+ /** 页面要的视图模块(views/*.tsx 编好的,加上它们 import 的工程文件);不写版本是最新的一版,没有视图时是空的 */
305
+ async function views(key: string, version?: number): Promise<Record<string, string>> {
306
+ const row = await versionRow(key, version);
307
+ return row.modules ? viewModules(row.modules) : {};
308
+ }
309
+
310
+ return { publish, check, versions, versionRow, views };
311
+ }
312
+
313
+ /** createPublishing 给出的函数 */
314
+ export type Publishing = ReturnType<typeof createPublishing>;