@nocobase/flow-engine 2.1.0-alpha.3 → 2.1.0-alpha.31

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 (165) hide show
  1. package/LICENSE +201 -661
  2. package/README.md +79 -10
  3. package/lib/JSRunner.d.ts +10 -1
  4. package/lib/JSRunner.js +50 -5
  5. package/lib/ViewScopedFlowEngine.js +5 -1
  6. package/lib/components/FieldModelRenderer.js +2 -2
  7. package/lib/components/FlowModelRenderer.d.ts +3 -1
  8. package/lib/components/FlowModelRenderer.js +12 -6
  9. package/lib/components/FormItem.d.ts +6 -0
  10. package/lib/components/FormItem.js +11 -3
  11. package/lib/components/MobilePopup.js +6 -5
  12. package/lib/components/dnd/gridDragPlanner.d.ts +59 -2
  13. package/lib/components/dnd/gridDragPlanner.js +613 -21
  14. package/lib/components/dnd/index.d.ts +19 -1
  15. package/lib/components/dnd/index.js +243 -23
  16. package/lib/components/settings/wrappers/component/SelectWithTitle.d.ts +2 -1
  17. package/lib/components/settings/wrappers/component/SelectWithTitle.js +14 -12
  18. package/lib/components/settings/wrappers/contextual/DefaultSettingsIcon.d.ts +3 -0
  19. package/lib/components/settings/wrappers/contextual/DefaultSettingsIcon.js +68 -10
  20. package/lib/components/settings/wrappers/contextual/FlowsFloatContextMenu.d.ts +23 -43
  21. package/lib/components/settings/wrappers/contextual/FlowsFloatContextMenu.js +352 -295
  22. package/lib/components/settings/wrappers/contextual/StepSettingsDialog.js +16 -2
  23. package/lib/components/settings/wrappers/contextual/useFloatToolbarPortal.d.ts +36 -0
  24. package/lib/components/settings/wrappers/contextual/useFloatToolbarPortal.js +274 -0
  25. package/lib/components/settings/wrappers/contextual/useFloatToolbarVisibility.d.ts +30 -0
  26. package/lib/components/settings/wrappers/contextual/useFloatToolbarVisibility.js +315 -0
  27. package/lib/components/subModel/AddSubModelButton.js +27 -1
  28. package/lib/components/subModel/index.d.ts +1 -0
  29. package/lib/components/subModel/index.js +19 -0
  30. package/lib/components/subModel/utils.d.ts +1 -1
  31. package/lib/components/subModel/utils.js +2 -2
  32. package/lib/data-source/index.d.ts +75 -0
  33. package/lib/data-source/index.js +246 -4
  34. package/lib/executor/FlowExecutor.js +31 -8
  35. package/lib/flowContext.d.ts +2 -0
  36. package/lib/flowContext.js +31 -1
  37. package/lib/flowEngine.d.ts +151 -1
  38. package/lib/flowEngine.js +389 -15
  39. package/lib/flowI18n.js +2 -1
  40. package/lib/flowSettings.d.ts +14 -6
  41. package/lib/flowSettings.js +34 -6
  42. package/lib/lazy-helper.d.ts +14 -0
  43. package/lib/lazy-helper.js +71 -0
  44. package/lib/locale/en-US.json +1 -0
  45. package/lib/locale/index.d.ts +2 -0
  46. package/lib/locale/zh-CN.json +1 -0
  47. package/lib/models/DisplayItemModel.d.ts +1 -1
  48. package/lib/models/EditableItemModel.d.ts +1 -1
  49. package/lib/models/FilterableItemModel.d.ts +1 -1
  50. package/lib/models/flowModel.d.ts +13 -10
  51. package/lib/models/flowModel.js +78 -18
  52. package/lib/provider.js +38 -23
  53. package/lib/reactive/observer.js +46 -16
  54. package/lib/runjs-context/registry.d.ts +1 -1
  55. package/lib/runjs-context/setup.js +20 -12
  56. package/lib/runjs-context/snippets/index.js +13 -2
  57. package/lib/runjs-context/snippets/scene/detail/set-field-style.snippet.d.ts +11 -0
  58. package/lib/runjs-context/snippets/scene/detail/set-field-style.snippet.js +50 -0
  59. package/lib/runjs-context/snippets/scene/table/set-cell-style.snippet.d.ts +11 -0
  60. package/lib/runjs-context/snippets/scene/table/set-cell-style.snippet.js +54 -0
  61. package/lib/scheduler/ModelOperationScheduler.d.ts +5 -1
  62. package/lib/scheduler/ModelOperationScheduler.js +3 -2
  63. package/lib/types.d.ts +47 -1
  64. package/lib/utils/createCollectionContextMeta.js +6 -2
  65. package/lib/utils/index.d.ts +2 -2
  66. package/lib/utils/index.js +4 -0
  67. package/lib/utils/parsePathnameToViewParams.js +1 -1
  68. package/lib/utils/runjsTemplateCompat.js +1 -1
  69. package/lib/utils/runjsValue.js +41 -11
  70. package/lib/utils/schema-utils.d.ts +7 -1
  71. package/lib/utils/schema-utils.js +19 -0
  72. package/lib/views/FlowView.d.ts +7 -1
  73. package/lib/views/runViewBeforeClose.d.ts +10 -0
  74. package/lib/views/runViewBeforeClose.js +45 -0
  75. package/lib/views/useDialog.d.ts +2 -1
  76. package/lib/views/useDialog.js +20 -3
  77. package/lib/views/useDrawer.d.ts +2 -1
  78. package/lib/views/useDrawer.js +20 -3
  79. package/lib/views/usePage.d.ts +2 -1
  80. package/lib/views/usePage.js +10 -3
  81. package/package.json +6 -5
  82. package/src/JSRunner.ts +68 -4
  83. package/src/ViewScopedFlowEngine.ts +4 -0
  84. package/src/__tests__/JSRunner.test.ts +27 -1
  85. package/src/__tests__/flow-engine.test.ts +166 -0
  86. package/src/__tests__/flowContext.test.ts +65 -1
  87. package/src/__tests__/flowEngine.modelLoaders.test.ts +245 -0
  88. package/src/__tests__/flowSettings.test.ts +94 -15
  89. package/src/__tests__/objectVariable.test.ts +24 -0
  90. package/src/__tests__/provider.test.tsx +24 -2
  91. package/src/__tests__/renderHiddenInConfig.test.tsx +6 -6
  92. package/src/__tests__/runjsContext.test.ts +16 -0
  93. package/src/__tests__/runjsContextRuntime.test.ts +2 -0
  94. package/src/__tests__/runjsPreprocessDefault.test.ts +23 -0
  95. package/src/__tests__/runjsSnippets.test.ts +21 -0
  96. package/src/__tests__/viewScopedFlowEngine.test.ts +3 -3
  97. package/src/components/FieldModelRenderer.tsx +2 -1
  98. package/src/components/FlowModelRenderer.tsx +18 -6
  99. package/src/components/FormItem.tsx +7 -1
  100. package/src/components/MobilePopup.tsx +4 -2
  101. package/src/components/__tests__/FlowModelRenderer.test.tsx +65 -2
  102. package/src/components/__tests__/FormItem.test.tsx +25 -0
  103. package/src/components/__tests__/dnd.test.ts +44 -0
  104. package/src/components/__tests__/flow-model-render-error-fallback.test.tsx +20 -10
  105. package/src/components/__tests__/gridDragPlanner.test.ts +558 -3
  106. package/src/components/dnd/__tests__/DndProvider.test.tsx +98 -0
  107. package/src/components/dnd/gridDragPlanner.ts +758 -19
  108. package/src/components/dnd/index.tsx +291 -27
  109. package/src/components/settings/wrappers/component/SelectWithTitle.tsx +21 -9
  110. package/src/components/settings/wrappers/contextual/DefaultSettingsIcon.tsx +88 -10
  111. package/src/components/settings/wrappers/contextual/FlowsFloatContextMenu.tsx +487 -440
  112. package/src/components/settings/wrappers/contextual/StepSettingsDialog.tsx +18 -2
  113. package/src/components/settings/wrappers/contextual/__tests__/DefaultSettingsIcon.test.tsx +189 -3
  114. package/src/components/settings/wrappers/contextual/__tests__/FlowsFloatContextMenu.test.tsx +778 -0
  115. package/src/components/settings/wrappers/contextual/useFloatToolbarPortal.ts +360 -0
  116. package/src/components/settings/wrappers/contextual/useFloatToolbarVisibility.ts +361 -0
  117. package/src/components/subModel/AddSubModelButton.tsx +32 -2
  118. package/src/components/subModel/__tests__/AddSubModelButton.test.tsx +142 -32
  119. package/src/components/subModel/index.ts +1 -0
  120. package/src/components/subModel/utils.ts +1 -1
  121. package/src/data-source/__tests__/collection.test.ts +41 -2
  122. package/src/data-source/__tests__/index.test.ts +68 -1
  123. package/src/data-source/index.ts +303 -5
  124. package/src/executor/FlowExecutor.ts +34 -9
  125. package/src/executor/__tests__/flowExecutor.test.ts +57 -0
  126. package/src/flowContext.ts +37 -3
  127. package/src/flowEngine.ts +445 -11
  128. package/src/flowI18n.ts +2 -1
  129. package/src/flowSettings.ts +40 -6
  130. package/src/lazy-helper.tsx +57 -0
  131. package/src/locale/en-US.json +1 -0
  132. package/src/locale/zh-CN.json +1 -0
  133. package/src/models/DisplayItemModel.tsx +1 -1
  134. package/src/models/EditableItemModel.tsx +1 -1
  135. package/src/models/FilterableItemModel.tsx +1 -1
  136. package/src/models/__tests__/dispatchEvent.when.test.ts +214 -0
  137. package/src/models/__tests__/flowModel.test.ts +19 -3
  138. package/src/models/flowModel.tsx +119 -33
  139. package/src/provider.tsx +41 -25
  140. package/src/reactive/__tests__/observer.test.tsx +82 -0
  141. package/src/reactive/observer.tsx +87 -25
  142. package/src/runjs-context/registry.ts +1 -1
  143. package/src/runjs-context/setup.ts +22 -12
  144. package/src/runjs-context/snippets/index.ts +12 -1
  145. package/src/runjs-context/snippets/scene/detail/set-field-style.snippet.ts +30 -0
  146. package/src/runjs-context/snippets/scene/table/set-cell-style.snippet.ts +34 -0
  147. package/src/scheduler/ModelOperationScheduler.ts +14 -3
  148. package/src/types.ts +60 -0
  149. package/src/utils/__tests__/createCollectionContextMeta.test.ts +48 -0
  150. package/src/utils/__tests__/parsePathnameToViewParams.test.ts +7 -0
  151. package/src/utils/__tests__/runjsValue.test.ts +11 -0
  152. package/src/utils/__tests__/utils.test.ts +62 -0
  153. package/src/utils/createCollectionContextMeta.ts +6 -2
  154. package/src/utils/index.ts +2 -1
  155. package/src/utils/parsePathnameToViewParams.ts +2 -2
  156. package/src/utils/runjsTemplateCompat.ts +1 -1
  157. package/src/utils/runjsValue.ts +50 -11
  158. package/src/utils/schema-utils.ts +30 -1
  159. package/src/views/FlowView.tsx +11 -1
  160. package/src/views/__tests__/runViewBeforeClose.test.ts +30 -0
  161. package/src/views/__tests__/useDialog.closeDestroy.test.tsx +13 -12
  162. package/src/views/runViewBeforeClose.ts +19 -0
  163. package/src/views/useDialog.tsx +25 -3
  164. package/src/views/useDrawer.tsx +25 -3
  165. package/src/views/usePage.tsx +12 -3
