@nocobase/flow-engine 2.0.0-alpha.63 → 2.0.0-alpha.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/acl/Acl.js CHANGED
@@ -7,9 +7,11 @@
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
9
 
10
+ var __create = Object.create;
10
11
  var __defProp = Object.defineProperty;
11
12
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
13
  var __getOwnPropNames = Object.getOwnPropertyNames;
14
+ var __getProtoOf = Object.getPrototypeOf;
13
15
  var __hasOwnProp = Object.prototype.hasOwnProperty;
14
16
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
15
17
  var __export = (target, all) => {
@@ -24,13 +26,21 @@ var __copyProps = (to, from, except, desc) => {
24
26
  }
25
27
  return to;
26
28
  };
29
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
30
+ // If the importer is in node compatibility mode or this is not an ESM
31
+ // file that has been converted to a CommonJS file using a Babel-
32
+ // compatible transform (i.e. "__esModule" has not been set), then set
33
+ // "default" to the CommonJS "module.exports" for node compatibility.
34
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
35
+ mod
36
+ ));
27
37
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
38
  var Acl_exports = {};
29
39
  __export(Acl_exports, {
30
40
  ACL: () => ACL
31
41
  });
32
42
  module.exports = __toCommonJS(Acl_exports);
33
- var import_lodash = require("lodash");
43
+ var import_lodash = __toESM(require("lodash"));
34
44
  const _ACL = class _ACL {
35
45
  constructor(flowEngine) {
36
46
  this.flowEngine = flowEngine;
@@ -43,10 +53,10 @@ const _ACL = class _ACL {
43
53
  // 记录上一次用于鉴权的 token,用于识别登录态变更
44
54
  lastToken = null;
45
55
  setData(data) {
46
- this.data = data;
56
+ this.data = import_lodash.default.cloneDeep(data);
47
57
  }
48
58
  setMeta(data) {
49
- this.meta = data;
59
+ this.meta = import_lodash.default.cloneDeep(data);
50
60
  }
51
61
  async load() {
52
62
  var _a, _b, _c, _d;
@@ -31,6 +31,7 @@ export interface Point {
31
31
  export interface GridLayoutData {
32
32
  rows: Record<string, string[][]>;
33
33
  sizes: Record<string, number[]>;
34
+ rowOrder?: string[];
34
35
  }
35
36
  export interface ColumnSlot {
36
37
  type: 'column';
@@ -59,6 +59,43 @@ const COLUMN_EDGE_MAX_WIDTH = 28;
59
59
  const COLUMN_EDGE_WIDTH_RATIO = 0.2;
60
60
  const COLUMN_INSERT_THICKNESS_RATIO = 0.5;
61
61
  const ROW_GAP_HEIGHT_RATIO = 0.33;
62
+ const deriveRowOrder = /* @__PURE__ */ __name((rows, provided) => {
63
+ const order = [];
64
+ const used = /* @__PURE__ */ new Set();
65
+ (provided || Object.keys(rows)).forEach((rowId) => {
66
+ if (rows[rowId] && !used.has(rowId)) {
67
+ order.push(rowId);
68
+ used.add(rowId);
69
+ }
70
+ });
71
+ Object.keys(rows).forEach((rowId) => {
72
+ if (!used.has(rowId)) {
73
+ order.push(rowId);
74
+ used.add(rowId);
75
+ }
76
+ });
77
+ return order;
78
+ }, "deriveRowOrder");
79
+ const normalizeRowsWithOrder = /* @__PURE__ */ __name((rows, order) => {
80
+ const next = {};
81
+ order.forEach((rowId) => {
82
+ if (rows[rowId]) {
83
+ next[rowId] = rows[rowId];
84
+ }
85
+ });
86
+ Object.keys(rows).forEach((rowId) => {
87
+ if (!next[rowId]) {
88
+ next[rowId] = rows[rowId];
89
+ }
90
+ });
91
+ return next;
92
+ }, "normalizeRowsWithOrder");
93
+ const ensureRowOrder = /* @__PURE__ */ __name((layout) => {
94
+ const order = deriveRowOrder(layout.rows, layout.rowOrder);
95
+ layout.rowOrder = order;
96
+ layout.rows = normalizeRowsWithOrder(layout.rows, order);
97
+ return order;
98
+ }, "ensureRowOrder");
62
99
  const toRect = /* @__PURE__ */ __name((domRect) => ({
63
100
  top: domRect.top,
64
101
  left: domRect.left,
@@ -330,9 +367,11 @@ const removeItemFromLayout = /* @__PURE__ */ __name((layout, uidValue) => {
330
367
  if (columns.length === 0) {
331
368
  delete layout.rows[rowId];
332
369
  delete layout.sizes[rowId];
370
+ ensureRowOrder(layout);
333
371
  return;
334
372
  }
335
373
  normalizeRowSizes(rowId, layout);
374
+ ensureRowOrder(layout);
336
375
  }, "removeItemFromLayout");
337
376
  const toIntSizes = /* @__PURE__ */ __name((weights, count) => {
338
377
  if (count === 0) {
@@ -420,8 +459,10 @@ const simulateLayoutForSlot = /* @__PURE__ */ __name(({
420
459
  }) => {
421
460
  const cloned = {
422
461
  rows: import_lodash.default.cloneDeep(layout.rows),
423
- sizes: import_lodash.default.cloneDeep(layout.sizes)
462
+ sizes: import_lodash.default.cloneDeep(layout.sizes),
463
+ rowOrder: layout.rowOrder ? [...layout.rowOrder] : void 0
424
464
  };
465
+ ensureRowOrder(cloned);
425
466
  removeItemFromLayout(cloned, sourceUid);
426
467
  const createRowId = generateRowId ?? import_shared.uid;
427
468
  switch (slot.type) {
@@ -464,8 +505,15 @@ const simulateLayoutForSlot = /* @__PURE__ */ __name(({
464
505
  case "row-gap": {
465
506
  const newRowId = createRowId();
466
507
  const rowPosition = slot.position === "above" ? "before" : "after";
508
+ const currentOrder = deriveRowOrder(cloned.rows, cloned.rowOrder);
467
509
  cloned.rows = insertRow(cloned.rows, slot.targetRowId, newRowId, rowPosition, [[sourceUid]]);
468
510
  cloned.sizes[newRowId] = [DEFAULT_GRID_COLUMNS];
511
+ const targetIndex = currentOrder.indexOf(slot.targetRowId);
512
+ const insertIndex = targetIndex === -1 ? currentOrder.length : rowPosition === "before" ? targetIndex : targetIndex + 1;
513
+ const nextOrder = [...currentOrder];
514
+ nextOrder.splice(insertIndex, 0, newRowId);
515
+ cloned.rowOrder = nextOrder;
516
+ cloned.rows = normalizeRowsWithOrder(cloned.rows, nextOrder);
469
517
  break;
470
518
  }
471
519
  case "empty-row": {
@@ -475,11 +523,15 @@ const simulateLayoutForSlot = /* @__PURE__ */ __name(({
475
523
  [newRowId]: [[sourceUid]]
476
524
  };
477
525
  cloned.sizes[newRowId] = [DEFAULT_GRID_COLUMNS];
526
+ const currentOrder = deriveRowOrder(cloned.rows, cloned.rowOrder);
527
+ cloned.rowOrder = [...currentOrder.filter((id) => id !== newRowId), newRowId];
528
+ cloned.rows = normalizeRowsWithOrder(cloned.rows, cloned.rowOrder);
478
529
  break;
479
530
  }
480
531
  default:
481
532
  break;
482
533
  }
534
+ ensureRowOrder(cloned);
483
535
  return cloned;
484
536
  }, "simulateLayoutForSlot");
485
537
  // Annotate the CommonJS export names for ESM import in node:
@@ -682,6 +682,9 @@ const _CollectionField = class _CollectionField {
682
682
  if (typeof v !== "object") {
683
683
  return v;
684
684
  }
685
+ if (v.value === null || v.value === void 0) {
686
+ return v;
687
+ }
685
688
  return {
686
689
  ...v,
687
690
  value: Number(v.value)
@@ -12,12 +12,13 @@ import type { DispatchEventOptions } from '../types';
12
12
  export declare class FlowExecutor {
13
13
  private readonly engine;
14
14
  constructor(engine: FlowEngine);
15
+ private emitModelEventIf;
15
16
  /** Cache wrapper for applyFlow cache lifecycle */
16
17
  private withApplyFlowCache;
17
18
  /**
18
19
  * Execute a single flow on model.
19
20
  */
20
- runFlow(model: FlowModel, flowKey: string, inputArgs?: Record<string, any>, runId?: string): Promise<any>;
21
+ runFlow(model: FlowModel, flowKey: string, inputArgs?: Record<string, any>, runId?: string, eventName?: string): Promise<any>;
21
22
  /**
22
23
  * Dispatch an event to flows bound via flow.on and execute them.
23
24
  */
@@ -51,6 +51,10 @@ const _FlowExecutor = class _FlowExecutor {
51
51
  constructor(engine) {
52
52
  this.engine = engine;
53
53
  }
54
+ async emitModelEventIf(eventName, topic, payload) {
55
+ if (!eventName) return;
56
+ await this.engine.emitter.emitAsync(`model:event:${eventName}:${topic}`, payload);
57
+ }
54
58
  /** Cache wrapper for applyFlow cache lifecycle */
55
59
  async withApplyFlowCache(cacheKey, executor) {
56
60
  if (!cacheKey || !this.engine) return await executor();
@@ -81,7 +85,7 @@ const _FlowExecutor = class _FlowExecutor {
81
85
  /**
82
86
  * Execute a single flow on model.
83
87
  */
84
- async runFlow(model, flowKey, inputArgs, runId) {
88
+ async runFlow(model, flowKey, inputArgs, runId, eventName) {
85
89
  var _a;
86
90
  const flow = model.getFlow(flowKey);
87
91
  if (!flow) {
@@ -113,6 +117,14 @@ const _FlowExecutor = class _FlowExecutor {
113
117
  const stepDefs = eventStep ? { eventStep, ...flow.steps } : flow.steps;
114
118
  (0, import_setupRuntimeContextSteps.setupRuntimeContextSteps)(flowContext, stepDefs, model, flowKey);
115
119
  const stepsRuntime = flowContext.steps;
120
+ const flowEventBasePayload = {
121
+ uid: model.uid,
122
+ model,
123
+ runId: flowContext.runId,
124
+ inputArgs,
125
+ flowKey
126
+ };
127
+ await this.emitModelEventIf(eventName, `flow:${flowKey}:start`, flowEventBasePayload);
116
128
  for (const [stepKey, step] of Object.entries(stepDefs)) {
117
129
  let handler;
118
130
  let combinedParams = {};
@@ -163,20 +175,56 @@ const _FlowExecutor = class _FlowExecutor {
163
175
  );
164
176
  continue;
165
177
  }
178
+ await this.emitModelEventIf(eventName, `flow:${flowKey}:step:${stepKey}:start`, {
179
+ ...flowEventBasePayload,
180
+ stepKey
181
+ });
166
182
  const currentStepResult = handler(runtimeCtx, combinedParams);
167
183
  const isAwait = step.isAwait !== false;
168
184
  lastResult = isAwait ? await currentStepResult : currentStepResult;
169
185
  stepResults[stepKey] = lastResult;
170
186
  stepsRuntime[stepKey].result = stepResults[stepKey];
187
+ await this.emitModelEventIf(eventName, `flow:${flowKey}:step:${stepKey}:end`, {
188
+ ...flowEventBasePayload,
189
+ result: lastResult,
190
+ stepKey
191
+ });
171
192
  } catch (error) {
193
+ if (!(error instanceof import_utils.FlowExitException) && !(error instanceof import_exceptions.FlowExitAllException)) {
194
+ await this.emitModelEventIf(eventName, `flow:${flowKey}:step:${stepKey}:error`, {
195
+ ...flowEventBasePayload,
196
+ error,
197
+ stepKey
198
+ });
199
+ }
172
200
  if (error instanceof import_utils.FlowExitException) {
173
201
  flowContext.logger.info(`[FlowEngine] ${error.message}`);
202
+ await this.emitModelEventIf(eventName, `flow:${flowKey}:step:${stepKey}:end`, {
203
+ ...flowEventBasePayload,
204
+ stepKey
205
+ });
206
+ await this.emitModelEventIf(eventName, `flow:${flowKey}:end`, {
207
+ ...flowEventBasePayload,
208
+ result: stepResults
209
+ });
174
210
  return Promise.resolve(stepResults);
175
211
  }
176
212
  if (error instanceof import_exceptions.FlowExitAllException) {
177
213
  flowContext.logger.info(`[FlowEngine] ${error.message}`);
214
+ await this.emitModelEventIf(eventName, `flow:${flowKey}:step:${stepKey}:end`, {
215
+ ...flowEventBasePayload,
216
+ stepKey
217
+ });
218
+ await this.emitModelEventIf(eventName, `flow:${flowKey}:end`, {
219
+ ...flowEventBasePayload,
220
+ result: error
221
+ });
178
222
  return Promise.resolve(error);
179
223
  }
224
+ await this.emitModelEventIf(eventName, `flow:${flowKey}:error`, {
225
+ ...flowEventBasePayload,
226
+ error
227
+ });
180
228
  flowContext.logger.error(
181
229
  { err: error },
182
230
  `BaseModel.applyFlow: Error executing step '${stepKey}' in flow '${flowKey}':`
@@ -184,9 +232,12 @@ const _FlowExecutor = class _FlowExecutor {
184
232
  return Promise.reject(error);
185
233
  }
186
234
  }
235
+ await this.emitModelEventIf(eventName, `flow:${flowKey}:end`, {
236
+ ...flowEventBasePayload,
237
+ result: stepResults
238
+ });
187
239
  return Promise.resolve(stepResults);
188
240
  }
189
- // runAutoFlows 已移除:统一通过 dispatchEvent('beforeRender') + useCache 控制
190
241
  /**
191
242
  * Dispatch an event to flows bound via flow.on and execute them.
192
243
  */
@@ -198,13 +249,14 @@ const _FlowExecutor = class _FlowExecutor {
198
249
  const throwOnError = isBeforeRender;
199
250
  const runId = `${model.uid}-${eventName}-${Date.now()}`;
200
251
  const logger = model.context.logger;
252
+ const eventBasePayload = {
253
+ uid: model.uid,
254
+ model,
255
+ runId,
256
+ inputArgs
257
+ };
201
258
  try {
202
- await this.engine.emitter.emitAsync(`model:event:${eventName}:start`, {
203
- uid: model.uid,
204
- model,
205
- runId,
206
- inputArgs
207
- });
259
+ await this.emitModelEventIf(eventName, "start", eventBasePayload);
208
260
  await ((_a = model.onDispatchEventStart) == null ? void 0 : _a.call(model, eventName, options, inputArgs));
209
261
  } catch (err) {
210
262
  if (isBeforeRender && err instanceof import_utils.FlowExitException) {
@@ -226,9 +278,17 @@ const _FlowExecutor = class _FlowExecutor {
226
278
  if (typeof on === "object") return on.eventName === eventName;
227
279
  return false;
228
280
  });
281
+ const isRouterReplayClick = eventName === "click" && (inputArgs == null ? void 0 : inputArgs.triggerByRouter) === true;
282
+ const flowsToRun = isRouterReplayClick ? flows.filter((flow) => {
283
+ var _a2;
284
+ const reg = flow["flowRegistry"];
285
+ const type = (_a2 = reg == null ? void 0 : reg.constructor) == null ? void 0 : _a2._type;
286
+ return type !== "instance";
287
+ }) : flows;
288
+ const scheduledCancels = [];
229
289
  const execute = /* @__PURE__ */ __name(async () => {
230
290
  if (sequential) {
231
- const flowsWithIndex = flows.map((f, i) => ({ f, i }));
291
+ const flowsWithIndex = flowsToRun.map((f, i) => ({ f, i }));
232
292
  const ordered = flowsWithIndex.slice().sort((a, b) => {
233
293
  var _a2, _b2;
234
294
  const regA = a.f["flowRegistry"];
@@ -244,12 +304,88 @@ const _FlowExecutor = class _FlowExecutor {
244
304
  return a.i - b.i;
245
305
  }).map((x) => x.f);
246
306
  const results2 = [];
307
+ const staticFlowsByKey = new Map(
308
+ ordered.filter((f) => {
309
+ var _a2;
310
+ const reg = f["flowRegistry"];
311
+ const type = (_a2 = reg == null ? void 0 : reg.constructor) == null ? void 0 : _a2._type;
312
+ return type !== "instance";
313
+ }).map((f) => [f.key, f])
314
+ );
315
+ const scheduled = /* @__PURE__ */ new Set();
316
+ const scheduleGroups = /* @__PURE__ */ new Map();
317
+ ordered.forEach((flow, indexInOrdered) => {
318
+ var _a2;
319
+ const on = flow.on;
320
+ const onObj = typeof on === "object" ? on : void 0;
321
+ if (!onObj) return;
322
+ const phase = onObj.phase;
323
+ const flowKey = onObj.flowKey;
324
+ const stepKey = onObj.stepKey;
325
+ if (!phase || phase === "beforeAllFlows") return;
326
+ let whenKey = null;
327
+ if (phase === "afterAllFlows") {
328
+ whenKey = `event:${eventName}:end`;
329
+ } else if (phase === "beforeFlow" || phase === "afterFlow") {
330
+ if (!flowKey) {
331
+ whenKey = `event:${eventName}:end`;
332
+ } else {
333
+ const anchorFlow = staticFlowsByKey.get(String(flowKey));
334
+ if (anchorFlow) {
335
+ const anchorPhase = phase === "beforeFlow" ? "start" : "end";
336
+ whenKey = `event:${eventName}:flow:${String(flowKey)}:${anchorPhase}`;
337
+ } else {
338
+ whenKey = `event:${eventName}:end`;
339
+ }
340
+ }
341
+ } else if (phase === "beforeStep" || phase === "afterStep") {
342
+ if (!flowKey || !stepKey) {
343
+ whenKey = `event:${eventName}:end`;
344
+ } else {
345
+ const anchorFlow = staticFlowsByKey.get(String(flowKey));
346
+ const anchorStepExists = !!((_a2 = anchorFlow == null ? void 0 : anchorFlow.hasStep) == null ? void 0 : _a2.call(anchorFlow, String(stepKey)));
347
+ if (anchorFlow && anchorStepExists) {
348
+ const anchorPhase = phase === "beforeStep" ? "start" : "end";
349
+ whenKey = `event:${eventName}:flow:${String(flowKey)}:step:${String(stepKey)}:${anchorPhase}`;
350
+ } else {
351
+ whenKey = `event:${eventName}:end`;
352
+ }
353
+ }
354
+ } else {
355
+ return;
356
+ }
357
+ if (!whenKey) return;
358
+ scheduled.add(flow.key);
359
+ const list = scheduleGroups.get(whenKey) || [];
360
+ list.push({ flow, order: indexInOrdered });
361
+ scheduleGroups.set(whenKey, list);
362
+ });
363
+ for (const [whenKey, list] of scheduleGroups.entries()) {
364
+ const sorted = list.slice().sort((a, b) => {
365
+ const sa = a.flow.sort ?? 0;
366
+ const sb = b.flow.sort ?? 0;
367
+ if (sa !== sb) return sa - sb;
368
+ return a.order - b.order;
369
+ });
370
+ for (const it of sorted) {
371
+ const cancel = model.scheduleModelOperation(
372
+ model.uid,
373
+ async (m) => {
374
+ const res = await this.runFlow(m, it.flow.key, inputArgs, runId, eventName);
375
+ results2.push(res);
376
+ },
377
+ { when: whenKey }
378
+ );
379
+ scheduledCancels.push(cancel);
380
+ }
381
+ }
247
382
  for (const flow of ordered) {
383
+ if (scheduled.has(flow.key)) continue;
248
384
  try {
249
385
  logger.debug(
250
386
  `BaseModel '${model.uid}' dispatching event '${eventName}' to flow '${flow.key}' (sequential).`
251
387
  );
252
- const result = await this.runFlow(model, flow.key, inputArgs, runId);
388
+ const result = await this.runFlow(model, flow.key, inputArgs, runId, eventName);
253
389
  if (result instanceof import_exceptions.FlowExitAllException) {
254
390
  logger.debug(`[FlowEngine.dispatchEvent] ${result.message}`);
255
391
  break;
@@ -266,10 +402,10 @@ const _FlowExecutor = class _FlowExecutor {
266
402
  return results2;
267
403
  }
268
404
  const results = await Promise.all(
269
- flows.map(async (flow) => {
405
+ flowsToRun.map(async (flow) => {
270
406
  logger.debug(`BaseModel '${model.uid}' dispatching event '${eventName}' to flow '${flow.key}'.`);
271
407
  try {
272
- return await this.runFlow(model, flow.key, inputArgs, runId);
408
+ return await this.runFlow(model, flow.key, inputArgs, runId, eventName);
273
409
  } catch (error) {
274
410
  logger.error(
275
411
  { err: error },
@@ -295,11 +431,8 @@ const _FlowExecutor = class _FlowExecutor {
295
431
  } catch (hookErr) {
296
432
  logger.error({ err: hookErr }, `BaseModel.dispatchEvent: End hook error for event '${eventName}'`);
297
433
  }
298
- await this.engine.emitter.emitAsync(`model:event:${eventName}:end`, {
299
- uid: model.uid,
300
- model,
301
- runId,
302
- inputArgs,
434
+ await this.emitModelEventIf(eventName, "end", {
435
+ ...eventBasePayload,
303
436
  result
304
437
  });
305
438
  return result;
@@ -312,14 +445,15 @@ const _FlowExecutor = class _FlowExecutor {
312
445
  { err: error },
313
446
  `BaseModel.dispatchEvent: Error executing event '${eventName}' for model '${model.uid}':`
314
447
  );
315
- await this.engine.emitter.emitAsync(`model:event:${eventName}:error`, {
316
- uid: model.uid,
317
- model,
318
- runId,
319
- inputArgs,
448
+ await this.emitModelEventIf(eventName, "error", {
449
+ ...eventBasePayload,
320
450
  error
321
451
  });
322
452
  if (throwOnError) throw error;
453
+ } finally {
454
+ for (const cancel of scheduledCancels) {
455
+ cancel();
456
+ }
323
457
  }
324
458
  }
325
459
  };
@@ -74,6 +74,7 @@ var import_utils = require("./utils");
74
74
  var import_exceptions = require("./utils/exceptions");
75
75
  var import_params_resolvers = require("./utils/params-resolvers");
76
76
  var import_serverContextParams = require("./utils/serverContextParams");
77
+ var import_variablesParams = require("./utils/variablesParams");
77
78
  var import_registry = require("./runjs-context/registry");
78
79
  var import_createEphemeralContext = require("./utils/createEphemeralContext");
79
80
  var import_dayjs = __toESM(require("dayjs"));
@@ -96,6 +97,50 @@ function filterBuilderOutputByPaths(built, neededPaths) {
96
97
  return void 0;
97
98
  }
98
99
  __name(filterBuilderOutputByPaths, "filterBuilderOutputByPaths");
100
+ function topLevelOf(subPath) {
101
+ if (!subPath) return void 0;
102
+ const m = String(subPath).match(/^([^.[]+)/);
103
+ return m == null ? void 0 : m[1];
104
+ }
105
+ __name(topLevelOf, "topLevelOf");
106
+ function inferSelectsFromUsage(paths = []) {
107
+ if (!Array.isArray(paths) || paths.length === 0) {
108
+ return { generatedAppends: void 0, generatedFields: void 0 };
109
+ }
110
+ const appendSet = /* @__PURE__ */ new Set();
111
+ const fieldSet = /* @__PURE__ */ new Set();
112
+ const normalizePath = /* @__PURE__ */ __name((raw) => {
113
+ if (!raw) return "";
114
+ let s = String(raw);
115
+ s = s.replace(/\[(?:\d+)\]/g, "");
116
+ s = s.replace(/\[(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')\]/g, (_m, g1, g2) => `.${g1 || g2}`);
117
+ s = s.replace(/\.\.+/g, ".");
118
+ s = s.replace(/^\./, "").replace(/\.$/, "");
119
+ return s;
120
+ }, "normalizePath");
121
+ for (let path of paths) {
122
+ if (!path) continue;
123
+ while (/^\[(\d+)\](\.|$)/.test(path)) {
124
+ path = path.replace(/^\[(\d+)\]\.?/, "");
125
+ }
126
+ const norm = normalizePath(path);
127
+ if (!norm) continue;
128
+ const segments = norm.split(".").filter(Boolean);
129
+ if (segments.length === 0) continue;
130
+ if (segments.length === 1) {
131
+ fieldSet.add(segments[0]);
132
+ continue;
133
+ }
134
+ for (let i = 0; i < segments.length - 1; i++) {
135
+ appendSet.add(segments.slice(0, i + 1).join("."));
136
+ }
137
+ fieldSet.add(segments.join("."));
138
+ }
139
+ const generatedAppends = appendSet.size ? Array.from(appendSet) : void 0;
140
+ const generatedFields = fieldSet.size ? Array.from(fieldSet) : void 0;
141
+ return { generatedAppends, generatedFields };
142
+ }
143
+ __name(inferSelectsFromUsage, "inferSelectsFromUsage");
99
144
  const _FlowContext = class _FlowContext {
100
145
  constructor() {
101
146
  __privateAdd(this, _FlowContext_instances);
@@ -745,6 +790,21 @@ const _FlowEngineContext = class _FlowEngineContext extends BaseFlowEngineContex
745
790
  const needServer = Object.keys(serverVarPaths).length > 0;
746
791
  let serverResolved = template;
747
792
  if (needServer) {
793
+ const inferRecordRefWithMeta = /* @__PURE__ */ __name((ctx) => {
794
+ var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
795
+ const ref = (0, import_variablesParams.inferRecordRef)(ctx);
796
+ if (ref) return ref;
797
+ try {
798
+ const tk = (_b2 = (_a2 = ctx == null ? void 0 : ctx.resource) == null ? void 0 : _a2.getMeta) == null ? void 0 : _b2.call(_a2, "currentFilterByTk");
799
+ if (typeof tk === "undefined" || tk === null) return void 0;
800
+ const collection = ((_c = ctx == null ? void 0 : ctx.collection) == null ? void 0 : _c.name) || ((_j = (_i = (_h = (_g = (_f = (_e = (_d = ctx == null ? void 0 : ctx.resource) == null ? void 0 : _d.getResourceName) == null ? void 0 : _e.call(_d)) == null ? void 0 : _f.split) == null ? void 0 : _g.call(_f, ".")) == null ? void 0 : _h.slice) == null ? void 0 : _i.call(_h, -1)) == null ? void 0 : _j[0]);
801
+ if (!collection) return void 0;
802
+ const dataSourceKey = ((_k = ctx == null ? void 0 : ctx.collection) == null ? void 0 : _k.dataSourceKey) || ((_m = (_l = ctx == null ? void 0 : ctx.resource) == null ? void 0 : _l.getDataSourceKey) == null ? void 0 : _m.call(_l));
803
+ return { collection, dataSourceKey, filterByTk: tk };
804
+ } catch (_2) {
805
+ return void 0;
806
+ }
807
+ }, "inferRecordRefWithMeta");
748
808
  const collectFromMeta = /* @__PURE__ */ __name(async () => {
749
809
  var _a2;
750
810
  const out = {};
@@ -780,6 +840,43 @@ const _FlowEngineContext = class _FlowEngineContext extends BaseFlowEngineContex
780
840
  }, "collectFromMeta");
781
841
  const inputFromMeta = await collectFromMeta();
782
842
  const autoInput = { ...inputFromMeta };
843
+ try {
844
+ const varName = "formValues";
845
+ const neededPaths = serverVarPaths[varName] || [];
846
+ if (neededPaths.length) {
847
+ const requiredTop = /* @__PURE__ */ new Set();
848
+ for (const p of neededPaths) {
849
+ const top = topLevelOf(p);
850
+ if (top) requiredTop.add(top);
851
+ }
852
+ const metaOut = inputFromMeta == null ? void 0 : inputFromMeta[varName];
853
+ const builtTop = /* @__PURE__ */ new Set();
854
+ if (metaOut && typeof metaOut === "object" && !Array.isArray(metaOut) && !isRecordRefLike(metaOut)) {
855
+ Object.keys(metaOut).forEach((k) => builtTop.add(k));
856
+ }
857
+ const missing = [...requiredTop].filter((k) => !builtTop.has(k));
858
+ if (missing.length) {
859
+ const ref = inferRecordRefWithMeta(this);
860
+ if (ref) {
861
+ const { generatedFields, generatedAppends } = inferSelectsFromUsage(neededPaths);
862
+ const recordRef = {
863
+ ...ref,
864
+ fields: generatedFields,
865
+ appends: generatedAppends
866
+ };
867
+ const existing = autoInput[varName];
868
+ if (existing && typeof existing === "object" && !Array.isArray(existing) && !isRecordRefLike(existing)) {
869
+ for (const [k, v] of Object.entries(existing)) {
870
+ autoInput[`${varName}.${k}`] = v;
871
+ }
872
+ delete autoInput[varName];
873
+ }
874
+ autoInput[varName] = recordRef;
875
+ }
876
+ }
877
+ }
878
+ } catch (_2) {
879
+ }
783
880
  const autoContextParams = Object.keys(autoInput).length ? (0, import_serverContextParams.buildServerContextParams)(this, autoInput) : void 0;
784
881
  if (!autoContextParams) {
785
882
  const keys = Object.keys(serverVarPaths);
package/lib/provider.js CHANGED
@@ -97,9 +97,10 @@ const FlowEngineGlobalsContextProvider = /* @__PURE__ */ __name(({ children }) =
97
97
  const useFlowEngine = /* @__PURE__ */ __name(({ throwError = true } = {}) => {
98
98
  const context = (0, import_react.useContext)(FlowEngineReactContext);
99
99
  if (!context && throwError) {
100
- throw new Error(
100
+ console.warn(
101
101
  "useFlowEngine must be used within a FlowEngineProvider, and FlowEngineProvider must be supplied with an engine."
102
102
  );
103
+ return;
103
104
  }
104
105
  return context;
105
106
  }, "useFlowEngine");
@@ -22,6 +22,8 @@ export interface LifecycleEvent {
22
22
  error?: any;
23
23
  inputArgs?: Record<string, any>;
24
24
  result?: any;
25
+ flowKey?: string;
26
+ stepKey?: string;
25
27
  }
26
28
  export declare class ModelOperationScheduler {
27
29
  private engine;