@@ -8,7 +8,6 @@
8
8
  */
9
9
 
10
10
  import { observable } from '@formily/reactive';
11
- import { CascaderProps } from 'antd';
12
11
  import _ from 'lodash';
13
12
  import { FlowEngine } from '../flowEngine';
14
13
  import { jioToJoiSchema } from './jioToJoiSchema';
@@ -20,9 +19,31 @@ export interface DataSourceOptions extends Record<string, any> {
20
19
  [key: string]: any;
21
20
  }
22
21
 
22
+ export type DataSourceRequester = (options: Record<string, any>) => Promise<any>;
23
+
24
+ export interface DataSourceLoadResult {
25
+ collections?: CollectionOptions[];
26
+ dataSources?: Array<DataSourceOptions & { collections?: CollectionOptions[] }>;
27
+ }
28
+
29
+ export type DataSourceLoader = (context: { key: string; manager: DataSourceManager }) => Promise<DataSourceLoadResult>;
30
+
23
31
  export class DataSourceManager {
24
32
  dataSources: Map<string, DataSource>;
25
33
  flowEngine: FlowEngine;
34
+ requester?: DataSourceRequester;
35
+ collectionFieldInterfaceManager?: {
36
+ addFieldInterfaces?: (fieldInterfaceClasses?: any[]) => void;
37
+ addFieldInterfaceGroups?: (groups: Record<string, { label: string; order?: number }>) => void;
38
+ addFieldInterfaceComponentOption?: (name: string, option: any) => void;
39
+ addFieldInterfaceOperator?: (name: string, operator: any) => void;
40
+ getFieldInterface?: (name: string) => any;
41
+ };
42
+ loaders = new Map<string, DataSourceLoader>();
43
+ loadedKeys = new Set<string>();
44
+ loadingKeys = new Set<string>();
45
+ loadErrors = new Map<string, Error | null>();
46
+ loadingPromise: Promise<void> | null = null;
26
47
 
27
48
  constructor() {
28
49
  this.dataSources = observable.shallow<Map<string, DataSource>>(new Map());
@@ -32,6 +53,38 @@ export class DataSourceManager {
32
53
  this.flowEngine = flowEngine;
33
54
  }
34
55
 
56
+ setRequester(requester?: DataSourceRequester) {
57
+ this.requester = requester;
58
+ }
59
+
60
+ setCollectionFieldInterfaceManager(manager: DataSourceManager['collectionFieldInterfaceManager']) {
61
+ this.collectionFieldInterfaceManager = manager;
62
+ }
63
+
64
+ addFieldInterfaces(fieldInterfaceClasses: any[] = []) {
65
+ this.collectionFieldInterfaceManager?.addFieldInterfaces?.(fieldInterfaceClasses);
66
+ }
67
+
68
+ addFieldInterfaceGroups(groups: Record<string, { label: string; order?: number }>) {
69
+ this.collectionFieldInterfaceManager?.addFieldInterfaceGroups?.(groups);
70
+ }
71
+
72
+ addFieldInterfaceComponentOption(name: string, option: any) {
73
+ this.collectionFieldInterfaceManager?.addFieldInterfaceComponentOption?.(name, option);
74
+ }
75
+
76
+ addFieldInterfaceOperator(name: string, operator: any) {
77
+ this.collectionFieldInterfaceManager?.addFieldInterfaceOperator?.(name, operator);
78
+ }
79
+
80
+ registerLoader(key: string, loader: DataSourceLoader) {
81
+ this.loaders.set(key, loader);
82
+ }
83
+
84
+ removeLoader(key: string) {
85
+ this.loaders.delete(key);
86
+ }
87
+
35
88
  addDataSource(ds: DataSource | DataSourceOptions) {
36
89
  if (this.dataSources.has(ds.key)) {
37
90
  throw new Error(`DataSource with name ${ds.key} already exists`);
@@ -48,7 +101,7 @@ export class DataSourceManager {
48
101
 
49
102
  upsertDataSource(ds: DataSource | DataSourceOptions) {
50
103
  if (this.dataSources.has(ds.key)) {
51
- this.dataSources.get(ds.key)?.setOptions(ds);
104
+ this.dataSources.get(ds.key)?.patchOptions(ds);
52
105
  } else {
53
106
  this.addDataSource(ds);
54
107
  }
@@ -82,6 +135,187 @@ export class DataSourceManager {
82
135
  if (!ds) return undefined;
83
136
  return ds.getCollectionField(otherKeys.join('.'));
84
137
  }
138
+
139
+ async ensureLoaded(options: { force?: boolean; keys?: string[] } = {}) {
140
+ const { force = false } = options;
141
+ const keys = this.resolveLoadKeys(options.keys);
142
+ const pendingKeys = force ? keys : keys.filter((key) => !this.loadedKeys.has(key));
143
+ if (!pendingKeys.length) {
144
+ return;
145
+ }
146
+ if (this.loadingPromise) {
147
+ return this.loadingPromise;
148
+ }
149
+
150
+ this.loadingPromise = (async () => {
151
+ try {
152
+ for (const key of pendingKeys) {
153
+ await this.loadKey(key, { initial: !this.loadedKeys.has(key), force });
154
+ }
155
+ } finally {
156
+ this.loadingPromise = null;
157
+ }
158
+ })();
159
+
160
+ return this.loadingPromise;
161
+ }
162
+
163
+ async reload(options: { keys?: string[] } = {}) {
164
+ const keys = this.resolveLoadKeys(options.keys);
165
+ if (!keys.length) {
166
+ return;
167
+ }
168
+ if (this.loadingPromise) {
169
+ return this.loadingPromise;
170
+ }
171
+
172
+ this.loadingPromise = (async () => {
173
+ try {
174
+ for (const key of keys) {
175
+ await this.loadKey(key, { initial: false, force: true });
176
+ }
177
+ } finally {
178
+ this.loadingPromise = null;
179
+ }
180
+ })();
181
+
182
+ return this.loadingPromise;
183
+ }
184
+
185
+ async reloadDataSource(key: string) {
186
+ if (this.loadingKeys.has(key) && this.loadingPromise) {
187
+ return this.loadingPromise;
188
+ }
189
+ if (!this.loaders.has(key) && this.loaders.has('*')) {
190
+ return this.reload({ keys: ['*'] });
191
+ }
192
+ return this.reload({ keys: [key] });
193
+ }
194
+
195
+ protected resolveLoadKeys(requestedKeys?: string[]) {
196
+ const normalizedKeys = requestedKeys?.length ? requestedKeys : ['main'];
197
+ const explicitKeys = normalizedKeys.filter((key) => this.loaders.has(key));
198
+ if (this.loaders.has('*')) {
199
+ return _.uniq(['*', ...explicitKeys]);
200
+ }
201
+ return explicitKeys.length ? explicitKeys : normalizedKeys;
202
+ }
203
+
204
+ protected getApp() {
205
+ return this.flowEngine?.context?.app as { eventBus?: EventTarget } | undefined;
206
+ }
207
+
208
+ protected dispatchDataSourceEvent(
209
+ type: 'dataSource:loaded' | 'dataSource:loadFailed',
210
+ detail: { dataSourceKey: string; initial: boolean; error?: Error },
211
+ ) {
212
+ this.getApp()?.eventBus?.dispatchEvent(new CustomEvent(type, { detail }));
213
+ }
214
+
215
+ protected setDataSourceState(
216
+ key: string,
217
+ options: Partial<Pick<DataSourceOptions, 'status' | 'errorMessage'>> & Record<string, any>,
218
+ ) {
219
+ const dataSource = this.getDataSource(key);
220
+ if (!dataSource) {
221
+ return;
222
+ }
223
+ dataSource.patchOptions(options);
224
+ }
225
+
226
+ protected applyDataSourceLoadResult(key: string, result: DataSourceLoadResult) {
227
+ if (key === '*') {
228
+ const dataSources = result?.dataSources || [];
229
+ dataSources.forEach((dataSourceOptions) => {
230
+ const { collections, ...dataSource } = dataSourceOptions;
231
+ this.upsertDataSource(dataSource);
232
+ if (collections) {
233
+ this.getDataSource(dataSource.key)?.setCollections(collections, { clearFields: true });
234
+ }
235
+ });
236
+ return;
237
+ }
238
+
239
+ const dataSource = this.getDataSource(key);
240
+ if (!dataSource) {
241
+ return;
242
+ }
243
+ dataSource.setCollections(result?.collections || [], { clearFields: true });
244
+ }
245
+
246
+ protected async loadKey(key: string, options: { initial: boolean; force: boolean }) {
247
+ const loader = this.loaders.get(key);
248
+ if (!loader) {
249
+ return;
250
+ }
251
+
252
+ if (!this.getDataSource(key) && key !== '*') {
253
+ this.addDataSource({ key });
254
+ }
255
+
256
+ const { initial } = options;
257
+ this.loadingKeys.add(key);
258
+ if (key !== '*') {
259
+ this.setDataSourceState(key, {
260
+ status: initial ? 'loading' : 'reloading',
261
+ errorMessage: undefined,
262
+ });
263
+ }
264
+ this.loadErrors.set(key, null);
265
+
266
+ try {
267
+ const result = (await loader({ key, manager: this })) || {};
268
+ this.applyDataSourceLoadResult(key, result);
269
+ this.loadedKeys.add(key);
270
+ if (key !== '*') {
271
+ this.setDataSourceState(key, {
272
+ status: 'loaded',
273
+ errorMessage: undefined,
274
+ });
275
+ }
276
+ this.dispatchDataSourceEvent('dataSource:loaded', { dataSourceKey: key, initial });
277
+ } catch (error) {
278
+ const normalizedError = error instanceof Error ? error : new Error(String(error));
279
+ this.loadErrors.set(key, normalizedError);
280
+ if (key !== '*') {
281
+ this.setDataSourceState(key, {
282
+ status: initial ? 'loading-failed' : 'reloading-failed',
283
+ errorMessage: normalizedError.message,
284
+ });
285
+ }
286
+ this.dispatchDataSourceEvent('dataSource:loadFailed', {
287
+ dataSourceKey: key,
288
+ initial,
289
+ error: normalizedError,
290
+ });
291
+ throw normalizedError;
292
+ } finally {
293
+ this.loadingKeys.delete(key);
294
+ }
295
+ }
296
+ }
297
+
298
+ export type CollectionFieldInterfaceDataSourceManager = Pick<DataSourceManager, 'collectionFieldInterfaceManager'>;
299
+
300
+ export function getCollectionFieldInterface(
301
+ interfaceName: string | undefined,
302
+ ...dataSourceManagers: Array<CollectionFieldInterfaceDataSourceManager | null | undefined>
303
+ ) {
304
+ if (!interfaceName) {
305
+ return undefined;
306
+ }
307
+
308
+ // TODO: Once legacy client is removed and all runtimes share the client-v2 flow-engine
309
+ // DataSourceManager, callers should only pass the flow-engine context DataSourceManager.
310
+ for (const dataSourceManager of dataSourceManagers) {
311
+ const collectionFieldInterfaceManager = dataSourceManager?.collectionFieldInterfaceManager;
312
+ const getFieldInterface = collectionFieldInterfaceManager?.getFieldInterface;
313
+ if (typeof getFieldInterface === 'function') {
314
+ return getFieldInterface.call(collectionFieldInterfaceManager, interfaceName);
315
+ }
316
+ }
317
+
318
+ return undefined;
85
319
  }
86
320
 
87
321
  export class DataSource {
@@ -110,6 +344,14 @@ export class DataSource {
110
344
  return this.options.key;
111
345
  }
112
346
 
347
+ get status() {
348
+ return this.options.status;
349
+ }
350
+
351
+ get errorMessage() {
352
+ return this.options.errorMessage;
353
+ }
354
+
113
355
  setDataSourceManager(dataSourceManager: DataSourceManager) {
114
356
  this.dataSourceManager = dataSourceManager;
115
357
  }
@@ -149,6 +391,10 @@ export class DataSource {
149
391
  return this.collectionManager.upsertCollections(collections, options);
150
392
  }
151
393
 
394
+ setCollections(collections: CollectionOptions[], options: { clearFields?: boolean } = {}) {
395
+ return this.collectionManager.setCollections(collections, options);
396
+ }
397
+
152
398
  removeCollection(name: string) {
153
399
  return this.collectionManager.removeCollection(name);
154
400
  }
@@ -162,6 +408,14 @@ export class DataSource {
162
408
  Object.assign(this.options, newOptions);
163
409
  }
164
410
 
411
+ patchOptions(newOptions: any = {}) {
412
+ Object.assign(this.options, newOptions);
413
+ }
414
+
415
+ reload() {
416
+ return this.dataSourceManager.reloadDataSource(this.key);
417
+ }
418
+
165
419
  getCollectionField(fieldPath: string) {
166
420
  const [collectionName, ...otherKeys] = fieldPath.split('.');
167
421
  const fieldName = otherKeys.join('.');
@@ -194,6 +448,11 @@ export class CollectionManager {
194
448
  this.collections = observable.shallow<Map<string, Collection>>(new Map());
195
449
  }
196
450
 
451
+ protected resetCaches() {
452
+ this.childrenCollectionsName = {};
453
+ this.allCollectionsInheritChain = undefined;
454
+ }
455
+
197
456
  get flowEngine() {
198
457
  return this.dataSource.flowEngine;
199
458
  }
@@ -208,10 +467,12 @@ export class CollectionManager {
208
467
  col.setDataSource(this.dataSource);
209
468
  col.initInherits();
210
469
  this.collections.set(col.name, col);
470
+ this.resetCaches();
211
471
  }
212
472
 
213
473
  removeCollection(name: string) {
214
474
  this.collections.delete(name);
475
+ this.resetCaches();
215
476
  }
216
477
 
217
478
  updateCollection(newOptions: CollectionOptions, options: { clearFields?: boolean } = {}) {
@@ -220,6 +481,7 @@ export class CollectionManager {
220
481
  throw new Error(`Collection ${newOptions.name} not found`);
221
482
  }
222
483
  collection.setOptions(newOptions, options);
484
+ this.resetCaches();
223
485
  }
224
486
 
225
487
  upsertCollection(options: CollectionOptions) {
@@ -239,6 +501,12 @@ export class CollectionManager {
239
501
  this.addCollection(collection);
240
502
  }
241
503
  }
504
+ this.resetCaches();
505
+ }
506
+
507
+ setCollections(collections: CollectionOptions[], options: { clearFields?: boolean } = {}) {
508
+ this.clearCollections();
509
+ this.upsertCollections(collections, options);
242
510
  }
243
511
 
244
512
  sortCollectionsByInherits(collections: CollectionOptions[]): CollectionOptions[] {
@@ -315,6 +583,7 @@ export class CollectionManager {
315
583
 
316
584
  clearCollections() {
317
585
  this.collections.clear();
586
+ this.resetCaches();
318
587
  }
319
588
 
320
589
  getAssociation(associationName: string): CollectionField | undefined {
@@ -501,6 +770,12 @@ export class Collection {
501
770
 
502
771
  get titleCollectionField() {
503
772
  const titleFieldName = this.options.titleField || this.filterTargetKey;
773
+ if (Array.isArray(titleFieldName)) {
774
+ if (titleFieldName.length !== 1) {
775
+ return undefined;
776
+ }
777
+ return this.getField(titleFieldName[0]);
778
+ }
504
779
  const titleCollectionField = this.getField(titleFieldName);
505
780
  return titleCollectionField;
506
781
  }
@@ -531,6 +806,10 @@ export class Collection {
531
806
  this.upsertFields(this.options.fields || []);
532
807
  }
533
808
 
809
+ setOption(key: string, value: any) {
810
+ this.options[key] = value;
811
+ }
812
+
534
813
  getFields(): CollectionField[] {
535
814
  // 合并自身 fields 和所有 inherits 的 fields,后者优先被覆盖
536
815
  const fieldMap = new Map<string, CollectionField>();
@@ -856,7 +1135,21 @@ export class CollectionField {
856
1135
  });
857
1136
 
858
1137
  if (error) {
859
- const message = error.details.map((d: any) => d.message.replace(/"value"/g, `"${label}"`)).join(', ');
1138
+ const message = error.details
1139
+ .map((d: any) => {
1140
+ const translated = this.flowEngine.translate(d.type, {
1141
+ ...d.context,
1142
+ ns: 'data-source-main',
1143
+ label,
1144
+ });
1145
+
1146
+ if (translated && translated !== d.type) {
1147
+ return translated;
1148
+ }
1149
+
1150
+ return d.message.replace(/"value"/g, `"${label}"`);
1151
+ })
1152
+ .join(', ');
860
1153
  return Promise.reject(message);
861
1154
  }
862
1155
 
@@ -879,8 +1172,13 @@ export class CollectionField {
879
1172
  }
880
1173
 
881
1174
  getInterfaceOptions() {
882
- const app = this.flowEngine.context.app;
883
- return app.dataSourceManager.collectionFieldInterfaceManager.getFieldInterface(this.interface);
1175
+ const ctx = this.flowEngine.context;
1176
+ return getCollectionFieldInterface(
1177
+ this.interface,
1178
+ this.collection?.dataSource?.dataSourceManager,
1179
+ ctx.dataSourceManager,
1180
+ ctx.app?.dataSourceManager,
1181
+ );
884
1182
  }
885
1183
 
886
1184
  getFilterOperators() {
@@ -224,10 +224,12 @@ export class FlowExecutor {
224
224
  await this.emitModelEventIf(eventName, `flow:${flowKey}:step:${stepKey}:end`, {
225
225
  ...flowEventBasePayload,
226
226
  stepKey,
227
+ aborted: true,
227
228
  });
228
229
  await this.emitModelEventIf(eventName, `flow:${flowKey}:end`, {
229
230
  ...flowEventBasePayload,
230
231
  result: error,
232
+ aborted: true,
231
233
  });
232
234
  return Promise.resolve(error);
233
235
  }
@@ -316,9 +318,9 @@ export class FlowExecutor {
316
318
 
317
319
  // 记录本次 dispatchEvent 内注册的调度任务,用于在结束/错误后兜底清理未触发的任务
318
320
  const scheduledCancels: ScheduledCancel[] = [];
319
-
320
- // 组装执行函数(返回值用于缓存;beforeRender 返回 results:any[],其它返回 true)
321
- const execute = async () => {
321
+ // 组装执行函数(返回值用于缓存,包含事件结果与是否被 exitAll 中止)
322
+ const execute = async (): Promise<{ result: any[]; abortedByExitAll: boolean }> => {
323
+ let abortedByExitAll = false;
322
324
  if (sequential) {
323
325
  // 顺序执行:动态流(实例级)优先,其次静态流;各自组内再按 sort 升序,最后保持原始顺序稳定
324
326
  const flowsWithIndex = flowsToRun.map((f, i) => ({ f, i }));
@@ -351,7 +353,7 @@ export class FlowExecutor {
351
353
  .map((f) => [f.key, f] as const),
352
354
  );
353
355
  const scheduled = new Set<string>();
354
- const scheduleGroups = new Map<string, Array<{ flow: any; order: number }>>();
356
+ const scheduleGroups = new Map<string, Array<{ flow: any; order: number; shouldSkipOnAborted: boolean }>>();
355
357
  ordered.forEach((flow, indexInOrdered) => {
356
358
  const on = flow.on;
357
359
  const onObj = typeof on === 'object' ? (on as any) : undefined;
@@ -402,9 +404,11 @@ export class FlowExecutor {
402
404
  }
403
405
 
404
406
  if (!whenKey) return;
407
+ const shouldSkipOnAborted =
408
+ whenKey === `event:${eventName}:end` || phase === 'afterFlow' || phase === 'afterStep';
405
409
  scheduled.add(flow.key);
406
410
  const list = scheduleGroups.get(whenKey) || [];
407
- list.push({ flow, order: indexInOrdered });
411
+ list.push({ flow, order: indexInOrdered, shouldSkipOnAborted });
408
412
  scheduleGroups.set(whenKey, list);
409
413
  });
410
414
 
@@ -417,6 +421,14 @@ export class FlowExecutor {
417
421
  return a.order - b.order;
418
422
  });
419
423
  for (const it of sorted) {
424
+ const when = it.shouldSkipOnAborted
425
+ ? Object.assign(
426
+ (event: { type: string; aborted?: boolean }) => event.type === whenKey && event.aborted !== true,
427
+ {
428
+ __eventType: whenKey,
429
+ },
430
+ )
431
+ : (whenKey as any);
420
432
  const cancel = model.scheduleModelOperation(
421
433
  model.uid,
422
434
  async (m) => {
@@ -426,7 +438,7 @@ export class FlowExecutor {
426
438
  }
427
439
  results.push(res);
428
440
  },
429
- { when: whenKey as any },
441
+ { when },
430
442
  );
431
443
  scheduledCancels.push(cancel);
432
444
  }
@@ -441,12 +453,14 @@ export class FlowExecutor {
441
453
  const result = await this.runFlow(model, flow.key, inputArgs, runId, eventName);
442
454
  if (result instanceof FlowExitAllException) {
443
455
  logger.debug(`[FlowEngine.dispatchEvent] ${result.message}`);
456
+ abortedByExitAll = true;
444
457
  break; // 终止后续
445
458
  }
446
459
  results.push(result);
447
460
  } catch (error) {
448
461
  if (error instanceof FlowExitAllException) {
449
462
  logger.debug(`[FlowEngine.dispatchEvent] ${error.message}`);
463
+ abortedByExitAll = true;
450
464
  break; // 终止后续
451
465
  }
452
466
  logger.error(
@@ -456,7 +470,7 @@ export class FlowExecutor {
456
470
  throw error;
457
471
  }
458
472
  }
459
- return results;
473
+ return { result: results, abortedByExitAll };
460
474
  }
461
475
 
462
476
  // 并行
@@ -475,7 +489,11 @@ export class FlowExecutor {
475
489
  }
476
490
  }),
477
491
  );
478
- return results.filter((x) => x !== undefined);
492
+ const filteredResults = results.filter((x) => x !== undefined);
493
+ if (filteredResults.some((x) => x instanceof FlowExitAllException)) {
494
+ abortedByExitAll = true;
495
+ }
496
+ return { result: filteredResults, abortedByExitAll };
479
497
  };
480
498
 
481
499
  // 缓存键:按事件+scope 统一管理(beforeRender 也使用事件名 beforeRender)
@@ -489,7 +507,7 @@ export class FlowExecutor {
489
507
  : null;
490
508
 
491
509
  try {
492
- const result = await this.withApplyFlowCache(cacheKey, execute);
510
+ const { result, abortedByExitAll } = await this.withApplyFlowCache(cacheKey, execute);
493
511
  // 事件结束钩子
494
512
  try {
495
513
  await model.onDispatchEventEnd?.(eventName, options, inputArgs, result);
@@ -499,7 +517,14 @@ export class FlowExecutor {
499
517
  await this.emitModelEventIf(eventName, 'end', {
500
518
  ...eventBasePayload,
501
519
  result,
520
+ ...(abortedByExitAll ? { aborted: true } : {}),
502
521
  });
522
+ if (result && typeof result === 'object') {
523
+ Object.defineProperty(result, '__abortedByExitAll', {
524
+ value: abortedByExitAll,
525
+ configurable: true,
526
+ });
527
+ }
503
528
  return result;
504
529
  } catch (error) {
505
530
  // 进入错误钩子并记录
@@ -232,6 +232,37 @@ describe('FlowExecutor', () => {
232
232
  expect(calls.sort()).toEqual(['a', 'b']);
233
233
  });
234
234
 
235
+ it('dispatchEvent sequential exposes abortedByExitAll metadata on result array', async () => {
236
+ const flows = {
237
+ stopClose: {
238
+ on: { eventName: 'close' },
239
+ steps: {
240
+ only: {
241
+ handler: vi.fn().mockImplementation((ctx) => {
242
+ ctx.exit();
243
+ }),
244
+ },
245
+ },
246
+ },
247
+ afterClose: {
248
+ on: { eventName: 'close', phase: 'afterAllFlows' },
249
+ steps: {
250
+ only: {
251
+ handler: vi.fn(),
252
+ },
253
+ },
254
+ },
255
+ } satisfies Record<string, Omit<FlowDefinitionOptions, 'key'>>;
256
+
257
+ const model = createModelWithFlows('m-close-meta', flows);
258
+
259
+ const result = await engine.executor.dispatchEvent(model, 'close', {}, { sequential: true });
260
+
261
+ expect(Array.isArray(result)).toBe(true);
262
+ expect((result as any).__abortedByExitAll).toBe(true);
263
+ expect(flows.afterClose.steps.only.handler).not.toHaveBeenCalled();
264
+ });
265
+
235
266
  it('dispatchEvent sequential respects sort order and stops on errors', async () => {
236
267
  const calls: string[] = [];
237
268
  const mkFlow = (key: string, sort: number, opts?: { throw?: boolean }) => ({
@@ -288,6 +319,32 @@ describe('FlowExecutor', () => {
288
319
  expect(handler).toHaveBeenCalledTimes(2); // 每个 flow 各 1 次,共 2 次
289
320
  });
290
321
 
322
+ it("dispatchEvent('beforeRender') keeps aborted flag on end event when cache hits", async () => {
323
+ const handler = vi.fn().mockImplementation((ctx) => {
324
+ ctx.exitAll();
325
+ });
326
+ const flows = {
327
+ abortFlow: { steps: { s: { handler } } },
328
+ } satisfies Record<string, Omit<FlowDefinitionOptions, 'key'>>;
329
+ const model = createModelWithFlows('m-br-cache-aborted', flows);
330
+
331
+ const endEvents: any[] = [];
332
+ const onEnd = (payload: any) => {
333
+ endEvents.push(payload);
334
+ };
335
+ engine.emitter.on('model:event:beforeRender:end', onEnd);
336
+
337
+ await engine.executor.dispatchEvent(model, 'beforeRender', undefined, { sequential: true, useCache: true });
338
+ await engine.executor.dispatchEvent(model, 'beforeRender', undefined, { sequential: true, useCache: true });
339
+
340
+ engine.emitter.off('model:event:beforeRender:end', onEnd);
341
+
342
+ expect(handler).toHaveBeenCalledTimes(1);
343
+ expect(endEvents).toHaveLength(2);
344
+ expect(endEvents[0]?.aborted).toBe(true);
345
+ expect(endEvents[1]?.aborted).toBe(true);
346
+ });
347
+
291
348
  it('dispatchEvent supports sequential execution order and exitAll break', async () => {
292
349
  const calls: string[] = [];
293
350
  const mkFlow = (key: string, sort: number, opts?: { exitAll?: boolean }) => ({