@meshflow/core 0.1.8 → 0.2.1

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/README.md CHANGED
@@ -61,7 +61,7 @@ const engine = useMeshFlow<Ref<number,number>,AllPath>('main',schema, {
61
61
  // useGreedy:true
62
62
  // },
63
63
  UITrigger:{//以vue为例
64
- signalCreateor: () => ref(0),
64
+ signalCreator: () => ref(0),
65
65
  signalTrigger(signal) {
66
66
  signal.value++;
67
67
  },
package/index.d.mts CHANGED
@@ -3,6 +3,23 @@ interface MeshErrorContext {
3
3
  error: any;
4
4
  }
5
5
 
6
+ declare enum DefaultStarategy {
7
+ OR = "OR",
8
+ PRIORITY = "PRIORITY"
9
+ }
10
+
11
+ type Unwrap<T> = T extends ReadonlyArray<infer U> ? U : T;
12
+ type InferLeafPath<T, Prefix extends string = ""> = Unwrap<T> extends infer Node ? Node extends {
13
+ readonly name: infer N;
14
+ } ? N extends string ? N extends "" ? Node extends {
15
+ readonly children: infer C;
16
+ } ? InferLeafPath<C, Prefix> : never : (Node extends {
17
+ readonly children: infer C;
18
+ } ? InferLeafPath<C, Prefix extends "" ? N : `${Prefix}.${N}`> : (Prefix extends "" ? N : `${Prefix}.${N}`)) : N extends number | symbol ? Node extends {
19
+ readonly children: infer C;
20
+ } ? InferLeafPath<C, Prefix> : N : never : never : never;
21
+ type KeysOfUnion<T> = T extends any ? keyof T : never;
22
+
6
23
  interface MeshEvents {
7
24
  'node:start': {
8
25
  path: MeshPath;
@@ -91,179 +108,79 @@ interface MeshBucket<P> {
91
108
  evaluate: (context: any) => Promise<any> | any;
92
109
  [key: string]: any;
93
110
  }
94
- interface MeshFlowTaskNode<P extends MeshPath = MeshPath, S = any, V = any> {
111
+ interface MeshFlowTaskNode<P extends MeshPath = MeshPath, V = any, S = any> {
95
112
  path: P;
96
113
  uid: number;
97
114
  type: string;
98
115
  state: {
99
116
  value: V;
100
117
  };
101
- buckets: Record<string, MeshBucket<P>>;
118
+ nodeBucket: Record<keyof S, MeshBucket<P>>;
102
119
  notifyKeys: Set<keyof S>;
103
120
  dirtySignal: any;
104
121
  meta: S;
105
122
  dependOn: (cb: (val: V) => V) => void;
123
+ createView: (extraProps?: Record<string, any>) => any;
106
124
  }
107
125
  interface MeshFlowGroupNode<P extends MeshPath = MeshPath> {
108
126
  path: P;
109
127
  uid: number;
110
128
  type: 'group';
111
129
  children: Array<P>;
130
+ dirtySignal: any;
112
131
  meta: Record<string, any>;
113
132
  }
114
133
  interface DependOnContext<P extends MeshPath> {
115
134
  path: P;
116
135
  getNode: (path: P) => MeshFlowTaskNode<P>;
117
136
  }
118
-
119
- type ContractType = 'boolean' | 'scalar' | 'array' | 'object';
120
- declare enum DefaultStarategy {
121
- OR = "OR",
122
- PRIORITY = "PRIORITY"
123
- }
124
- declare class SchemaBucket<P> {
125
- private path;
126
- private strategy;
127
- contract: ContractType;
128
- private rules;
129
- private isValue;
130
- private id;
131
- private cache;
132
- private pendingPromise;
133
- private version;
134
- private deps;
135
- private _forceNotify;
136
- promiseToken: any;
137
- private effectArray;
138
- constructor(baseValue: any, key: string, path: P);
139
- forceNotify(): void;
140
- isForceNotify(): boolean;
141
- setStrategy(type: DefaultStarategy): void;
142
- setDefaultRule(value: any): void;
143
- setRules(value: any, DepsArray?: Array<[P, any]>): () => void;
144
- updateDeps(DepsArray: Array<[P, any]>): void;
145
- setRule(value: any, DepsArray?: Array<[P, any]>): (() => void) | undefined;
146
- setSideEffect(data: {
147
- fn: (args: any[]) => any;
148
- args: any[];
149
- }): void;
150
- getSideEffect(): {
151
- fn: (args: any) => any;
152
- args: any[];
153
- }[];
154
- evaluate(api: any): any;
155
- private finalizeSync;
156
- private inferType;
157
- }
158
-
159
- type FinalFlatten<T> = T extends infer O ? {
160
- [K in keyof O]: O[K];
161
- } : never;
162
- type Unwrap<T> = T extends ReadonlyArray<infer U> ? U : T;
163
- type InferLeafPath<T, Prefix extends string = ""> = Unwrap<T> extends infer Node ? Node extends {
164
- readonly name: infer N;
165
- } ? N extends string ? N extends "" ? Node extends {
166
- readonly children: infer C;
167
- } ? InferLeafPath<C, Prefix> : never : (Node extends {
168
- readonly children: infer C;
169
- } ? InferLeafPath<C, Prefix extends "" ? N : `${Prefix}.${N}`> : (Prefix extends "" ? N : `${Prefix}.${N}`)) : N extends number | symbol ? Node extends {
170
- readonly children: infer C;
171
- } ? InferLeafPath<C, Prefix> : N : never : never : never;
172
- type KeysOfUnion<T> = T extends any ? keyof T : never;
173
-
174
- type BaseField = {
175
- label: string;
176
- name: string;
177
- placeholder?: string;
178
- disabled: boolean;
179
- readonly: boolean;
180
- hidden?: boolean;
181
- validators?: any;
182
- theme?: string;
183
- };
184
- type InputField = BaseField & {
185
- type: "input" | "number";
186
- required: boolean;
187
- min?: number;
188
- maxLength: number;
189
- value: string | number;
190
- };
191
- type CheckboxField = BaseField & {
192
- type: "checkbox";
193
- description?: string;
194
- required: boolean;
195
- value: boolean;
196
- };
197
- type SelectField = BaseField & {
198
- type: "select";
199
- required: boolean;
200
- options: {
201
- label: string;
202
- value: any;
203
- }[];
204
- value: any;
205
- };
206
- type GroupField = Omit<BaseField, "label" | "name" | "placeholder" | "validators"> & {
207
- type: "group";
208
- name?: string;
209
- children: FormFieldSchema[];
210
- };
211
- type FormFieldSchema = InputField | CheckboxField | SelectField | GroupField;
212
- type RenderSchemaExtraCommonType<P = any> = {
213
- path: P;
214
- dirtySignal: any;
215
- uid: number;
216
- nodeBucket: Record<string, SchemaBucket<P>>;
217
- dependOn: (cb: (...args: any) => void) => void;
218
- };
219
- type RenderSchemaFn<T> = FinalFlatten<T extends GroupField ? Omit<T, "children"> & RenderSchemaExtraCommonType & {
220
- children: Array<RenderSchemaFn<FormFieldSchema>>;
221
- } : T & RenderSchemaExtraCommonType>;
222
- type RenderSchema = RenderSchemaFn<FormFieldSchema>;
223
-
224
137
  interface logicApi {
225
138
  slot: {
226
139
  triggerTargets: any;
227
140
  affectedTatget: any;
228
141
  };
229
142
  }
143
+ interface SetRuleOptions<NM> {
144
+ value?: any;
145
+ priority?: number;
146
+ forceNotify?: boolean;
147
+ logic: (api: logicApi) => any;
148
+ effect?: (args: any) => any;
149
+ effectArgs?: Array<KeysOfUnion<NM>>;
150
+ }
230
151
 
231
- declare function useEngineInstance<T, P extends MeshPath>(data: any, options: {
152
+ /**
153
+ * 🌟 入口函数
154
+ * @template T - UI 信号类型 (Signal)
155
+ * @template P - 路径联合类型 ("user.name" | "user.age") 也支持number或者symbol
156
+ * @template S - 业务元数据类型 (默认使用表单的 Meta,但也允许传入 any)
157
+ */
158
+ declare function useEngineInstance<T, P extends MeshPath, S = any, NM = any>(data: S, options: {
232
159
  config: {
233
160
  useGreedy: boolean;
234
161
  };
235
162
  UITrigger: {
236
- signalCreateor: () => T;
163
+ signalCreator: () => T;
237
164
  signalTrigger: (signal: T) => void;
238
165
  };
239
166
  modules: {
240
167
  useHistory?: () => MeshFlowHistory;
168
+ useInternalForm?: <T, P>(scheduler: any, data: any) => any;
169
+ useSchemaValidators?: <P>(Finder: (path: P) => any) => {
170
+ SetValidators: (path: P, options: {
171
+ logic: (val: any, GetByPath: any) => any;
172
+ condition: (data: any) => boolean;
173
+ }) => void;
174
+ };
241
175
  };
242
176
  plugins: {};
243
177
  }): {
244
- schema: RenderSchema;
245
- SetRule: (outDegreePath: P, inDegreePath: P, key: KeysOfUnion<InputField | CheckboxField | SelectField>, options?: {
246
- value?: any;
247
- priority?: number;
248
- forceNotify?: boolean;
249
- logic: (api: logicApi) => any;
250
- effect?: ((args: any) => any) | undefined;
251
- effectArgs?: Array<KeysOfUnion<Exclude<FormFieldSchema, GroupField>>>;
252
- } | undefined) => void;
253
- SetRules: (outDegreePaths: P[], inDegreePath: P, key: KeysOfUnion<InputField | CheckboxField | SelectField>, options?: {
254
- value?: any;
255
- priority?: number;
256
- forceNotify?: boolean;
257
- logic: (api: logicApi) => any;
258
- effect?: ((args: any) => any) | undefined;
259
- effectArgs?: Array<KeysOfUnion<Exclude<FormFieldSchema, GroupField>>>;
260
- } | undefined) => void;
261
- SetStrategy: (path: unknown, key: KeysOfUnion<Exclude<FormFieldSchema, GroupField>>, strategy: DefaultStarategy) => void;
262
- SetValidators: (path: P, options: {
263
- logic: (val: any, GetByPath: any) => any;
264
- condition: (data: any) => boolean;
265
- }) => void;
266
- SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => () => void;
178
+ SetRule: <K extends KeysOfUnion<NM>>(outDegreePath: P, inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
179
+ SetRules: <K extends KeysOfUnion<NM>>(outDegreePaths: P[], inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
180
+ SetStrategy: (path: P, key: KeysOfUnion<NM>, strategy: DefaultStarategy) => void;
181
+ SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => {
182
+ cancel: () => void;
183
+ };
267
184
  usePlugin: (plugin: {
268
185
  apply: (api: {
269
186
  on: (event: MeshEventName, cb: Function) => () => boolean;
@@ -271,13 +188,18 @@ declare function useEngineInstance<T, P extends MeshPath>(data: any, options: {
271
188
  }) => () => void;
272
189
  SetValue: (path: P, value: any) => void;
273
190
  GetValue: (path: P, key?: string) => any;
274
- GetFormData: () => any;
275
- GetGroupByPath: (path: MeshPath) => RenderSchema | undefined;
191
+ GetGroupByPath: (path: MeshPath) => MeshFlowGroupNode<MeshPath> | undefined;
276
192
  notifyAll: () => Promise<void>;
277
- AddNewSchema: (path: string, data: any) => RenderSchema;
278
193
  GetAllDependency: () => Map<P, Set<P>>;
279
194
  GetDependencyOrder: () => P[][];
280
195
  historyExports: Partial<MeshFlowHistory>;
196
+ formExports: {};
197
+ validatorExports: {
198
+ SetValidators?: (path: P, options: {
199
+ logic: (val: any, GetByPath: any) => any;
200
+ condition: (data: any) => boolean;
201
+ }) => void;
202
+ };
281
203
  onError: (cb: (error: MeshErrorContext) => void) => () => void;
282
204
  onSuccess: (cb: (data: unknown) => void) => () => void;
283
205
  onStart: (cb: (data: {
@@ -285,62 +207,89 @@ declare function useEngineInstance<T, P extends MeshPath>(data: any, options: {
285
207
  }) => void) => () => void;
286
208
  };
287
209
 
288
- type SchedulerType<T, P extends MeshPath> = ReturnType<typeof useEngineInstance<T, P>>;
289
- type GetType<T, P> = P extends keyof T ? T[P] : never;
210
+ type SchedulerType<T, P extends MeshPath, S, NM> = ReturnType<typeof useEngineInstance<T, P, S, NM>>;
290
211
  type BaseEngine<T> = {
291
212
  data: {
292
- [K in "schema" | "GetFormData" | "AddNewSchema" | 'SetValue' | 'GetValue' | 'GetGroupByPath']: GetType<T, K>;
213
+ SetValue: T extends {
214
+ SetValue: infer F;
215
+ } ? F : never;
216
+ GetValue: T extends {
217
+ GetValue: infer F;
218
+ } ? F : never;
219
+ GetGroupByPath: T extends {
220
+ GetGroupByPath: infer F;
221
+ } ? F : never;
293
222
  };
294
223
  config: {
295
- [K in "SetRule" | "SetRules" | "SetStrategy" | "SetValidators" | "notifyAll" | "SetTrace" | "usePlugin"]: GetType<T, K>;
224
+ SetRule: T extends {
225
+ SetRule: infer F;
226
+ } ? F : never;
227
+ SetRules: T extends {
228
+ SetRules: infer F;
229
+ } ? F : never;
230
+ SetStrategy: T extends {
231
+ SetStrategy: infer F;
232
+ } ? F : never;
233
+ notifyAll: T extends {
234
+ notifyAll: infer F;
235
+ } ? F : never;
236
+ SetTrace: T extends {
237
+ SetTrace: infer F;
238
+ } ? F : never;
239
+ usePlugin: T extends {
240
+ usePlugin: infer F;
241
+ } ? F : never;
296
242
  };
297
243
  dependency: {
298
- [K in 'GetAllDependency' | 'GetDependencyOrder']: GetType<T, K>;
244
+ GetAllDependency: T extends {
245
+ GetAllDependency: infer F;
246
+ } ? F : never;
247
+ GetDependencyOrder: T extends {
248
+ GetDependencyOrder: infer F;
249
+ } ? F : never;
299
250
  };
300
251
  hooks: {
301
- [K in "onError" | "onSuccess" | "onStart"]: GetType<T, K>;
252
+ onError: T extends {
253
+ onError: infer F;
254
+ } ? F : never;
255
+ onSuccess: T extends {
256
+ onSuccess: infer F;
257
+ } ? F : never;
258
+ onStart: T extends {
259
+ onStart: infer F;
260
+ } ? F : never;
302
261
  };
303
262
  };
304
- type TransformKey<T> = T extends `use${infer Rest}` ? Uncapitalize<Rest> : T;
305
- type EngineModules<M> = {
306
- [K in keyof M as TransformKey<string & K>]: M[K] extends (...args: any) => infer R ? R : never;
263
+ type TransformModuleKey<T> = T extends `use${infer Rest}` ? Uncapitalize<Rest> : T;
264
+ type MapModuleToReturn<K, F, P extends MeshPath> = K extends 'useSchemaValidators' | 'schemaValidators' ? {
265
+ SetValidators: (path: P, options: {
266
+ logic: (val: any, GetByPath: (path: P) => any) => any;
267
+ condition: (data: any) => boolean;
268
+ }) => void;
269
+ } : F extends (...args: any) => infer R ? R : any;
270
+ type EngineModules<M, P extends MeshPath> = {
271
+ [K in keyof M as TransformModuleKey<string & K>]: MapModuleToReturn<K, M[K], P>;
307
272
  };
308
- type Engine<T, M> = BaseEngine<T> & EngineModules<M>;
273
+ type Engine<T, M, P extends MeshPath> = BaseEngine<T> & EngineModules<M, P>;
309
274
  /** @deprecated 请使用新的 useMeshFlow 别名 */
310
275
  declare const useEngineManager: <const S extends Record<string, any>, T, //UITrigger的类型
311
- M extends Record<string, any>, P extends MeshPath = [InferLeafPath<S>] extends [never] ? MeshPath : InferLeafPath<S> | (string & {})>(id: MeshPath, Schema: S, options: {
276
+ M extends Record<string, any>, NM extends Record<string, any> = Record<string, any>, P extends MeshPath = [InferLeafPath<S>] extends [never] ? MeshPath : InferLeafPath<S> | (string & {})>(id: MeshPath, Schema: S, options: {
277
+ metaType?: NM;
312
278
  config?: {
313
279
  useGreedy: boolean;
314
280
  };
315
281
  modules?: M;
316
282
  UITrigger: {
317
- signalCreateor: () => T;
283
+ signalCreator: () => T;
318
284
  signalTrigger: (signal: T) => void;
319
285
  };
320
286
  }) => Engine<{
321
- schema: RenderSchema;
322
- SetRule: (outDegreePath: P, inDegreePath: P, key: KeysOfUnion<InputField | CheckboxField | SelectField>, options?: {
323
- value?: any;
324
- priority?: number;
325
- forceNotify?: boolean;
326
- logic: (api: logicApi) => any;
327
- effect?: ((args: any) => any) | undefined;
328
- effectArgs?: Array<KeysOfUnion<Exclude<FormFieldSchema, GroupField>>>;
329
- } | undefined) => void;
330
- SetRules: (outDegreePaths: P[], inDegreePath: P, key: KeysOfUnion<InputField | CheckboxField | SelectField>, options?: {
331
- value?: any;
332
- priority?: number;
333
- forceNotify?: boolean;
334
- logic: (api: logicApi) => any;
335
- effect?: ((args: any) => any) | undefined;
336
- effectArgs?: Array<KeysOfUnion<Exclude<FormFieldSchema, GroupField>>>;
337
- } | undefined) => void;
338
- SetStrategy: (path: unknown, key: KeysOfUnion<Exclude<FormFieldSchema, GroupField>>, strategy: DefaultStarategy) => void;
339
- SetValidators: (path: P, options: {
340
- logic: (val: any, GetByPath: any) => any;
341
- condition: (data: any) => boolean;
342
- }) => void;
343
- SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => () => void;
287
+ SetRule: <K extends KeysOfUnion<NM>>(outDegreePath: P, inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
288
+ SetRules: <K extends KeysOfUnion<NM>>(outDegreePaths: P[], inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
289
+ SetStrategy: (path: P, key: KeysOfUnion<NM>, strategy: DefaultStarategy) => void;
290
+ SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => {
291
+ cancel: () => void;
292
+ };
344
293
  usePlugin: (plugin: {
345
294
  apply: (api: {
346
295
  on: (event: MeshEventName, cb: Function) => () => boolean;
@@ -348,67 +297,57 @@ M extends Record<string, any>, P extends MeshPath = [InferLeafPath<S>] extends [
348
297
  }) => () => void;
349
298
  SetValue: (path: P, value: any) => void;
350
299
  GetValue: (path: P, key?: string) => any;
351
- GetFormData: () => any;
352
- GetGroupByPath: (path: MeshPath) => RenderSchema | undefined;
300
+ GetGroupByPath: (path: MeshPath) => MeshFlowGroupNode<MeshPath> | undefined;
353
301
  notifyAll: () => Promise<void>;
354
- AddNewSchema: (path: string, data: any) => RenderSchema;
355
302
  GetAllDependency: () => Map<P, Set<P>>;
356
303
  GetDependencyOrder: () => P[][];
357
304
  historyExports: Partial<MeshFlowHistory>;
305
+ formExports: {};
306
+ validatorExports: {
307
+ SetValidators?: ((path: P, options: {
308
+ logic: (val: any, GetByPath: any) => any;
309
+ condition: (data: any) => boolean;
310
+ }) => void) | undefined;
311
+ };
358
312
  onError: (cb: (error: MeshErrorContext) => void) => () => void;
359
313
  onSuccess: (cb: (data: unknown) => void) => () => void;
360
314
  onStart: (cb: (data: {
361
315
  path: P;
362
316
  }) => void) => () => void;
363
- }, M>;
364
- declare const useMeshFlowDefiner: <P extends string>() => <T, M extends Record<string, any>>(id: MeshPath, schema: any, options: {
317
+ }, M, P>;
318
+ declare const useMeshFlowDefiner: <P extends MeshPath, NM extends Record<string, any> = any>() => <T, M extends Record<string, any>>(id: MeshPath, schema: any, options: {
319
+ metaType?: NM;
365
320
  UITrigger: {
366
- signalCreateor: () => T;
321
+ signalCreator: () => T;
367
322
  signalTrigger: (s: T) => void;
368
323
  };
369
324
  modules?: M;
370
325
  config?: any;
371
- }) => Engine<ReturnType<typeof useEngineInstance<T, P>>, M>;
326
+ }) => Engine<SchedulerType<T, P, any, NM>, M, P>;
372
327
  /**
373
328
  * 获取 Engine 实例
374
329
  * @template M 手动注入的模块映射 (例如 { useHistory: typeof useHistory })
375
- * @template K ID 类型 (支持 string | number | symbol)
330
+ * @template P ID 类型 (支持 string | number | symbol)
376
331
  */
377
- declare const useEngine: <M, ID extends keyof MeshFlowEngineMap | (MeshPath & {}) = MeshPath>(id: ID) => [M] extends [never] ? (ID extends keyof MeshFlowEngineMap ? MeshFlowEngineMap[ID] : Engine<SchedulerType<any, any>, {}>) : Engine<SchedulerType<any, any>, M>;
332
+ declare const useEngine: <M, P extends MeshPath = any, NM = any, S = any, ID extends keyof MeshFlowEngineMap | (MeshPath & {}) = MeshPath>(id: ID) => [M] extends [never] ? (ID extends keyof MeshFlowEngineMap ? MeshFlowEngineMap[ID] : Engine<SchedulerType<any, any, any, any>, {}, P>) : Engine<SchedulerType<any, P, S, NM>, M, P>;
378
333
  declare const deleteEngine: (id: MeshPath) => void;
379
- declare const useMeshFlow: <const S extends Record<string, any>, T, M extends Record<string, any>, P extends MeshPath = [InferLeafPath<S>] extends [never] ? MeshPath : InferLeafPath<S> | (string & {})>(id: MeshPath, Schema: S, options: {
334
+ declare const useMeshFlow: <const S extends Record<string, any>, T, M extends Record<string, any>, NM extends Record<string, any> = Record<string, any>, P extends MeshPath = [InferLeafPath<S>] extends [never] ? MeshPath : InferLeafPath<S> | (string & {})>(id: MeshPath, Schema: S, options: {
335
+ metaType?: NM;
380
336
  config?: {
381
337
  useGreedy: boolean;
382
338
  };
383
339
  modules?: M;
384
340
  UITrigger: {
385
- signalCreateor: () => T;
341
+ signalCreator: () => T;
386
342
  signalTrigger: (signal: T) => void;
387
343
  };
388
344
  }) => Engine<{
389
- schema: RenderSchema;
390
- SetRule: (outDegreePath: P, inDegreePath: P, key: KeysOfUnion<InputField | CheckboxField | SelectField>, options?: {
391
- value?: any;
392
- priority?: number;
393
- forceNotify?: boolean;
394
- logic: (api: logicApi) => any;
395
- effect?: ((args: any) => any) | undefined;
396
- effectArgs?: Array<KeysOfUnion<Exclude<FormFieldSchema, GroupField>>>;
397
- } | undefined) => void;
398
- SetRules: (outDegreePaths: P[], inDegreePath: P, key: KeysOfUnion<InputField | CheckboxField | SelectField>, options?: {
399
- value?: any;
400
- priority?: number;
401
- forceNotify?: boolean;
402
- logic: (api: logicApi) => any;
403
- effect?: ((args: any) => any) | undefined;
404
- effectArgs?: Array<KeysOfUnion<Exclude<FormFieldSchema, GroupField>>>;
405
- } | undefined) => void;
406
- SetStrategy: (path: unknown, key: KeysOfUnion<Exclude<FormFieldSchema, GroupField>>, strategy: DefaultStarategy) => void;
407
- SetValidators: (path: P, options: {
408
- logic: (val: any, GetByPath: any) => any;
409
- condition: (data: any) => boolean;
410
- }) => void;
411
- SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => () => void;
345
+ SetRule: <K extends KeysOfUnion<NM>>(outDegreePath: P, inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
346
+ SetRules: <K extends KeysOfUnion<NM>>(outDegreePaths: P[], inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
347
+ SetStrategy: (path: P, key: KeysOfUnion<NM>, strategy: DefaultStarategy) => void;
348
+ SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => {
349
+ cancel: () => void;
350
+ };
412
351
  usePlugin: (plugin: {
413
352
  apply: (api: {
414
353
  on: (event: MeshEventName, cb: Function) => () => boolean;
@@ -416,18 +355,23 @@ declare const useMeshFlow: <const S extends Record<string, any>, T, M extends Re
416
355
  }) => () => void;
417
356
  SetValue: (path: P, value: any) => void;
418
357
  GetValue: (path: P, key?: string) => any;
419
- GetFormData: () => any;
420
- GetGroupByPath: (path: MeshPath) => RenderSchema | undefined;
358
+ GetGroupByPath: (path: MeshPath) => MeshFlowGroupNode<MeshPath> | undefined;
421
359
  notifyAll: () => Promise<void>;
422
- AddNewSchema: (path: string, data: any) => RenderSchema;
423
360
  GetAllDependency: () => Map<P, Set<P>>;
424
361
  GetDependencyOrder: () => P[][];
425
362
  historyExports: Partial<MeshFlowHistory>;
363
+ formExports: {};
364
+ validatorExports: {
365
+ SetValidators?: ((path: P, options: {
366
+ logic: (val: any, GetByPath: any) => any;
367
+ condition: (data: any) => boolean;
368
+ }) => void) | undefined;
369
+ };
426
370
  onError: (cb: (error: MeshErrorContext) => void) => () => void;
427
371
  onSuccess: (cb: (data: unknown) => void) => () => void;
428
372
  onStart: (cb: (data: {
429
373
  path: P;
430
374
  }) => void) => () => void;
431
- }, M>;
375
+ }, M, P>;
432
376
 
433
- export { type DependOnContext, type HistoryActionItem, type MeshBucket, type MeshEmit, type MeshEventName, type MeshEvents, type MeshFlowEngineMap, type MeshFlowGroupNode, type MeshFlowHistory, type MeshFlowTaskNode, type MeshPath, deleteEngine, useEngine, useEngineManager, useMeshFlow, useMeshFlowDefiner };
377
+ export { type DependOnContext, type HistoryActionItem, type MeshBucket, type MeshEmit, type MeshEventName, type MeshEvents, type MeshFlowEngineMap, type MeshFlowGroupNode, type MeshFlowHistory, type MeshFlowTaskNode, type MeshPath, type SetRuleOptions, deleteEngine, type logicApi, useEngine, useEngineManager, useMeshFlow, useMeshFlowDefiner };
package/index.d.ts CHANGED
@@ -3,6 +3,23 @@ interface MeshErrorContext {
3
3
  error: any;
4
4
  }
5
5
 
6
+ declare enum DefaultStarategy {
7
+ OR = "OR",
8
+ PRIORITY = "PRIORITY"
9
+ }
10
+
11
+ type Unwrap<T> = T extends ReadonlyArray<infer U> ? U : T;
12
+ type InferLeafPath<T, Prefix extends string = ""> = Unwrap<T> extends infer Node ? Node extends {
13
+ readonly name: infer N;
14
+ } ? N extends string ? N extends "" ? Node extends {
15
+ readonly children: infer C;
16
+ } ? InferLeafPath<C, Prefix> : never : (Node extends {
17
+ readonly children: infer C;
18
+ } ? InferLeafPath<C, Prefix extends "" ? N : `${Prefix}.${N}`> : (Prefix extends "" ? N : `${Prefix}.${N}`)) : N extends number | symbol ? Node extends {
19
+ readonly children: infer C;
20
+ } ? InferLeafPath<C, Prefix> : N : never : never : never;
21
+ type KeysOfUnion<T> = T extends any ? keyof T : never;
22
+
6
23
  interface MeshEvents {
7
24
  'node:start': {
8
25
  path: MeshPath;
@@ -91,179 +108,79 @@ interface MeshBucket<P> {
91
108
  evaluate: (context: any) => Promise<any> | any;
92
109
  [key: string]: any;
93
110
  }
94
- interface MeshFlowTaskNode<P extends MeshPath = MeshPath, S = any, V = any> {
111
+ interface MeshFlowTaskNode<P extends MeshPath = MeshPath, V = any, S = any> {
95
112
  path: P;
96
113
  uid: number;
97
114
  type: string;
98
115
  state: {
99
116
  value: V;
100
117
  };
101
- buckets: Record<string, MeshBucket<P>>;
118
+ nodeBucket: Record<keyof S, MeshBucket<P>>;
102
119
  notifyKeys: Set<keyof S>;
103
120
  dirtySignal: any;
104
121
  meta: S;
105
122
  dependOn: (cb: (val: V) => V) => void;
123
+ createView: (extraProps?: Record<string, any>) => any;
106
124
  }
107
125
  interface MeshFlowGroupNode<P extends MeshPath = MeshPath> {
108
126
  path: P;
109
127
  uid: number;
110
128
  type: 'group';
111
129
  children: Array<P>;
130
+ dirtySignal: any;
112
131
  meta: Record<string, any>;
113
132
  }
114
133
  interface DependOnContext<P extends MeshPath> {
115
134
  path: P;
116
135
  getNode: (path: P) => MeshFlowTaskNode<P>;
117
136
  }
118
-
119
- type ContractType = 'boolean' | 'scalar' | 'array' | 'object';
120
- declare enum DefaultStarategy {
121
- OR = "OR",
122
- PRIORITY = "PRIORITY"
123
- }
124
- declare class SchemaBucket<P> {
125
- private path;
126
- private strategy;
127
- contract: ContractType;
128
- private rules;
129
- private isValue;
130
- private id;
131
- private cache;
132
- private pendingPromise;
133
- private version;
134
- private deps;
135
- private _forceNotify;
136
- promiseToken: any;
137
- private effectArray;
138
- constructor(baseValue: any, key: string, path: P);
139
- forceNotify(): void;
140
- isForceNotify(): boolean;
141
- setStrategy(type: DefaultStarategy): void;
142
- setDefaultRule(value: any): void;
143
- setRules(value: any, DepsArray?: Array<[P, any]>): () => void;
144
- updateDeps(DepsArray: Array<[P, any]>): void;
145
- setRule(value: any, DepsArray?: Array<[P, any]>): (() => void) | undefined;
146
- setSideEffect(data: {
147
- fn: (args: any[]) => any;
148
- args: any[];
149
- }): void;
150
- getSideEffect(): {
151
- fn: (args: any) => any;
152
- args: any[];
153
- }[];
154
- evaluate(api: any): any;
155
- private finalizeSync;
156
- private inferType;
157
- }
158
-
159
- type FinalFlatten<T> = T extends infer O ? {
160
- [K in keyof O]: O[K];
161
- } : never;
162
- type Unwrap<T> = T extends ReadonlyArray<infer U> ? U : T;
163
- type InferLeafPath<T, Prefix extends string = ""> = Unwrap<T> extends infer Node ? Node extends {
164
- readonly name: infer N;
165
- } ? N extends string ? N extends "" ? Node extends {
166
- readonly children: infer C;
167
- } ? InferLeafPath<C, Prefix> : never : (Node extends {
168
- readonly children: infer C;
169
- } ? InferLeafPath<C, Prefix extends "" ? N : `${Prefix}.${N}`> : (Prefix extends "" ? N : `${Prefix}.${N}`)) : N extends number | symbol ? Node extends {
170
- readonly children: infer C;
171
- } ? InferLeafPath<C, Prefix> : N : never : never : never;
172
- type KeysOfUnion<T> = T extends any ? keyof T : never;
173
-
174
- type BaseField = {
175
- label: string;
176
- name: string;
177
- placeholder?: string;
178
- disabled: boolean;
179
- readonly: boolean;
180
- hidden?: boolean;
181
- validators?: any;
182
- theme?: string;
183
- };
184
- type InputField = BaseField & {
185
- type: "input" | "number";
186
- required: boolean;
187
- min?: number;
188
- maxLength: number;
189
- value: string | number;
190
- };
191
- type CheckboxField = BaseField & {
192
- type: "checkbox";
193
- description?: string;
194
- required: boolean;
195
- value: boolean;
196
- };
197
- type SelectField = BaseField & {
198
- type: "select";
199
- required: boolean;
200
- options: {
201
- label: string;
202
- value: any;
203
- }[];
204
- value: any;
205
- };
206
- type GroupField = Omit<BaseField, "label" | "name" | "placeholder" | "validators"> & {
207
- type: "group";
208
- name?: string;
209
- children: FormFieldSchema[];
210
- };
211
- type FormFieldSchema = InputField | CheckboxField | SelectField | GroupField;
212
- type RenderSchemaExtraCommonType<P = any> = {
213
- path: P;
214
- dirtySignal: any;
215
- uid: number;
216
- nodeBucket: Record<string, SchemaBucket<P>>;
217
- dependOn: (cb: (...args: any) => void) => void;
218
- };
219
- type RenderSchemaFn<T> = FinalFlatten<T extends GroupField ? Omit<T, "children"> & RenderSchemaExtraCommonType & {
220
- children: Array<RenderSchemaFn<FormFieldSchema>>;
221
- } : T & RenderSchemaExtraCommonType>;
222
- type RenderSchema = RenderSchemaFn<FormFieldSchema>;
223
-
224
137
  interface logicApi {
225
138
  slot: {
226
139
  triggerTargets: any;
227
140
  affectedTatget: any;
228
141
  };
229
142
  }
143
+ interface SetRuleOptions<NM> {
144
+ value?: any;
145
+ priority?: number;
146
+ forceNotify?: boolean;
147
+ logic: (api: logicApi) => any;
148
+ effect?: (args: any) => any;
149
+ effectArgs?: Array<KeysOfUnion<NM>>;
150
+ }
230
151
 
231
- declare function useEngineInstance<T, P extends MeshPath>(data: any, options: {
152
+ /**
153
+ * 🌟 入口函数
154
+ * @template T - UI 信号类型 (Signal)
155
+ * @template P - 路径联合类型 ("user.name" | "user.age") 也支持number或者symbol
156
+ * @template S - 业务元数据类型 (默认使用表单的 Meta,但也允许传入 any)
157
+ */
158
+ declare function useEngineInstance<T, P extends MeshPath, S = any, NM = any>(data: S, options: {
232
159
  config: {
233
160
  useGreedy: boolean;
234
161
  };
235
162
  UITrigger: {
236
- signalCreateor: () => T;
163
+ signalCreator: () => T;
237
164
  signalTrigger: (signal: T) => void;
238
165
  };
239
166
  modules: {
240
167
  useHistory?: () => MeshFlowHistory;
168
+ useInternalForm?: <T, P>(scheduler: any, data: any) => any;
169
+ useSchemaValidators?: <P>(Finder: (path: P) => any) => {
170
+ SetValidators: (path: P, options: {
171
+ logic: (val: any, GetByPath: any) => any;
172
+ condition: (data: any) => boolean;
173
+ }) => void;
174
+ };
241
175
  };
242
176
  plugins: {};
243
177
  }): {
244
- schema: RenderSchema;
245
- SetRule: (outDegreePath: P, inDegreePath: P, key: KeysOfUnion<InputField | CheckboxField | SelectField>, options?: {
246
- value?: any;
247
- priority?: number;
248
- forceNotify?: boolean;
249
- logic: (api: logicApi) => any;
250
- effect?: ((args: any) => any) | undefined;
251
- effectArgs?: Array<KeysOfUnion<Exclude<FormFieldSchema, GroupField>>>;
252
- } | undefined) => void;
253
- SetRules: (outDegreePaths: P[], inDegreePath: P, key: KeysOfUnion<InputField | CheckboxField | SelectField>, options?: {
254
- value?: any;
255
- priority?: number;
256
- forceNotify?: boolean;
257
- logic: (api: logicApi) => any;
258
- effect?: ((args: any) => any) | undefined;
259
- effectArgs?: Array<KeysOfUnion<Exclude<FormFieldSchema, GroupField>>>;
260
- } | undefined) => void;
261
- SetStrategy: (path: unknown, key: KeysOfUnion<Exclude<FormFieldSchema, GroupField>>, strategy: DefaultStarategy) => void;
262
- SetValidators: (path: P, options: {
263
- logic: (val: any, GetByPath: any) => any;
264
- condition: (data: any) => boolean;
265
- }) => void;
266
- SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => () => void;
178
+ SetRule: <K extends KeysOfUnion<NM>>(outDegreePath: P, inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
179
+ SetRules: <K extends KeysOfUnion<NM>>(outDegreePaths: P[], inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
180
+ SetStrategy: (path: P, key: KeysOfUnion<NM>, strategy: DefaultStarategy) => void;
181
+ SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => {
182
+ cancel: () => void;
183
+ };
267
184
  usePlugin: (plugin: {
268
185
  apply: (api: {
269
186
  on: (event: MeshEventName, cb: Function) => () => boolean;
@@ -271,13 +188,18 @@ declare function useEngineInstance<T, P extends MeshPath>(data: any, options: {
271
188
  }) => () => void;
272
189
  SetValue: (path: P, value: any) => void;
273
190
  GetValue: (path: P, key?: string) => any;
274
- GetFormData: () => any;
275
- GetGroupByPath: (path: MeshPath) => RenderSchema | undefined;
191
+ GetGroupByPath: (path: MeshPath) => MeshFlowGroupNode<MeshPath> | undefined;
276
192
  notifyAll: () => Promise<void>;
277
- AddNewSchema: (path: string, data: any) => RenderSchema;
278
193
  GetAllDependency: () => Map<P, Set<P>>;
279
194
  GetDependencyOrder: () => P[][];
280
195
  historyExports: Partial<MeshFlowHistory>;
196
+ formExports: {};
197
+ validatorExports: {
198
+ SetValidators?: (path: P, options: {
199
+ logic: (val: any, GetByPath: any) => any;
200
+ condition: (data: any) => boolean;
201
+ }) => void;
202
+ };
281
203
  onError: (cb: (error: MeshErrorContext) => void) => () => void;
282
204
  onSuccess: (cb: (data: unknown) => void) => () => void;
283
205
  onStart: (cb: (data: {
@@ -285,62 +207,89 @@ declare function useEngineInstance<T, P extends MeshPath>(data: any, options: {
285
207
  }) => void) => () => void;
286
208
  };
287
209
 
288
- type SchedulerType<T, P extends MeshPath> = ReturnType<typeof useEngineInstance<T, P>>;
289
- type GetType<T, P> = P extends keyof T ? T[P] : never;
210
+ type SchedulerType<T, P extends MeshPath, S, NM> = ReturnType<typeof useEngineInstance<T, P, S, NM>>;
290
211
  type BaseEngine<T> = {
291
212
  data: {
292
- [K in "schema" | "GetFormData" | "AddNewSchema" | 'SetValue' | 'GetValue' | 'GetGroupByPath']: GetType<T, K>;
213
+ SetValue: T extends {
214
+ SetValue: infer F;
215
+ } ? F : never;
216
+ GetValue: T extends {
217
+ GetValue: infer F;
218
+ } ? F : never;
219
+ GetGroupByPath: T extends {
220
+ GetGroupByPath: infer F;
221
+ } ? F : never;
293
222
  };
294
223
  config: {
295
- [K in "SetRule" | "SetRules" | "SetStrategy" | "SetValidators" | "notifyAll" | "SetTrace" | "usePlugin"]: GetType<T, K>;
224
+ SetRule: T extends {
225
+ SetRule: infer F;
226
+ } ? F : never;
227
+ SetRules: T extends {
228
+ SetRules: infer F;
229
+ } ? F : never;
230
+ SetStrategy: T extends {
231
+ SetStrategy: infer F;
232
+ } ? F : never;
233
+ notifyAll: T extends {
234
+ notifyAll: infer F;
235
+ } ? F : never;
236
+ SetTrace: T extends {
237
+ SetTrace: infer F;
238
+ } ? F : never;
239
+ usePlugin: T extends {
240
+ usePlugin: infer F;
241
+ } ? F : never;
296
242
  };
297
243
  dependency: {
298
- [K in 'GetAllDependency' | 'GetDependencyOrder']: GetType<T, K>;
244
+ GetAllDependency: T extends {
245
+ GetAllDependency: infer F;
246
+ } ? F : never;
247
+ GetDependencyOrder: T extends {
248
+ GetDependencyOrder: infer F;
249
+ } ? F : never;
299
250
  };
300
251
  hooks: {
301
- [K in "onError" | "onSuccess" | "onStart"]: GetType<T, K>;
252
+ onError: T extends {
253
+ onError: infer F;
254
+ } ? F : never;
255
+ onSuccess: T extends {
256
+ onSuccess: infer F;
257
+ } ? F : never;
258
+ onStart: T extends {
259
+ onStart: infer F;
260
+ } ? F : never;
302
261
  };
303
262
  };
304
- type TransformKey<T> = T extends `use${infer Rest}` ? Uncapitalize<Rest> : T;
305
- type EngineModules<M> = {
306
- [K in keyof M as TransformKey<string & K>]: M[K] extends (...args: any) => infer R ? R : never;
263
+ type TransformModuleKey<T> = T extends `use${infer Rest}` ? Uncapitalize<Rest> : T;
264
+ type MapModuleToReturn<K, F, P extends MeshPath> = K extends 'useSchemaValidators' | 'schemaValidators' ? {
265
+ SetValidators: (path: P, options: {
266
+ logic: (val: any, GetByPath: (path: P) => any) => any;
267
+ condition: (data: any) => boolean;
268
+ }) => void;
269
+ } : F extends (...args: any) => infer R ? R : any;
270
+ type EngineModules<M, P extends MeshPath> = {
271
+ [K in keyof M as TransformModuleKey<string & K>]: MapModuleToReturn<K, M[K], P>;
307
272
  };
308
- type Engine<T, M> = BaseEngine<T> & EngineModules<M>;
273
+ type Engine<T, M, P extends MeshPath> = BaseEngine<T> & EngineModules<M, P>;
309
274
  /** @deprecated 请使用新的 useMeshFlow 别名 */
310
275
  declare const useEngineManager: <const S extends Record<string, any>, T, //UITrigger的类型
311
- M extends Record<string, any>, P extends MeshPath = [InferLeafPath<S>] extends [never] ? MeshPath : InferLeafPath<S> | (string & {})>(id: MeshPath, Schema: S, options: {
276
+ M extends Record<string, any>, NM extends Record<string, any> = Record<string, any>, P extends MeshPath = [InferLeafPath<S>] extends [never] ? MeshPath : InferLeafPath<S> | (string & {})>(id: MeshPath, Schema: S, options: {
277
+ metaType?: NM;
312
278
  config?: {
313
279
  useGreedy: boolean;
314
280
  };
315
281
  modules?: M;
316
282
  UITrigger: {
317
- signalCreateor: () => T;
283
+ signalCreator: () => T;
318
284
  signalTrigger: (signal: T) => void;
319
285
  };
320
286
  }) => Engine<{
321
- schema: RenderSchema;
322
- SetRule: (outDegreePath: P, inDegreePath: P, key: KeysOfUnion<InputField | CheckboxField | SelectField>, options?: {
323
- value?: any;
324
- priority?: number;
325
- forceNotify?: boolean;
326
- logic: (api: logicApi) => any;
327
- effect?: ((args: any) => any) | undefined;
328
- effectArgs?: Array<KeysOfUnion<Exclude<FormFieldSchema, GroupField>>>;
329
- } | undefined) => void;
330
- SetRules: (outDegreePaths: P[], inDegreePath: P, key: KeysOfUnion<InputField | CheckboxField | SelectField>, options?: {
331
- value?: any;
332
- priority?: number;
333
- forceNotify?: boolean;
334
- logic: (api: logicApi) => any;
335
- effect?: ((args: any) => any) | undefined;
336
- effectArgs?: Array<KeysOfUnion<Exclude<FormFieldSchema, GroupField>>>;
337
- } | undefined) => void;
338
- SetStrategy: (path: unknown, key: KeysOfUnion<Exclude<FormFieldSchema, GroupField>>, strategy: DefaultStarategy) => void;
339
- SetValidators: (path: P, options: {
340
- logic: (val: any, GetByPath: any) => any;
341
- condition: (data: any) => boolean;
342
- }) => void;
343
- SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => () => void;
287
+ SetRule: <K extends KeysOfUnion<NM>>(outDegreePath: P, inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
288
+ SetRules: <K extends KeysOfUnion<NM>>(outDegreePaths: P[], inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
289
+ SetStrategy: (path: P, key: KeysOfUnion<NM>, strategy: DefaultStarategy) => void;
290
+ SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => {
291
+ cancel: () => void;
292
+ };
344
293
  usePlugin: (plugin: {
345
294
  apply: (api: {
346
295
  on: (event: MeshEventName, cb: Function) => () => boolean;
@@ -348,67 +297,57 @@ M extends Record<string, any>, P extends MeshPath = [InferLeafPath<S>] extends [
348
297
  }) => () => void;
349
298
  SetValue: (path: P, value: any) => void;
350
299
  GetValue: (path: P, key?: string) => any;
351
- GetFormData: () => any;
352
- GetGroupByPath: (path: MeshPath) => RenderSchema | undefined;
300
+ GetGroupByPath: (path: MeshPath) => MeshFlowGroupNode<MeshPath> | undefined;
353
301
  notifyAll: () => Promise<void>;
354
- AddNewSchema: (path: string, data: any) => RenderSchema;
355
302
  GetAllDependency: () => Map<P, Set<P>>;
356
303
  GetDependencyOrder: () => P[][];
357
304
  historyExports: Partial<MeshFlowHistory>;
305
+ formExports: {};
306
+ validatorExports: {
307
+ SetValidators?: ((path: P, options: {
308
+ logic: (val: any, GetByPath: any) => any;
309
+ condition: (data: any) => boolean;
310
+ }) => void) | undefined;
311
+ };
358
312
  onError: (cb: (error: MeshErrorContext) => void) => () => void;
359
313
  onSuccess: (cb: (data: unknown) => void) => () => void;
360
314
  onStart: (cb: (data: {
361
315
  path: P;
362
316
  }) => void) => () => void;
363
- }, M>;
364
- declare const useMeshFlowDefiner: <P extends string>() => <T, M extends Record<string, any>>(id: MeshPath, schema: any, options: {
317
+ }, M, P>;
318
+ declare const useMeshFlowDefiner: <P extends MeshPath, NM extends Record<string, any> = any>() => <T, M extends Record<string, any>>(id: MeshPath, schema: any, options: {
319
+ metaType?: NM;
365
320
  UITrigger: {
366
- signalCreateor: () => T;
321
+ signalCreator: () => T;
367
322
  signalTrigger: (s: T) => void;
368
323
  };
369
324
  modules?: M;
370
325
  config?: any;
371
- }) => Engine<ReturnType<typeof useEngineInstance<T, P>>, M>;
326
+ }) => Engine<SchedulerType<T, P, any, NM>, M, P>;
372
327
  /**
373
328
  * 获取 Engine 实例
374
329
  * @template M 手动注入的模块映射 (例如 { useHistory: typeof useHistory })
375
- * @template K ID 类型 (支持 string | number | symbol)
330
+ * @template P ID 类型 (支持 string | number | symbol)
376
331
  */
377
- declare const useEngine: <M, ID extends keyof MeshFlowEngineMap | (MeshPath & {}) = MeshPath>(id: ID) => [M] extends [never] ? (ID extends keyof MeshFlowEngineMap ? MeshFlowEngineMap[ID] : Engine<SchedulerType<any, any>, {}>) : Engine<SchedulerType<any, any>, M>;
332
+ declare const useEngine: <M, P extends MeshPath = any, NM = any, S = any, ID extends keyof MeshFlowEngineMap | (MeshPath & {}) = MeshPath>(id: ID) => [M] extends [never] ? (ID extends keyof MeshFlowEngineMap ? MeshFlowEngineMap[ID] : Engine<SchedulerType<any, any, any, any>, {}, P>) : Engine<SchedulerType<any, P, S, NM>, M, P>;
378
333
  declare const deleteEngine: (id: MeshPath) => void;
379
- declare const useMeshFlow: <const S extends Record<string, any>, T, M extends Record<string, any>, P extends MeshPath = [InferLeafPath<S>] extends [never] ? MeshPath : InferLeafPath<S> | (string & {})>(id: MeshPath, Schema: S, options: {
334
+ declare const useMeshFlow: <const S extends Record<string, any>, T, M extends Record<string, any>, NM extends Record<string, any> = Record<string, any>, P extends MeshPath = [InferLeafPath<S>] extends [never] ? MeshPath : InferLeafPath<S> | (string & {})>(id: MeshPath, Schema: S, options: {
335
+ metaType?: NM;
380
336
  config?: {
381
337
  useGreedy: boolean;
382
338
  };
383
339
  modules?: M;
384
340
  UITrigger: {
385
- signalCreateor: () => T;
341
+ signalCreator: () => T;
386
342
  signalTrigger: (signal: T) => void;
387
343
  };
388
344
  }) => Engine<{
389
- schema: RenderSchema;
390
- SetRule: (outDegreePath: P, inDegreePath: P, key: KeysOfUnion<InputField | CheckboxField | SelectField>, options?: {
391
- value?: any;
392
- priority?: number;
393
- forceNotify?: boolean;
394
- logic: (api: logicApi) => any;
395
- effect?: ((args: any) => any) | undefined;
396
- effectArgs?: Array<KeysOfUnion<Exclude<FormFieldSchema, GroupField>>>;
397
- } | undefined) => void;
398
- SetRules: (outDegreePaths: P[], inDegreePath: P, key: KeysOfUnion<InputField | CheckboxField | SelectField>, options?: {
399
- value?: any;
400
- priority?: number;
401
- forceNotify?: boolean;
402
- logic: (api: logicApi) => any;
403
- effect?: ((args: any) => any) | undefined;
404
- effectArgs?: Array<KeysOfUnion<Exclude<FormFieldSchema, GroupField>>>;
405
- } | undefined) => void;
406
- SetStrategy: (path: unknown, key: KeysOfUnion<Exclude<FormFieldSchema, GroupField>>, strategy: DefaultStarategy) => void;
407
- SetValidators: (path: P, options: {
408
- logic: (val: any, GetByPath: any) => any;
409
- condition: (data: any) => boolean;
410
- }) => void;
411
- SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => () => void;
345
+ SetRule: <K extends KeysOfUnion<NM>>(outDegreePath: P, inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
346
+ SetRules: <K extends KeysOfUnion<NM>>(outDegreePaths: P[], inDegreePath: P, key: K, options: SetRuleOptions<NM>) => void;
347
+ SetStrategy: (path: P, key: KeysOfUnion<NM>, strategy: DefaultStarategy) => void;
348
+ SetTrace: (myPath: P, onUpdate: (newStatus: "idle" | "pending" | "calculating" | "calculated" | "error" | "canceled") => void) => {
349
+ cancel: () => void;
350
+ };
412
351
  usePlugin: (plugin: {
413
352
  apply: (api: {
414
353
  on: (event: MeshEventName, cb: Function) => () => boolean;
@@ -416,18 +355,23 @@ declare const useMeshFlow: <const S extends Record<string, any>, T, M extends Re
416
355
  }) => () => void;
417
356
  SetValue: (path: P, value: any) => void;
418
357
  GetValue: (path: P, key?: string) => any;
419
- GetFormData: () => any;
420
- GetGroupByPath: (path: MeshPath) => RenderSchema | undefined;
358
+ GetGroupByPath: (path: MeshPath) => MeshFlowGroupNode<MeshPath> | undefined;
421
359
  notifyAll: () => Promise<void>;
422
- AddNewSchema: (path: string, data: any) => RenderSchema;
423
360
  GetAllDependency: () => Map<P, Set<P>>;
424
361
  GetDependencyOrder: () => P[][];
425
362
  historyExports: Partial<MeshFlowHistory>;
363
+ formExports: {};
364
+ validatorExports: {
365
+ SetValidators?: ((path: P, options: {
366
+ logic: (val: any, GetByPath: any) => any;
367
+ condition: (data: any) => boolean;
368
+ }) => void) | undefined;
369
+ };
426
370
  onError: (cb: (error: MeshErrorContext) => void) => () => void;
427
371
  onSuccess: (cb: (data: unknown) => void) => () => void;
428
372
  onStart: (cb: (data: {
429
373
  path: P;
430
374
  }) => void) => () => void;
431
- }, M>;
375
+ }, M, P>;
432
376
 
433
- export { type DependOnContext, type HistoryActionItem, type MeshBucket, type MeshEmit, type MeshEventName, type MeshEvents, type MeshFlowEngineMap, type MeshFlowGroupNode, type MeshFlowHistory, type MeshFlowTaskNode, type MeshPath, deleteEngine, useEngine, useEngineManager, useMeshFlow, useMeshFlowDefiner };
377
+ export { type DependOnContext, type HistoryActionItem, type MeshBucket, type MeshEmit, type MeshEventName, type MeshEvents, type MeshFlowEngineMap, type MeshFlowGroupNode, type MeshFlowHistory, type MeshFlowTaskNode, type MeshPath, type SetRuleOptions, deleteEngine, type logicApi, useEngine, useEngineManager, useMeshFlow, useMeshFlowDefiner };
package/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';var ne=class{computedRules=[];store={OR:(e,n)=>{let t,l,r=this.computedRules;for(let o=0;o<r.length;o++){let a=r[o],s=a.logic(e);if(s instanceof Promise)return (async()=>{let c=await s;if(a.entityId==="__base__"?l=c:c&&(t=c),typeof t>"u")for(let u=o+1;u<r.length;u++){let h=r[u],S=h.logic(e),p=S instanceof Promise?await S:S;if(h.entityId==="__base__"){l=p;continue}if(p){t=h.value;break}}return typeof t>"u"&&(t=l),{res:t,version:n}})();let i=s;if(a.entityId==="__base__"){l=i;continue}if(i){t=a.value;break}}return typeof t>"u"&&(t=l),{res:t,version:n}},PRIORITY:(e,n)=>{let t,l=this.computedRules;for(let r=0;r<l.length;r++){let a=l[r].logic(e);if(a instanceof Promise)return (async()=>{let s=await a;if(s!==void 0)return {res:s,version:n};for(let i=r+1;i<l.length;i++){let c=l[i].logic(e),u=c instanceof Promise?await c:c;if(u!==void 0)return {res:u,version:n}}return {res:void 0,version:n}})();if(a!==void 0)return {res:a,version:n}}return {res:t,version:n}}};CurrentStrategy=()=>{};CurrentStrategyType="PRIORITY";getRules=()=>{};constructor(e){this.getRules=e,this.CurrentStrategy=this.store.PRIORITY,this.updateComputedRules();}updateComputedRules(){let e=this.getRules();this.CurrentStrategyType==="PRIORITY"?this.computedRules=Array.from(e.values()).map(n=>Array.from(n)).flat().sort((n,t)=>t.priority-n.priority):this.computedRules=Array.from(e.values()).map(n=>Array.from(n)).flat();}setStrategy(e){this.CurrentStrategy=this.store[e],this.updateComputedRules();}evaluate(e,n){return this.CurrentStrategy(e,n)}},J=class{path;strategy;contract;rules=new Map;isValue=false;id=0;cache=void 0;pendingPromise=null;version=0;deps=new Map;_forceNotify=false;promiseToken=null;effectArray=[];constructor(e,n,t){let l=()=>this.rules;this.strategy=new ne(l),this.path=t,this.isValue=n==="value",this.contract=this.inferType(e),this.cache=e,this.setRule({priority:0,entityId:"__base__",logic:()=>e});}forceNotify(){this._forceNotify=true;}isForceNotify(){return this._forceNotify}setStrategy(e){this.strategy.setStrategy(e);}setDefaultRule(e){let n=new Set;n.add(e),this.rules.set(e.id,n);}setRules(e,n){n&&this.updateDeps(n);let t=++this.id,l={...e,entityId:t};for(let r of e.triggerPaths)this.rules.has(r)||this.rules.set(r,new Set),this.rules.get(r).add(l);return this.strategy.updateComputedRules(),()=>{for(let r of e.triggerPaths){let o=this.rules.get(r);o&&(o.delete(l),o.size===0&&(this.rules.delete(r),this.deps.delete(r)));}this.strategy.updateComputedRules();}}updateDeps(e){for(let[n,t]of e)this.deps.set(n,t);}setRule(e,n){if(n&&this.updateDeps(n),typeof e.entityId=="string"){this.setDefaultRule(e);return}let t=++this.id,l={...e,entityId:t};if(e)for(let r of e.triggerPaths)this.rules.has(r)||this.rules.set(r,new Set),this.rules.get(r).add(l);return this.strategy.updateComputedRules(),()=>{for(let r of e.triggerPaths){let o=this.rules.get(r);o&&(o.delete(l),o.size===0&&(this.rules.delete(r),this.deps.delete(r)));}this.strategy.updateComputedRules();}}setSideEffect(e){this.effectArray.push(e);}getSideEffect(){return [...this.effectArray]}evaluate(e){let n=null;if(e.GetToken&&(n=e.GetToken()),this.pendingPromise&&this.promiseToken!==n&&(this.pendingPromise=null,this.promiseToken=null),this.pendingPromise)return this.pendingPromise;let t=false;if(typeof e.triggerPath=="string"){t=true;let o=this.deps.get(e.triggerPath),a=e.GetValueByPath(e.triggerPath);if(typeof o=="object"||typeof a=="object")t=false;else {let s=Array.from(this.deps.keys());for(let i of s){let c=this.deps.get(i),u=e.GetValueByPath(i);if(c!==u){t=false;break}}}}if(t)return this.cache;this.promiseToken=n;let l=++this.version,r=this.strategy.evaluate(e,l);if(!(r instanceof Promise)){let{res:o,version:a}=r;return this.finalizeSync(o,a,e,n)}return this.pendingPromise=(async()=>{try{let{res:o,version:a}=await r;return this.finalizeSync(o,a,e,n)}catch(o){throw {path:this.path,error:o}}finally{this.promiseToken===n&&(this.pendingPromise=null,this.promiseToken=null);}})(),this.pendingPromise}finalizeSync(e,n,t,l){return l!==this.promiseToken||n<this.version?this.cache:(this.cache=e,this.deps.forEach((r,o)=>{this.deps.set(o,t.GetValueByPath(o));}),e)}inferType(e){return Array.isArray(e)?"array":typeof e}},ee=class{validators=[];defaultValidators=[];path="";constructor(e){this.path=e,this.SetDefaultValidators();}setValidators(e){this.validators.push(e);}SetDefaultValidators(){let e={logic:t=>t||typeof t=="number"?true:`${this.path} undefined`,condition:t=>!!t.required},n={logic:function(t){return t.length>this.options.maxLength?`Too long:${this.options.maxLength}`:true},condition:function(t){return typeof t.maxLength!="number"?false:(n.options={maxLength:t.maxLength},t.type==="input"&&t.hidden===false)},options:{}};this.defaultValidators.push(e),this.defaultValidators.push(n);}evaluate(e,n){let t=true,l=[...this.defaultValidators,...this.validators];for(let r of l){if(!r.condition(n))continue;let a=r.logic(e);if(typeof a!="boolean"){t=a;break}}return t}};var re=(d={frameQuota:12})=>{let e=performance.now(),n=0,t=false,l=()=>!!navigator?.scheduling?.isInputPending?.({includeContinuous:true});return {getIsFirstFrame:()=>t,reset(){e=performance.now(),n=0,t=true;},shouldYield(){let r=performance.now();return n++,!!((n>=5||t)&&(n=0,r-e>d.frameQuota||l()))},async yieldToMain(){return new Promise(r=>{Te(()=>{e=performance.now(),n=0,t&&(t=false),r();});})}}},Te=d=>{let{port1:e,port2:n}=new MessageChannel;e.onmessage=d,n.postMessage(null);};function ae(d,e,n,t,l){let r=new Map,o=d.useGreedy,a=re();return async(i,c)=>{let h=Symbol("token");r.set(i,h);let S=false;a.reset();let p=new Set,T=new Set,N=new Set(e.GetAllNextDependency(i));N.add(i);let M=new Map,D=new Map,F=new Set,V=e.GetPathToLevelMap(),_=V.get(i)??0,H=0,q=G=>{e.GetAllNextDependency(G).forEach(U=>{let R=V.get(U)||0;R>H&&(H=R);});};q(i),c.forEach(G=>{F.add(G);}),p.add(i);let z=performance.now();t.emit("flow:start",{path:i}),t.callOnStart({path:i});let W=false,$=30,g=G=>{let{target:y,trigger:U}=G,R=false,k=false,C=n.GetNodeByPath(y),E=[],P=(f,m)=>{if(p.has(f)||T.has(f)||F.has(f))return;let B=0,v=V.get(f)??0;if(M.has(f))B=M.get(f)-1;else {if(v>_&&M.size>$){D.has(v)||D.set(v,new Set),D.get(v).add(f),t.emit("node:intercept",{path:f,type:7});return}let O=e.GetPrevDependency(f),L=0;for(let K of O){if(p.has(K))continue;(V.get(K)??0)>_&&L++;}B=L;}if(B<=0){let O=F.has(f),L=T.has(f);if(O||L){t.emit("node:intercept",{path:f,type:L?3:3.1});return}M.delete(f),F.add(f),t.emit("node:release",{path:f,type:m,detail:{path:y}});}else M.set(f,B);},b=(f=[])=>{if(r.get(i)!==h)return;if(f.length){let v={};for(let O of f){let L=(O.args||[]).reduce((K,I)=>(K[I]=C[I],K),{});try{let K=O.fn(L);K&&typeof K=="object"&&Object.assign(v,K);}catch(K){}}for(let O in v)C[O]=v[O];R=true;}R&&l.flushPathSet.add(y),t.emit("node:success",{path:y}),p.add(y);let m=e.GetNextDependency(y);(R||k)&&e.GetAllNextDependency(y).forEach(O=>N.add(O));for(let v of m){if(p.has(v)){t.emit("node:intercept",{path:v,type:2});continue}if(T.has(v)||F.has(v)){t.emit("node:intercept",{path:v,type:T.has(v)?3:3.1});continue}if(R||k)P(v,1);else if(M.has(v))P(v,2);else {let L=V.get(v);D.has(L)||D.set(L,new Set);let K=D.get(L);K.has(v)||(K.add(v),t.emit("node:stagnate",{path:v,type:1}));}}T.delete(y),(async()=>{if(!S){let v=T.size,O=F.size;t.emit("flow:fire",{path:y,type:1,detail:{active:v,pending:O,blocked:M.size}}),w();}})();},A=f=>{t.emit("node:error",{path:y,error:f});let m=Symbol("abort");r.set(i,m),F.clear(),M.clear(),T.clear(),t.callOnError(f);},x=(f,m)=>{let B=false;f!==C[m]&&(C[m]=f,R=true,t.emit("node:bucket:success",{path:y,key:m,value:f}),m==="value"&&(B=true)),C.nodeBucket[m].isForceNotify()&&(k=true),(B||k)&&q(y);};t.emit("node:start",{path:y});try{let f=[];for(let m in C.nodeBucket){let B=C.nodeBucket[m];f.push(...B.getSideEffect());let v=B.evaluate({affectKey:m,triggerPath:U,GetRenderSchemaByPath:n.GetNodeByPath,GetValueByPath:O=>n.GetNodeByPath(O).value,GetToken:()=>h});if(v instanceof Promise){let O=v.then(L=>{r.get(i)===h&&x(L,m);});E.push(O);}else x(v,m);}if(E.length>0)return Promise.all(E).then(()=>{b(f);}).catch(A);b(f);return}catch(f){A(f);}},w=async()=>{if(r.get(i)!==h){S=false;return}S=true;let G=a.getIsFirstFrame(),y=0,U=()=>o&&G?30:1/0,R=0,k=U();try{for(;r.get(i)===h;){let C=R>=k,E=a.shouldYield();if(C||E){if(R>0&&(y++,(G||y%2===0)&&l.requestUpdate()),await a.yieldToMain(),r.get(i)!==h)break;R=0,G=a.getIsFirstFrame();}if(F.size>0&&T.size<5){for(let P of F){if(T.size>=5||R>=k)break;let b=V.get(P)??0,A=e.GetPrevDependency(P),x=A.length>1;if((!o||x)&&b>_){F.delete(P);let m=A.filter(B=>N.has(B)&&!p.has(B)).length;M.set(P,m||0),t.emit("node:intercept",{path:P,type:m>0?4:5,detail:{targetLevel:b,currentLevel:_,pendingParentsCount:m}});continue}if(F.delete(P),T.add(P),t.emit("node:processing",{path:P}),g({target:P,trigger:i}),R++,R>=k||a.shouldYield())break}if(F.size>0)continue}if(R<k&&o&&M.size>0&&T.size<5){let P=!1,b=0;for(let[A,x]of M)if(x<=0){let f=V.get(A)??0,m=e.GetPrevDependency(A);if(f>_&&m.length>1)continue;if(M.delete(A),F.add(A),b++,P=!0,t.emit("node:release",{path:A,type:4}),b>=k)break}if(b>0)continue;if(P){if(a.shouldYield()&&(await a.yieldToMain(),r.get(i)!==h))break;continue}}if(T.size===0&&F.size===0){let P=new Set;for(let x of D.keys())P.add(x);for(let[x]of M){let f=V.get(x)??0;f>_&&P.add(f);}let b=Array.from(P).sort((x,f)=>x-f),A=b[0];if(b.length>0&&A<=H){let x=b[0];if(x<=H){_=x;let f=D.get(x);f&&(f.forEach(m=>F.add(m)),D.delete(x));for(let[m]of M)(V.get(m)??0)===x&&(M.delete(m),F.add(m),t.emit("node:release",{path:m,type:3,detail:{level:x}}));continue}}else {D.forEach((x,f)=>{x.forEach(m=>{p.add(m),t.emit("node:intercept",{path:m,type:6});});}),D.clear();for(let[x]of M)p.add(x),t.emit("node:intercept",{path:x,type:6});M.clear();break}}F.size>0&&T.size>=5&&t.emit("flow:wait",{type:2});break}}finally{if(S=false,T.size+M.size+F.size===0){if(r.get(i)===h&&!W){W=true,t.emit("flow:end",{type:1}),l.requestUpdate();let E=performance.now();t.emit("flow:success",{duration:(E-z).toFixed(2)+"ms"}),Promise.resolve().then(()=>{t.callOnSuccess();});}}else t.emit("flow:wait",{type:1,detail:{nums:T.size}});}};w();}}function se(d,e,n,t,l,r){let o=xe(d),a=0,s=new Map,i=new Map,c=new Map,u=false,h=new Set,S=false,p=true,T=null,N=g=>{let w=s.get(g);return i.get(w)},M=g=>c.get(g),D=async()=>{let g=Array.from(h);h.clear();for(let w of g){let G=N(w);r.signalTrigger(G.dirtySignal);}},F=()=>{u||(u=true,requestAnimationFrame(()=>{try{for(;h.size>0;)D();}finally{u=false;}}));},V=()=>{let g=(w,G,y)=>{if(typeof w!="object"||w===null||Array.isArray(w)){if(y.length>0){let R=y[y.length-1];G[R]=N(y.join(".")).value;}return}let U=Object.getOwnPropertyNames(w);for(let R of U)y.push(R),g(w[R],w,y),y.pop();};return g(o,null,[]),o},Y=ae({useGreedy:e.useGreedy},n,{GetNodeByPath:N},l,{requestUpdate:F,flushPathSet:h}),_=async()=>(S&&T||(S=true,T=(async()=>{let g=n.GetDependencyOrder(),w=performance.now(),G=performance.now();try{for(let U=0;U<g.length;U++){let R=g[U];await Promise.all(R.map(async k=>{let C=N(k),E=!1;for(let P in C.nodeBucket){let b=await C.nodeBucket[P].evaluate({affectKey:P,triggerPath:void 0,GetRenderSchemaByPath:N,GetValueByPath:A=>N(A).value,isSameToken:()=>!0});if(P==="options"){let A=!1,x=C.value;for(let f of b)if(f.value==x){A=!0;break}A||(C.value=void 0,E=!0);}b!==C[P]&&(C[P]=b,E=!0);}E&&h.add(k);})),performance.now()-G>12&&(await new Promise(k=>requestAnimationFrame(k)),G=performance.now());}h.size>0&&F(),p=!1;let y=performance.now();l.emit("flow:success",{duration:(y-w).toFixed(2)+"ms"}),l.callOnSuccess();}catch(y){throw l.emit("node:error",{path:y.path,error:y.error}),l.callOnError(y),y}finally{S=false,T=null,p=false;}})()),T),H=g=>{if(p)return;if(!N(g))throw Error("Node undefined");performance.now();h.add(g),F();let y=n.GetNextDependency(g);q(y,g);};function q(g,w){Y(w,g);}let z=(g,w="")=>{let G="name"in g?g.name:void 0,y=G?w===""?G:`${w}.${G}`:w,U=r.signalCreateor(),R=a++,k={getRenderSchema:P=>N(P)},C=(P,b)=>{let A=P(b),x=N(b.path),f=t.createHistoryAction([{path:b.path,value:x.value},{path:b.path,value:A}],m=>{let B=N(m.path);B.value=m.value,H(m.path);});x.value=A,t.pushIntoHistory(f),H(b.path);},E={...g,disabled:!!g.disabled,hidden:"hidden"in g?g.hidden:false,readonly:"readonly"in g?g.readonly:false,required:"required"in g?g.required:false,path:y,dirtySignal:U,uid:R,nodeBucket:{},validators:new ee(y),theme:"secondary",dependOn:P=>C(P,{...k,path:y})};return g.type==="group"&&(delete E.nodeBucket,delete E.validators,E.children=g.children.map(P=>z(P,y)),c.set(E.path,E)),s.set(E.path,E.uid),i.set(E.uid,E),E};return {schema:z(d),GetFormData:()=>V(),GetRenderSchemaByPath:N,GetGroupByPath:M,notifyAll:_,convertToRenderSchema:z}}function xe(d,e={}){let n=r=>{if(r.type=="group")return {key:r.name||"",isGroup:true,val:r.children.reduce((o,a)=>[...o,n(a)],[])};if(r.type=="input"||r.type=="number"||r.type=="select"||r.type=="checkbox")return {key:r.name,isGroup:false,val:r.value};throw Error(`undefined type:${r.type}`)},t=(r,o)=>{if(o.isGroup){let a={};o.key===""?a=r:r[o.key]=a,o.val.forEach(s=>{t(a,s);});}else r[o.key]=o.val;},l=n(d);return t(e,l),e}var oe=(d,e,n)=>{let l=r=>{let o=n.triggerPaths.map(i=>r.GetValueByPath(i)),a=Object.create(null);return Object.defineProperty(a,"triggerTargets",{get:()=>o}),Object.defineProperty(a,"affectedTatget",{get:()=>r.GetRenderSchemaByPath(d)[e]}),n.logic({slot:a})};return {value:n.value,targetPath:d,triggerPaths:n.triggerPaths,priority:n.priority??10,logic:l}},ie=(d,e,n)=>{if(!d)throw Error("");let t=d,l=(a,s)=>{e.has(a)||e.set(a,new Set),e.get(a).add(s),n.has(s)||n.set(s,new Set),n.get(s).add(a);};return {SetRule:(a,s,i,c={logic:u=>{}})=>{let u=t(s),h=oe(s,i,{...c,triggerPaths:[a]}),S=[a].map(p=>[p,t(p).value]);if(l(a,s),u.nodeBucket[i])u.nodeBucket[i].setRule(h,S),c.effect&&u.nodeBucket[i].setSideEffect({fn:c.effect,args:c.effectArgs?c.effectArgs:[i]});else {let p=new J(u[i],i,s);p.setRule(h,S),c.effect&&p.setSideEffect({fn:c.effect,args:c.effectArgs?c.effectArgs:[i]}),u.nodeBucket[i]=p;}c.forceNotify&&u.nodeBucket[i].forceNotify();},SetRules:(a,s,i,c={logic:u=>{}})=>{let u=t(s);for(let p of a)l(p,s);let h=oe(s,i,{...c,triggerPaths:a}),S=a.map(p=>[p,t(p).value]);if(u.nodeBucket[i])u.nodeBucket[i].setRules(h,S),c.effect&&u.nodeBucket[i].setSideEffect({fn:c.effect,args:c.effectArgs?c.effectArgs:[i]});else {let p=new J(u[i],i,s);p.setRules(h,S),c.effect&&p.setSideEffect({fn:c.effect,args:c.effectArgs?c.effectArgs:[i]}),u.nodeBucket[i]=p;}c.forceNotify&&u.nodeBucket[i].forceNotify();}}};var le=d=>{let e=d||void 0;if(!e)throw Error("");return {SetStrategy:(t,l,r)=>{e(t).nodeBucket[l].setStrategy(r);}}};var ce=d=>{let e=d||void 0;return {SetValidators:(t,l)=>{let r=e(t),o=(s,i,c)=>s(i,c),a=(s,i,c)=>s(i,c);if(!r.validators)throw Error("validator init error");r.validators.setValidators({logic:s=>o(l.logic,s,e),condition:typeof l.condition=="function"?s=>a(l.condition,s,e):()=>true});}}};function de(){let d=new Map,e=new Map,n=new Set,t=(o,a)=>{d.set(o,a);let s=e.get(o);s&&s(a);};return {SetTrace:(o,a)=>{e.set(o,a);let s=d.get(o)||"idle";return a(s),()=>{e.delete(o);}},useTrace:()=>({apply:a=>{a.on("flow:start",()=>{n.forEach(s=>t(s,"idle")),n.clear(),d.clear();}),a.on("node:release",({path:s,type:i})=>{(i==1||i==2)&&(n.add(s),t(s,"pending"));}),a.on("node:pending",({path:s})=>{n.add(s),(!d.has(s)||d.get(s)==="idle")&&t(s,"pending");}),a.on("node:start",({path:s})=>{n.add(s),t(s,"calculating");}),a.on("node:success",({path:s})=>{t(s,"calculated");}),a.on("node:intercept",({path:s,type:i})=>{i==3&&t(s,"calculating"),i==6&&t(s,"idle");}),a.on("node:stagnate",({path:s})=>{t(s,"pending");}),a.on("node:error",({path:s})=>t(s,"error"));}})}}function ue(d,e,n,t){let l=c=>{let u=d(),h=e(),S=new Set;return u.get(c)?.forEach(p=>S.add(p)),S.size===0?[]:Array.from(S).filter(p=>{let T=h.get(p)||new Set;return !Array.from(T).some(D=>S.has(D))})};return {GetNextDependency:c=>{let u=t();return Array.from(u.get(c)||[])},GetPrevDependency:c=>{let u=n();return Array.from(u.get(c)||[])},GetAllPrevDependency:c=>{let u=e();return Array.from(u.get(c)||[])},GetAllNextDependency:c=>{let u=d();return Array.from(u.get(c)||[])},rebuildDirectDependencyMaps:c=>{let u=new Map,h=new Map;for(let S of c){let p=l(S);u.set(S,new Set(p));for(let T of p)h.has(T)||h.set(T,new Set),h.get(T).add(S);}return {directNextMap:u,directPrevMap:h}}}}function fe(d){let e=t=>{let l=[],r=[],o=new Map,a=t.size,s=0,i=0;for(let[c,u]of t)u===0&&r.push(c);if(r.length===0&&a>0)throw Error("Circular dependency detected");for(;r.length>0;){l.push([...r]);let c=[];for(let u of r){s++,o.set(u,i);let h=d.get(u);if(h)for(let S of h){let p=t.get(S)-1;t.set(S,p),p===0&&c.push(S);}}r=c,i++;}if(s<a)throw Error("Circular dependency detected");return {steps:l,levelMap:o}};return ()=>{let t=new Map;for(let l of d.keys()){let r=Array.from(d.get(l)||[]);t.has(l)||t.set(l,0);for(let o of r){let a=t.get(o)||0;t.set(o,++a);}}return e(t)}}var X=()=>{let d=[];return {on:e=>(d.push(e),()=>{let n=d.indexOf(e);n>-1&&d.splice(n,1);}),call:e=>d.forEach(n=>n(e))}};function pe(){let{on:d,call:e}=X();return {onError:d,callOnError:e}}function ye(){let{on:d,call:e}=X();return {onSuccess:d,callOnSuccess:e}}var he=()=>{let d=new Set,e=new Map,n=(r,o)=>{e.get(r)?.forEach(a=>a(o));},t=(r,o)=>(e.has(r)||e.set(r,new Set),e.get(r).add(o),()=>e.get(r).delete(o));return {usePlugin:r=>{let o=new Set,a=(s,i)=>{let c=t(s,i);return o.add(c),c};return r.apply({on:a}),d.add(r),()=>{o.forEach(s=>s()),o.clear(),d.delete(r);}},emit:n}};function me(){let{on:d,call:e}=X();return {onStart:d,callOnStart:e}}function ge(d,e){let n=false,t=false,l=new Map,r=new Map,o=new Map,a=new Map,s=[],i=new Map,{GetNextDependency:u,GetPrevDependency:h,GetAllPrevDependency:S,GetAllNextDependency:p,rebuildDirectDependencyMaps:T}=ue(()=>l,()=>r,()=>a,()=>o),N={},M={};if(e.modules.useHistory){let{Undo:I,Redo:j,PushIntoHistory:Q,CreateHistoryAction:Z,initCanUndo:Pe,initCanRedo:Se}=e.modules.useHistory();N.pushIntoHistory=Q,N.createHistoryAction=Z,M={Undo:I,Redo:j,initCanUndo:Pe,initCanRedo:Se};}let{onError:D,callOnError:F}=pe(),{onSuccess:V,callOnSuccess:Y}=ye(),{onStart:_,callOnStart:H}=me(),{emit:q,usePlugin:z}=he(),{SetTrace:W,useTrace:$}=de(),g=$();z(g);let{schema:w,GetFormData:G,GetRenderSchemaByPath:y,GetGroupByPath:U,notifyAll:R,convertToRenderSchema:k}=se(d,{useGreedy:e.config.useGreedy},{GetDependencyOrder:()=>s,GetAllNextDependency:p,GetNextDependency:u,GetPrevDependency:h,GetAllPrevDependency:S,GetPathToLevelMap:()=>i},N,{callOnError:F,callOnSuccess:Y,callOnStart:H,emit:q},e.UITrigger),C=(I,j)=>{let Q=U(I),Z=k(j,I);return Q.children.push(Z),Q.dirtySignal.value++,Z},{SetRule:E,SetRules:P}=ie(y,l,r),{SetStrategy:b}=le(y),{SetValidators:A}=ce(y),x=fe(l),f=()=>{let I=x();s=I.steps,i=I.levelMap;},m=()=>{t||(t=true,Promise.resolve().then(()=>{if(f(),n){let{directNextMap:I,directPrevMap:j}=T(s.flat());o=I,a=j;}}).finally(()=>{t=false,n=false;}));};return {schema:w,SetRule:(...I)=>{E.apply(null,I),n=true,m();},SetRules:(...I)=>{P.apply(null,I),n=true,m();},SetStrategy:b,SetValidators:A,SetTrace:W,usePlugin:z,SetValue:(I,j)=>{y(I).dependOn(()=>j);},GetValue:(I,j="value")=>y(I)[j],GetFormData:G,GetGroupByPath:U,notifyAll:async()=>{f(),await R();},AddNewSchema:C,GetAllDependency:()=>l,GetDependencyOrder:()=>s,historyExports:M,onError:D,onSuccess:V,onStart:_}}var te=new Map,ve=(d,e,n)=>{try{if(typeof n.UITrigger.signalCreateor!="function"||typeof n.UITrigger.signalTrigger!="function")throw Error("ui trigger undefined");if(te.has(d))throw Error("engineID repeated");let t=ge(e,{config:n.config||{useGreedy:!1},UITrigger:n.UITrigger,modules:n.modules||{},plugins:{}}),{schema:l,GetFormData:r,SetRule:o,SetRules:a,SetStrategy:s,SetValidators:i,SetValue:c,GetValue:u,usePlugin:h,GetGroupByPath:S,notifyAll:p,SetTrace:T,GetAllDependency:N,GetDependencyOrder:M,AddNewSchema:D,historyExports:F,onError:V,onSuccess:Y,onStart:_}=t,q={...{config:{SetRule:o,SetRules:a,SetStrategy:s,SetValidators:i,notifyAll:p,SetTrace:T,usePlugin:h},data:{schema:l,GetFormData:r,AddNewSchema:D,SetValue:c,GetValue:u,GetGroupByPath:S},dependency:{GetAllDependency:N,GetDependencyOrder:M},hooks:{onError:V,onSuccess:Y,onStart:_}}},z=n.modules;return z&&Object.keys(z).forEach(W=>{let $=W;if($.startsWith("use")){let g=$.slice(3);$=g.charAt(0).toLowerCase()+g.slice(1);}W==="useHistory"&&F&&Object.keys(F).length>0&&(q[$]=F);}),te.set(d,q),q}catch(t){throw Error(t)}},dt=()=>(d,e,n)=>Fe(d,e,n),ut=d=>{let e=te.get(d);if(e)return e;throw Error("[MeshFlow] Engine ID not found.")},ft=d=>{te.delete(d);},Fe=ve;exports.deleteEngine=ft;exports.useEngine=ut;exports.useEngineManager=ve;exports.useMeshFlow=Fe;exports.useMeshFlowDefiner=dt;
1
+ 'use strict';var Z=class{computedRules=[];store={OR:(e,n)=>{let t,c,r=this.computedRules;for(let l=0;l<r.length;l++){let o=r[l],s=o.logic(e);if(s instanceof Promise)return (async()=>{let i=await s;if(o.entityId==="__base__"?c=i:i&&(t=i),typeof t>"u")for(let u=l+1;u<r.length;u++){let f=r[u],p=f.logic(e),P=p instanceof Promise?await p:p;if(f.entityId==="__base__"){c=P;continue}if(P){t=f.value;break}}return typeof t>"u"&&(t=c),{res:t,version:n}})();let d=s;if(o.entityId==="__base__"){c=d;continue}if(d){t=o.value;break}}return typeof t>"u"&&(t=c),{res:t,version:n}},PRIORITY:(e,n)=>{let t,c=this.computedRules;for(let r=0;r<c.length;r++){let o=c[r].logic(e);if(o instanceof Promise)return (async()=>{let s=await o;if(s!==void 0)return {res:s,version:n};for(let d=r+1;d<c.length;d++){let i=c[d].logic(e),u=i instanceof Promise?await i:i;if(u!==void 0)return {res:u,version:n}}return {res:void 0,version:n}})();if(o!==void 0)return {res:o,version:n}}return {res:t,version:n}}};CurrentStrategy=()=>{};CurrentStrategyType="PRIORITY";getRules=()=>{};constructor(e){this.getRules=e,this.CurrentStrategy=this.store.PRIORITY,this.updateComputedRules();}updateComputedRules(){let e=this.getRules();this.CurrentStrategyType==="PRIORITY"?this.computedRules=Array.from(e.values()).map(n=>Array.from(n)).flat().sort((n,t)=>t.priority-n.priority):this.computedRules=Array.from(e.values()).map(n=>Array.from(n)).flat();}setStrategy(e){this.CurrentStrategy=this.store[e],this.updateComputedRules();}evaluate(e,n){return this.CurrentStrategy(e,n)}},X=class{path;strategy;contract;rules=new Map;isValue=false;id=0;cache=void 0;pendingPromise=null;version=0;deps=new Map;_forceNotify=false;promiseToken=null;effectArray=[];constructor(e,n,t){let c=()=>this.rules;this.strategy=new Z(c),this.path=t,this.isValue=n==="value",this.contract=this.inferType(e),this.cache=e,this.setRule({priority:0,entityId:"__base__",logic:()=>e});}forceNotify(){this._forceNotify=true;}isForceNotify(){return this._forceNotify}setStrategy(e){this.strategy.setStrategy(e);}setDefaultRule(e){let n=new Set;n.add(e),this.rules.set("defaultRules",n);}setRules(e,n){n&&this.updateDeps(n);let t=++this.id,c={...e,entityId:t};for(let r of e.triggerPaths)this.rules.has(r)||this.rules.set(r,new Set),this.rules.get(r).add(c);return this.strategy.updateComputedRules(),()=>{for(let r of e.triggerPaths){let l=this.rules.get(r);l&&(l.delete(c),l.size===0&&(this.rules.delete(r),this.deps.delete(r)));}this.strategy.updateComputedRules();}}updateDeps(e){for(let[n,t]of e)this.deps.set(n,t);}setRule(e,n){if(n&&this.updateDeps(n),typeof e.entityId=="string"){this.setDefaultRule(e);return}let t=++this.id,c={...e,entityId:t};if(e)for(let r of e.triggerPaths)this.rules.has(r)||this.rules.set(r,new Set),this.rules.get(r).add(c);return this.strategy.updateComputedRules(),()=>{for(let r of e.triggerPaths){let l=this.rules.get(r);l&&(l.delete(c),l.size===0&&(this.rules.delete(r),this.deps.delete(r)));}this.strategy.updateComputedRules();}}setSideEffect(e){this.effectArray.push(e);}getSideEffect(){return [...this.effectArray]}evaluate(e){let n=null;if(e.GetToken&&(n=e.GetToken()),this.pendingPromise&&this.promiseToken!==n&&(this.pendingPromise=null,this.promiseToken=null),this.pendingPromise)return this.pendingPromise;let t=false;if(typeof e.triggerPath=="string"){t=true;let l=this.deps.get(e.triggerPath),o=e.GetValueByPath(e.triggerPath);if(typeof l=="object"||typeof o=="object")t=false;else {let s=Array.from(this.deps.keys());for(let d of s){let i=this.deps.get(d),u=e.GetValueByPath(d);if(i!==u){t=false;break}}}}if(t)return this.cache;this.promiseToken=n;let c=++this.version,r=this.strategy.evaluate(e,c);if(!(r instanceof Promise)){let{res:l,version:o}=r;return this.finalizeSync(l,o,e,n)}return this.pendingPromise=(async()=>{try{let{res:l,version:o}=await r;return this.finalizeSync(l,o,e,n)}catch(l){throw {path:this.path,error:l}}finally{this.promiseToken===n&&(this.pendingPromise=null,this.promiseToken=null);}})(),this.pendingPromise}finalizeSync(e,n,t,c){return c!==this.promiseToken||n<this.version?this.cache:(this.cache=e,this.deps.forEach((r,l)=>{this.deps.set(l,t.GetValueByPath(l));}),e)}inferType(e){return Array.isArray(e)?"array":typeof e}};var te=(a,e,n)=>{let c=r=>{let l=n.triggerPaths.map(d=>r.GetValueByPath(d).value),o=Object.create(null);return Object.defineProperty(o,"triggerTargets",{get:()=>l||[]}),Object.defineProperty(o,"affectedTatget",{get:()=>r.GetRenderSchemaByPath(a)[e]}),n.logic({slot:o})};return {value:n.value,targetPath:a,triggerPaths:n.triggerPaths,priority:n.priority??10,logic:c}},ne=(a,e,n,t)=>{if(!a)throw Error("");let c=a,r=(s,d)=>{e.has(s)||e.set(s,new Set),e.get(s).add(d),n.has(d)||n.set(d,new Set),n.get(d).add(s);};return {SetRule:(s,d,i,u={logic:()=>{}})=>{let f=c(d),p=te(d,i,{...u,triggerPaths:[s]}),P=[s].map(g=>[g,c(g).state.value]);if(r(s,d),f.nodeBucket[i])f.nodeBucket[i].setRule(p,P),u.effect&&f.nodeBucket[i].setSideEffect({fn:u.effect,args:u.effectArgs?u.effectArgs:[i]});else {let g=f.meta[i],m=new X(g,i,d);m.setRule(p,P),u.effect&&m.setSideEffect({fn:u.effect,args:u.effectArgs?u.effectArgs:[i]}),f.nodeBucket[i]=m;}f.state[i]=f.meta[i],u.forceNotify&&f.nodeBucket[i].forceNotify();},SetRules:(s,d,i,u={logic:()=>{}})=>{let f=c(d);for(let g of s)r(g,d);let p=te(d,i,{...u,triggerPaths:s}),P=s.map(g=>[g,c(g).state.value]);if(f.nodeBucket[i])f.nodeBucket[i].setRules(p,P),u.effect&&f.nodeBucket[i].setSideEffect({fn:u.effect,args:u.effectArgs?u.effectArgs:[i]});else {let g=f.meta[i],m=new X(g,i,d);m.setRules(p,P),u.effect&&m.setSideEffect({fn:u.effect,args:u.effectArgs?u.effectArgs:[i]}),f.nodeBucket[i]=m;}f.state[i]=f.meta[i],u.forceNotify&&f.nodeBucket[i].forceNotify();}}};var re=a=>{let e=a||void 0;if(!e)throw Error("");return {SetStrategy:(t,c,r)=>{e(t).nodeBucket[c].setStrategy(r);}}};function se(){let a=new Map,e=new Map,n=new Set,t=(l,o)=>{a.set(l,o);let s=e.get(l);s&&s(o);};return {SetTrace:(l,o)=>{e.set(l,o);let s=a.get(l)||"idle";return o(s),{cancel:()=>{e.delete(l);}}},useTrace:()=>({apply:o=>{o.on("flow:start",()=>{n.forEach(s=>t(s,"idle")),n.clear(),a.clear();}),o.on("node:release",({path:s,type:d})=>{(d==1||d==2)&&(n.add(s),t(s,"pending"));}),o.on("node:pending",({path:s})=>{n.add(s),(!a.has(s)||a.get(s)==="idle")&&t(s,"pending");}),o.on("node:start",({path:s})=>{n.add(s),t(s,"calculating");}),o.on("node:success",({path:s})=>{t(s,"calculated");}),o.on("node:intercept",({path:s,type:d})=>{d==3&&t(s,"calculating"),d==6&&t(s,"idle");}),o.on("node:stagnate",({path:s})=>{t(s,"pending");}),o.on("node:error",({path:s})=>t(s,"error"));}})}}function ae(a,e,n,t){let c=i=>{let u=a(),f=e(),p=new Set;return u.get(i)?.forEach(P=>p.add(P)),p.size===0?[]:Array.from(p).filter(P=>{let g=f.get(P)||new Set;return !Array.from(g).some(N=>p.has(N))})};return {GetNextDependency:i=>{let u=t();return Array.from(u.get(i)||[])},GetPrevDependency:i=>{let u=n();return Array.from(u.get(i)||[])},GetAllPrevDependency:i=>{let u=e();return Array.from(u.get(i)||[])},GetAllNextDependency:i=>{let u=a();return Array.from(u.get(i)||[])},rebuildDirectDependencyMaps:i=>{let u=new Map,f=new Map;for(let p of i){let P=c(p);u.set(p,new Set(P));for(let g of P)f.has(g)||f.set(g,new Set),f.get(g).add(p);}return {directNextMap:u,directPrevMap:f}}}}function oe(a){let e=t=>{let c=[],r=[],l=new Map,o=t.size,s=0,d=0;for(let[i,u]of t)u===0&&r.push(i);if(r.length===0&&o>0)throw Error("Circular dependency detected");for(;r.length>0;){c.push([...r]);let i=[];for(let u of r){s++,l.set(u,d);let f=a.get(u);if(f)for(let p of f){let P=t.get(p)-1;t.set(p,P),P===0&&i.push(p);}}r=i,d++;}if(s<o)throw Error("Circular dependency detected");return {steps:c,levelMap:l}};return ()=>{let t=new Map;for(let c of a.keys()){let r=Array.from(a.get(c)||[]);t.has(c)||t.set(c,0);for(let l of r){let o=t.get(l)||0;t.set(l,++o);}}return e(t)}}var q=()=>{let a=[];return {on:e=>(a.push(e),()=>{let n=a.indexOf(e);n>-1&&a.splice(n,1);}),call:e=>a.forEach(n=>{n(e);})}};function ie(){let{on:a,call:e}=q();return {onError:a,callOnError:e}}function le(){let{on:a,call:e}=q();return {onSuccess:a,callOnSuccess:e}}var ce=()=>{let a=new Set,e=new Map,n=(r,l)=>{e.get(r)?.forEach(o=>o(l));},t=(r,l)=>(e.has(r)||e.set(r,new Set),e.get(r).add(l),()=>e.get(r).delete(l));return {usePlugin:r=>{let l=new Set,o=(s,d)=>{let i=t(s,d);return l.add(i),i};return r.apply({on:o}),a.add(r),()=>{l.forEach(s=>s()),l.clear(),a.delete(r);}},emit:n}};function ue(){let{on:a,call:e}=q();return {onStart:a,callOnStart:e}}var de=(a={frameQuota:12})=>{let e=performance.now(),n=0,t=false,c=()=>!!navigator?.scheduling?.isInputPending?.({includeContinuous:true});return {getIsFirstFrame:()=>t,reset(){e=performance.now(),n=0,t=true;},shouldYield(){let r=performance.now();return n++,!!((n>=5||t)&&(n=0,r-e>a.frameQuota||c()))},async yieldToMain(){return new Promise(r=>{Pe(()=>{e=performance.now(),n=0,t&&(t=false),r();});})}}},Pe=a=>{let{port1:e,port2:n}=new MessageChannel;e.onmessage=a,n.postMessage(null);};function fe(a,e,n,t,c){let r=new Map,l=a.useGreedy,o=de();return async(d,i)=>{let f=Symbol("token"),p=d||"__NOTIFY_ALL__";r.set(p,f);let P=false;o.reset();let g=new Set,m=new Set,_=new Set;i.forEach(I=>{_.add(I),e.GetAllNextDependency(I).forEach(v=>_.add(v));});let N=new Map,C=new Map,M=new Set,L=e.GetPathToLevelMap(),A=0,z=0,H=I=>{e.GetAllNextDependency(I).forEach($=>{let G=L.get($)||0;G>z&&(z=G);});};d?(A=L.get(d)??0,H(d),g.add(d)):i.forEach(I=>H(I)),i.forEach(I=>{M.add(I);});let y=performance.now();t.emit("flow:start",{path:p}),t.callOnStart({path:p});let R=false,O=30,Q=I=>{let{target:v,trigger:$}=I,G=false,D=false,k=n.GetNodeByPath(v),W=[],E=(h,T)=>{if(g.has(h)||m.has(h)||M.has(h))return;let K=0,x=L.get(h)??0;if(N.has(h))K=N.get(h)-1;else {if(x>A&&N.size>O){C.has(x)||C.set(x,new Set),C.get(x).add(h),t.emit("node:intercept",{path:h,type:7});return}let F=e.GetPrevDependency(h),S=0;for(let b of F){if(g.has(b))continue;(L.get(b)??0)>A&&S++;}K=S;}if(K<=0){let F=M.has(h),S=m.has(h);if(F||S){t.emit("node:intercept",{path:h,type:S?3:3.1});return}N.delete(h),M.add(h),t.emit("node:release",{path:h,type:T,detail:{path:v}});}else N.set(h,K);},B=(h=[])=>{if(r.get(p)!==f)return;if(h.length){let x={},F=k.proxy;for(let S of h){let b=(S.args||[]).reduce((U,Y)=>(U[Y]=F[Y],U),{});try{let U=S.fn(b);U&&typeof U=="object"&&Object.assign(x,U);}catch(U){}}for(let S in x)if(S in k.state)k.state[S]=x[S];else throw {error:`wrong effect in ${k.path}`};G=true;}G&&c.flushPathSet.add(v),t.emit("node:success",{path:v}),g.add(v);let T=e.GetNextDependency(v);(G||D)&&e.GetAllNextDependency(v).forEach(F=>_.add(F));for(let x of T){if(g.has(x)){t.emit("node:intercept",{path:x,type:2});continue}if(m.has(x)||M.has(x)){t.emit("node:intercept",{path:x,type:m.has(x)?3:3.1});continue}if(G||D)E(x,1);else if(N.has(x))E(x,2);else {let S=L.get(x);C.has(S)||C.set(S,new Set);let b=C.get(S);b.has(x)||(b.add(x),t.emit("node:stagnate",{path:x,type:1}));}}m.delete(v),(async()=>{if(!P){let x=m.size,F=M.size;t.emit("flow:fire",{path:v,type:1,detail:{active:x,pending:F,blocked:N.size}}),j();}})();},V=h=>{t.emit("node:error",{path:v,error:h});let T=Symbol("abort");r.set(p,T),M.clear(),N.clear(),m.clear(),t.callOnError(h);},w=(h,T)=>{let K=false;h!==k[T]&&(k[T]=h,k.state[T]=h,G=true,t.emit("node:bucket:success",{path:v,key:T,value:h}),T==="value"&&(K=true)),k.nodeBucket[T].isForceNotify()&&(D=true),(K||D)&&H(v);};t.emit("node:start",{path:v});try{let h=[];for(let T in k.nodeBucket){let K=k.nodeBucket[T];h.push(...K.getSideEffect());let x=K.evaluate({affectKey:T,triggerPath:$,GetRenderSchemaByPath:F=>n.GetNodeByPath(F).proxy,GetValueByPath:F=>n.GetNodeByPath(F).state,GetToken:()=>f});if(x instanceof Promise){let F=x.then(S=>{r.get(p)===f&&w(S,T);});W.push(F);}else w(x,T);}if(W.length>0)return Promise.all(W).then(()=>{B(h);}).catch(V);B(h);return}catch(h){V(h);}},j=async()=>{if(r.get(p)!==f){P=false;return}P=true;let I=o.getIsFirstFrame(),v=0,$=()=>l&&I?30:1/0,G=0,D=$();try{for(;r.get(p)===f;){let k=G>=D,W=o.shouldYield();if(k||W){if(G>0&&(v++,(I||v%2===0)&&c.requestUpdate()),await o.yieldToMain(),r.get(p)!==f)break;G=0,I=o.getIsFirstFrame();}if(M.size>0&&m.size<5){for(let E of M){if(m.size>=5||G>=D)break;let B=L.get(E)??0,V=e.GetPrevDependency(E),w=V.length>1;if((!l||w)&&B>A){M.delete(E);let T=V.filter(K=>_.has(K)&&!g.has(K)).length;N.set(E,T||0),t.emit("node:intercept",{path:E,type:T>0?4:5,detail:{targetLevel:B,currentLevel:A,pendingParentsCount:T}});continue}if(M.delete(E),m.add(E),t.emit("node:processing",{path:E}),Q({target:E,trigger:d}),G++,G>=D||o.shouldYield())break}if(M.size>0)continue}if(G<D&&l&&N.size>0&&m.size<5){let E=!1,B=0;for(let[V,w]of N)if(w<=0){let h=L.get(V)??0,T=e.GetPrevDependency(V);if(h>A&&T.length>1)continue;if(N.delete(V),M.add(V),B++,E=!0,t.emit("node:release",{path:V,type:4}),B>=D)break}if(B>0)continue;if(E){if(o.shouldYield()&&(await o.yieldToMain(),r.get(p)!==f))break;continue}}if(m.size===0&&M.size===0){let E=new Set;for(let w of C.keys())E.add(w);for(let[w]of N){let h=L.get(w)??0;h>A&&E.add(h);}let B=Array.from(E).sort((w,h)=>w-h),V=B[0];if(B.length>0&&V<=z){let w=B[0];if(w<=z){A=w;let h=C.get(w);h&&(h.forEach(T=>M.add(T)),C.delete(w));for(let[T]of N)(L.get(T)??0)===w&&(N.delete(T),M.add(T),t.emit("node:release",{path:T,type:3,detail:{level:w}}));continue}}else {C.forEach((w,h)=>{w.forEach(T=>{g.add(T),t.emit("node:intercept",{path:T,type:6});});}),C.clear();for(let[w]of N)g.add(w),t.emit("node:intercept",{path:w,type:6});N.clear();break}}M.size>0&&m.size>=5&&t.emit("flow:wait",{type:2});break}}finally{if(P=false,m.size+N.size+M.size===0){if(r.get(p)===f&&!R){R=true,t.emit("flow:end",{type:1}),c.requestUpdate();let W=performance.now();t.emit("flow:success",{duration:(W-y).toFixed(2)+"ms"}),Promise.resolve().then(()=>{t.callOnSuccess();});}}else t.emit("flow:wait",{type:1,detail:{nums:m.size}});}};j();}}function ee(a){let{path:e,uid:n,type:t,meta:c,dirtySignal:r,triggerUI:l,state:o}=a,s=null,i={path:e,uid:n,type:t,meta:c,dirtySignal:r,createView:(u={})=>{let f=new Proxy(u,{get(p,P){let g=P;return g in a.state?a.state[g]:g in a?a[g]:c&&g in c?c[g]:Reflect.get(p,P)},set(p,P,g){let m=P;return m in a.state?(a.state[m]=g,l(),true):Reflect.set(p,P,g)},ownKeys(p){let P=new Set([...Reflect.ownKeys(p),...Object.keys(o||{}),...Object.keys(c||{})]);return Array.from(P)},getOwnPropertyDescriptor(p,P){return o&&P in o||c&&P in c?{enumerable:true,configurable:true}:Reflect.getOwnPropertyDescriptor(p,P)}});return s=f,f}};return "children"in a?{...i,children:a.children}:{...i,state:a.state,nodeBucket:a.nodeBucket,notifyKeys:a.notifyKeys,dependOn:a.dependOn,get proxy(){return s}}}function ye(a,e,n,t,c,r){let l=0,o=new Map,s=new Map,d=new Map,i=false,u=new Set,g=async()=>{let y=Array.from(u);u.clear();for(let R of y){let O=M(R);r.signalTrigger(O.dirtySignal);}},m=()=>{i||(i=true,requestAnimationFrame(()=>{try{for(;u.size>0;)g();}finally{i=false;}}));},_=fe({useGreedy:e.useGreedy},n,{GetNodeByPath:M},c,{requestUpdate:m,flushPathSet:u}),N=y=>{if(o.has(y.path))throw new Error(`[MeshFlow] Duplicate Path: ${String(y.path)}`);let R=++l,O={path:y.path,getNode:I=>M(I)},Q=I=>{let v=I({...O}),$=M(y.path);if(t.createHistoryAction&&t.pushIntoHistory){let G=t.createHistoryAction([{path:y.path,value:$.state.value},{path:y.path,value:v}],D=>{let k=M(D.path);k.state.value=D.value,A(D.path);});t.pushIntoHistory(G);}$.state.value=v,A(y.path);},j=ee({uid:R,path:y.path,state:y.state,meta:y.meta,nodeBucket:y.nodeBucket,dirtySignal:y.dirtySignal,notifyKeys:y.notifyKeys,dependOn:Q,triggerUI:()=>r.signalTrigger(y.dirtySignal)});return o.set(j.path,R),s.set(R,j),j},C=y=>{if(o.has(y.path))throw new Error(`[MeshFlow] Duplicate Path: ${String(y.path)}`);let R=++l,O=ee({uid:R,path:y.path,state:{},meta:y,nodeBucket:{},children:y.children});return o.set(O.path,R),d.set(R,O),O};function M(y){let R=o.get(y),O=s.get(R);if(!O)throw Error("wrong ID");return O}function L(y){let R=o.get(y);return d.get(R)}let A=y=>{if(!M(y))throw Error("Node undefined");u.add(y),m();let O=n.GetNextDependency(y);z(O,y);};function z(y,R){_(R,y);}return {registerNode:N,registerGroupNode:C,GetNodeByPath:M,GetGroupByPath:L,notify:A,notifyAll:async()=>{Promise.resolve().then(async()=>{let y=n.GetDependencyOrder();if(!y||y.length===0)return;let R=y[0];try{_(null,R);}catch(O){throw c.callOnError(O),O}finally{m();}});},UITrigger:r,UidToNodeMap:s}}function pe(a,e){let n=false,t=false,c=new Map,r=new Map,l=new Map,o=new Map,s=[],d=new Map,{GetNextDependency:u,GetPrevDependency:f,GetAllPrevDependency:p,GetAllNextDependency:P,rebuildDirectDependencyMaps:g}=ae(()=>c,()=>r,()=>o,()=>l),m={},_={};if(e.modules.useHistory){let{Undo:S,Redo:b,PushIntoHistory:U,CreateHistoryAction:Y,initCanUndo:he,initCanRedo:ge}=e.modules.useHistory();m.pushIntoHistory=U,m.createHistoryAction=Y,_={Undo:S,Redo:b,initCanUndo:he,initCanRedo:ge};}let{onError:N,callOnError:C}=ie(),{onSuccess:M,callOnSuccess:L}=le(),{onStart:A,callOnStart:z}=ue(),{emit:H,usePlugin:y}=ce(),{SetTrace:R,useTrace:O}=se(),Q=O();y(Q);let j=ye(a,{useGreedy:e.config.useGreedy},{GetDependencyOrder:()=>s,GetAllNextDependency:P,GetNextDependency:u,GetPrevDependency:f,GetAllPrevDependency:p,GetPathToLevelMap:()=>d},m,{callOnError:C,callOnSuccess:L,callOnStart:z,emit:H},e.UITrigger),{GetGroupByPath:I,GetNodeByPath:v,notifyAll:$}=j,G={};if(e.modules.useInternalForm){let{uiSchema:S,GetFormData:b}=e.modules.useInternalForm(j,a);G={uiSchema:S,GetFormData:b};}let D={};if(e.modules.useSchemaValidators){let{SetValidators:S}=e.modules.useSchemaValidators(v);D={SetValidators:S};}let{SetRule:k,SetRules:W}=ne(v,c,r),{SetStrategy:E}=re(v),B=oe(c),V=()=>{let S=B();s=S.steps,d=S.levelMap;},w=()=>{t||(t=true,Promise.resolve().then(()=>{if(V(),n){let{directNextMap:S,directPrevMap:b}=g(s.flat());l=S,o=b;}}).finally(()=>{t=false,n=false;}));};return {SetRule:(S,b,U,Y)=>{k(S,b,U,Y),n=true,w();},SetRules:(S,b,U,Y)=>{W(S,b,U,Y),n=true,w();},SetStrategy:E,SetTrace:R,usePlugin:y,SetValue:(S,b)=>{v(S).dependOn(()=>b);},GetValue:(S,b="value")=>v(S)[b],GetGroupByPath:I,notifyAll:async()=>{V(),await $();},GetAllDependency:()=>c,GetDependencyOrder:()=>s,historyExports:_,formExports:G,validatorExports:D,onError:N,onSuccess:M,onStart:A}}var J=new Map,me=(a,e,n)=>{try{if(typeof n.UITrigger.signalCreator!="function"||typeof n.UITrigger.signalTrigger!="function")throw Error("ui trigger undefined");if(J.has(a))throw Error("engineID repeated");let t=pe(e,{config:n.config||{useGreedy:!1},UITrigger:n.UITrigger,modules:n.modules||{},plugins:{}}),{SetRule:c,SetRules:r,SetStrategy:l,SetValue:o,GetValue:s,usePlugin:d,GetGroupByPath:i,notifyAll:u,SetTrace:f,GetAllDependency:p,GetDependencyOrder:P,historyExports:g,formExports:m,validatorExports:_,onError:N,onSuccess:C,onStart:M}=t,A={...{config:{SetRule:c,SetRules:r,SetStrategy:l,notifyAll:u,SetTrace:f,usePlugin:d},data:{SetValue:o,GetValue:s,GetGroupByPath:i},dependency:{GetAllDependency:p,GetDependencyOrder:P},hooks:{onError:N,onSuccess:C,onStart:M}}},z=n.modules;return z&&Object.keys(z).forEach(H=>{let y=H;if(y.startsWith("use")){let R=y.slice(3);y=R.charAt(0).toLowerCase()+R.slice(1);}H==="useHistory"&&g&&Object.keys(g).length>0&&(A[y]=g),H==="useInternalForm"&&Object.keys(m).length>0&&(A[y]=m),H==="useSchemaValidators"&&Object.keys(_).length>0&&(A[y]=_);}),J.set(a,A),A}catch(t){throw Error(t)}},Ze=()=>(a,e,n)=>Se(a,e,n),et=a=>{let e=J.get(a);if(e)return e;throw Error("[MeshFlow] Engine ID not found.")},tt=a=>{J.delete(a);},Se=me;exports.deleteEngine=tt;exports.useEngine=et;exports.useEngineManager=me;exports.useMeshFlow=Se;exports.useMeshFlowDefiner=Ze;
package/index.mjs CHANGED
@@ -1 +1 @@
1
- var ne=class{computedRules=[];store={OR:(e,n)=>{let t,l,r=this.computedRules;for(let o=0;o<r.length;o++){let a=r[o],s=a.logic(e);if(s instanceof Promise)return (async()=>{let c=await s;if(a.entityId==="__base__"?l=c:c&&(t=c),typeof t>"u")for(let u=o+1;u<r.length;u++){let h=r[u],S=h.logic(e),p=S instanceof Promise?await S:S;if(h.entityId==="__base__"){l=p;continue}if(p){t=h.value;break}}return typeof t>"u"&&(t=l),{res:t,version:n}})();let i=s;if(a.entityId==="__base__"){l=i;continue}if(i){t=a.value;break}}return typeof t>"u"&&(t=l),{res:t,version:n}},PRIORITY:(e,n)=>{let t,l=this.computedRules;for(let r=0;r<l.length;r++){let a=l[r].logic(e);if(a instanceof Promise)return (async()=>{let s=await a;if(s!==void 0)return {res:s,version:n};for(let i=r+1;i<l.length;i++){let c=l[i].logic(e),u=c instanceof Promise?await c:c;if(u!==void 0)return {res:u,version:n}}return {res:void 0,version:n}})();if(a!==void 0)return {res:a,version:n}}return {res:t,version:n}}};CurrentStrategy=()=>{};CurrentStrategyType="PRIORITY";getRules=()=>{};constructor(e){this.getRules=e,this.CurrentStrategy=this.store.PRIORITY,this.updateComputedRules();}updateComputedRules(){let e=this.getRules();this.CurrentStrategyType==="PRIORITY"?this.computedRules=Array.from(e.values()).map(n=>Array.from(n)).flat().sort((n,t)=>t.priority-n.priority):this.computedRules=Array.from(e.values()).map(n=>Array.from(n)).flat();}setStrategy(e){this.CurrentStrategy=this.store[e],this.updateComputedRules();}evaluate(e,n){return this.CurrentStrategy(e,n)}},J=class{path;strategy;contract;rules=new Map;isValue=false;id=0;cache=void 0;pendingPromise=null;version=0;deps=new Map;_forceNotify=false;promiseToken=null;effectArray=[];constructor(e,n,t){let l=()=>this.rules;this.strategy=new ne(l),this.path=t,this.isValue=n==="value",this.contract=this.inferType(e),this.cache=e,this.setRule({priority:0,entityId:"__base__",logic:()=>e});}forceNotify(){this._forceNotify=true;}isForceNotify(){return this._forceNotify}setStrategy(e){this.strategy.setStrategy(e);}setDefaultRule(e){let n=new Set;n.add(e),this.rules.set(e.id,n);}setRules(e,n){n&&this.updateDeps(n);let t=++this.id,l={...e,entityId:t};for(let r of e.triggerPaths)this.rules.has(r)||this.rules.set(r,new Set),this.rules.get(r).add(l);return this.strategy.updateComputedRules(),()=>{for(let r of e.triggerPaths){let o=this.rules.get(r);o&&(o.delete(l),o.size===0&&(this.rules.delete(r),this.deps.delete(r)));}this.strategy.updateComputedRules();}}updateDeps(e){for(let[n,t]of e)this.deps.set(n,t);}setRule(e,n){if(n&&this.updateDeps(n),typeof e.entityId=="string"){this.setDefaultRule(e);return}let t=++this.id,l={...e,entityId:t};if(e)for(let r of e.triggerPaths)this.rules.has(r)||this.rules.set(r,new Set),this.rules.get(r).add(l);return this.strategy.updateComputedRules(),()=>{for(let r of e.triggerPaths){let o=this.rules.get(r);o&&(o.delete(l),o.size===0&&(this.rules.delete(r),this.deps.delete(r)));}this.strategy.updateComputedRules();}}setSideEffect(e){this.effectArray.push(e);}getSideEffect(){return [...this.effectArray]}evaluate(e){let n=null;if(e.GetToken&&(n=e.GetToken()),this.pendingPromise&&this.promiseToken!==n&&(this.pendingPromise=null,this.promiseToken=null),this.pendingPromise)return this.pendingPromise;let t=false;if(typeof e.triggerPath=="string"){t=true;let o=this.deps.get(e.triggerPath),a=e.GetValueByPath(e.triggerPath);if(typeof o=="object"||typeof a=="object")t=false;else {let s=Array.from(this.deps.keys());for(let i of s){let c=this.deps.get(i),u=e.GetValueByPath(i);if(c!==u){t=false;break}}}}if(t)return this.cache;this.promiseToken=n;let l=++this.version,r=this.strategy.evaluate(e,l);if(!(r instanceof Promise)){let{res:o,version:a}=r;return this.finalizeSync(o,a,e,n)}return this.pendingPromise=(async()=>{try{let{res:o,version:a}=await r;return this.finalizeSync(o,a,e,n)}catch(o){throw {path:this.path,error:o}}finally{this.promiseToken===n&&(this.pendingPromise=null,this.promiseToken=null);}})(),this.pendingPromise}finalizeSync(e,n,t,l){return l!==this.promiseToken||n<this.version?this.cache:(this.cache=e,this.deps.forEach((r,o)=>{this.deps.set(o,t.GetValueByPath(o));}),e)}inferType(e){return Array.isArray(e)?"array":typeof e}},ee=class{validators=[];defaultValidators=[];path="";constructor(e){this.path=e,this.SetDefaultValidators();}setValidators(e){this.validators.push(e);}SetDefaultValidators(){let e={logic:t=>t||typeof t=="number"?true:`${this.path} undefined`,condition:t=>!!t.required},n={logic:function(t){return t.length>this.options.maxLength?`Too long:${this.options.maxLength}`:true},condition:function(t){return typeof t.maxLength!="number"?false:(n.options={maxLength:t.maxLength},t.type==="input"&&t.hidden===false)},options:{}};this.defaultValidators.push(e),this.defaultValidators.push(n);}evaluate(e,n){let t=true,l=[...this.defaultValidators,...this.validators];for(let r of l){if(!r.condition(n))continue;let a=r.logic(e);if(typeof a!="boolean"){t=a;break}}return t}};var re=(d={frameQuota:12})=>{let e=performance.now(),n=0,t=false,l=()=>!!navigator?.scheduling?.isInputPending?.({includeContinuous:true});return {getIsFirstFrame:()=>t,reset(){e=performance.now(),n=0,t=true;},shouldYield(){let r=performance.now();return n++,!!((n>=5||t)&&(n=0,r-e>d.frameQuota||l()))},async yieldToMain(){return new Promise(r=>{Te(()=>{e=performance.now(),n=0,t&&(t=false),r();});})}}},Te=d=>{let{port1:e,port2:n}=new MessageChannel;e.onmessage=d,n.postMessage(null);};function ae(d,e,n,t,l){let r=new Map,o=d.useGreedy,a=re();return async(i,c)=>{let h=Symbol("token");r.set(i,h);let S=false;a.reset();let p=new Set,T=new Set,N=new Set(e.GetAllNextDependency(i));N.add(i);let M=new Map,D=new Map,F=new Set,V=e.GetPathToLevelMap(),_=V.get(i)??0,H=0,q=G=>{e.GetAllNextDependency(G).forEach(U=>{let R=V.get(U)||0;R>H&&(H=R);});};q(i),c.forEach(G=>{F.add(G);}),p.add(i);let z=performance.now();t.emit("flow:start",{path:i}),t.callOnStart({path:i});let W=false,$=30,g=G=>{let{target:y,trigger:U}=G,R=false,k=false,C=n.GetNodeByPath(y),E=[],P=(f,m)=>{if(p.has(f)||T.has(f)||F.has(f))return;let B=0,v=V.get(f)??0;if(M.has(f))B=M.get(f)-1;else {if(v>_&&M.size>$){D.has(v)||D.set(v,new Set),D.get(v).add(f),t.emit("node:intercept",{path:f,type:7});return}let O=e.GetPrevDependency(f),L=0;for(let K of O){if(p.has(K))continue;(V.get(K)??0)>_&&L++;}B=L;}if(B<=0){let O=F.has(f),L=T.has(f);if(O||L){t.emit("node:intercept",{path:f,type:L?3:3.1});return}M.delete(f),F.add(f),t.emit("node:release",{path:f,type:m,detail:{path:y}});}else M.set(f,B);},b=(f=[])=>{if(r.get(i)!==h)return;if(f.length){let v={};for(let O of f){let L=(O.args||[]).reduce((K,I)=>(K[I]=C[I],K),{});try{let K=O.fn(L);K&&typeof K=="object"&&Object.assign(v,K);}catch(K){}}for(let O in v)C[O]=v[O];R=true;}R&&l.flushPathSet.add(y),t.emit("node:success",{path:y}),p.add(y);let m=e.GetNextDependency(y);(R||k)&&e.GetAllNextDependency(y).forEach(O=>N.add(O));for(let v of m){if(p.has(v)){t.emit("node:intercept",{path:v,type:2});continue}if(T.has(v)||F.has(v)){t.emit("node:intercept",{path:v,type:T.has(v)?3:3.1});continue}if(R||k)P(v,1);else if(M.has(v))P(v,2);else {let L=V.get(v);D.has(L)||D.set(L,new Set);let K=D.get(L);K.has(v)||(K.add(v),t.emit("node:stagnate",{path:v,type:1}));}}T.delete(y),(async()=>{if(!S){let v=T.size,O=F.size;t.emit("flow:fire",{path:y,type:1,detail:{active:v,pending:O,blocked:M.size}}),w();}})();},A=f=>{t.emit("node:error",{path:y,error:f});let m=Symbol("abort");r.set(i,m),F.clear(),M.clear(),T.clear(),t.callOnError(f);},x=(f,m)=>{let B=false;f!==C[m]&&(C[m]=f,R=true,t.emit("node:bucket:success",{path:y,key:m,value:f}),m==="value"&&(B=true)),C.nodeBucket[m].isForceNotify()&&(k=true),(B||k)&&q(y);};t.emit("node:start",{path:y});try{let f=[];for(let m in C.nodeBucket){let B=C.nodeBucket[m];f.push(...B.getSideEffect());let v=B.evaluate({affectKey:m,triggerPath:U,GetRenderSchemaByPath:n.GetNodeByPath,GetValueByPath:O=>n.GetNodeByPath(O).value,GetToken:()=>h});if(v instanceof Promise){let O=v.then(L=>{r.get(i)===h&&x(L,m);});E.push(O);}else x(v,m);}if(E.length>0)return Promise.all(E).then(()=>{b(f);}).catch(A);b(f);return}catch(f){A(f);}},w=async()=>{if(r.get(i)!==h){S=false;return}S=true;let G=a.getIsFirstFrame(),y=0,U=()=>o&&G?30:1/0,R=0,k=U();try{for(;r.get(i)===h;){let C=R>=k,E=a.shouldYield();if(C||E){if(R>0&&(y++,(G||y%2===0)&&l.requestUpdate()),await a.yieldToMain(),r.get(i)!==h)break;R=0,G=a.getIsFirstFrame();}if(F.size>0&&T.size<5){for(let P of F){if(T.size>=5||R>=k)break;let b=V.get(P)??0,A=e.GetPrevDependency(P),x=A.length>1;if((!o||x)&&b>_){F.delete(P);let m=A.filter(B=>N.has(B)&&!p.has(B)).length;M.set(P,m||0),t.emit("node:intercept",{path:P,type:m>0?4:5,detail:{targetLevel:b,currentLevel:_,pendingParentsCount:m}});continue}if(F.delete(P),T.add(P),t.emit("node:processing",{path:P}),g({target:P,trigger:i}),R++,R>=k||a.shouldYield())break}if(F.size>0)continue}if(R<k&&o&&M.size>0&&T.size<5){let P=!1,b=0;for(let[A,x]of M)if(x<=0){let f=V.get(A)??0,m=e.GetPrevDependency(A);if(f>_&&m.length>1)continue;if(M.delete(A),F.add(A),b++,P=!0,t.emit("node:release",{path:A,type:4}),b>=k)break}if(b>0)continue;if(P){if(a.shouldYield()&&(await a.yieldToMain(),r.get(i)!==h))break;continue}}if(T.size===0&&F.size===0){let P=new Set;for(let x of D.keys())P.add(x);for(let[x]of M){let f=V.get(x)??0;f>_&&P.add(f);}let b=Array.from(P).sort((x,f)=>x-f),A=b[0];if(b.length>0&&A<=H){let x=b[0];if(x<=H){_=x;let f=D.get(x);f&&(f.forEach(m=>F.add(m)),D.delete(x));for(let[m]of M)(V.get(m)??0)===x&&(M.delete(m),F.add(m),t.emit("node:release",{path:m,type:3,detail:{level:x}}));continue}}else {D.forEach((x,f)=>{x.forEach(m=>{p.add(m),t.emit("node:intercept",{path:m,type:6});});}),D.clear();for(let[x]of M)p.add(x),t.emit("node:intercept",{path:x,type:6});M.clear();break}}F.size>0&&T.size>=5&&t.emit("flow:wait",{type:2});break}}finally{if(S=false,T.size+M.size+F.size===0){if(r.get(i)===h&&!W){W=true,t.emit("flow:end",{type:1}),l.requestUpdate();let E=performance.now();t.emit("flow:success",{duration:(E-z).toFixed(2)+"ms"}),Promise.resolve().then(()=>{t.callOnSuccess();});}}else t.emit("flow:wait",{type:1,detail:{nums:T.size}});}};w();}}function se(d,e,n,t,l,r){let o=xe(d),a=0,s=new Map,i=new Map,c=new Map,u=false,h=new Set,S=false,p=true,T=null,N=g=>{let w=s.get(g);return i.get(w)},M=g=>c.get(g),D=async()=>{let g=Array.from(h);h.clear();for(let w of g){let G=N(w);r.signalTrigger(G.dirtySignal);}},F=()=>{u||(u=true,requestAnimationFrame(()=>{try{for(;h.size>0;)D();}finally{u=false;}}));},V=()=>{let g=(w,G,y)=>{if(typeof w!="object"||w===null||Array.isArray(w)){if(y.length>0){let R=y[y.length-1];G[R]=N(y.join(".")).value;}return}let U=Object.getOwnPropertyNames(w);for(let R of U)y.push(R),g(w[R],w,y),y.pop();};return g(o,null,[]),o},Y=ae({useGreedy:e.useGreedy},n,{GetNodeByPath:N},l,{requestUpdate:F,flushPathSet:h}),_=async()=>(S&&T||(S=true,T=(async()=>{let g=n.GetDependencyOrder(),w=performance.now(),G=performance.now();try{for(let U=0;U<g.length;U++){let R=g[U];await Promise.all(R.map(async k=>{let C=N(k),E=!1;for(let P in C.nodeBucket){let b=await C.nodeBucket[P].evaluate({affectKey:P,triggerPath:void 0,GetRenderSchemaByPath:N,GetValueByPath:A=>N(A).value,isSameToken:()=>!0});if(P==="options"){let A=!1,x=C.value;for(let f of b)if(f.value==x){A=!0;break}A||(C.value=void 0,E=!0);}b!==C[P]&&(C[P]=b,E=!0);}E&&h.add(k);})),performance.now()-G>12&&(await new Promise(k=>requestAnimationFrame(k)),G=performance.now());}h.size>0&&F(),p=!1;let y=performance.now();l.emit("flow:success",{duration:(y-w).toFixed(2)+"ms"}),l.callOnSuccess();}catch(y){throw l.emit("node:error",{path:y.path,error:y.error}),l.callOnError(y),y}finally{S=false,T=null,p=false;}})()),T),H=g=>{if(p)return;if(!N(g))throw Error("Node undefined");performance.now();h.add(g),F();let y=n.GetNextDependency(g);q(y,g);};function q(g,w){Y(w,g);}let z=(g,w="")=>{let G="name"in g?g.name:void 0,y=G?w===""?G:`${w}.${G}`:w,U=r.signalCreateor(),R=a++,k={getRenderSchema:P=>N(P)},C=(P,b)=>{let A=P(b),x=N(b.path),f=t.createHistoryAction([{path:b.path,value:x.value},{path:b.path,value:A}],m=>{let B=N(m.path);B.value=m.value,H(m.path);});x.value=A,t.pushIntoHistory(f),H(b.path);},E={...g,disabled:!!g.disabled,hidden:"hidden"in g?g.hidden:false,readonly:"readonly"in g?g.readonly:false,required:"required"in g?g.required:false,path:y,dirtySignal:U,uid:R,nodeBucket:{},validators:new ee(y),theme:"secondary",dependOn:P=>C(P,{...k,path:y})};return g.type==="group"&&(delete E.nodeBucket,delete E.validators,E.children=g.children.map(P=>z(P,y)),c.set(E.path,E)),s.set(E.path,E.uid),i.set(E.uid,E),E};return {schema:z(d),GetFormData:()=>V(),GetRenderSchemaByPath:N,GetGroupByPath:M,notifyAll:_,convertToRenderSchema:z}}function xe(d,e={}){let n=r=>{if(r.type=="group")return {key:r.name||"",isGroup:true,val:r.children.reduce((o,a)=>[...o,n(a)],[])};if(r.type=="input"||r.type=="number"||r.type=="select"||r.type=="checkbox")return {key:r.name,isGroup:false,val:r.value};throw Error(`undefined type:${r.type}`)},t=(r,o)=>{if(o.isGroup){let a={};o.key===""?a=r:r[o.key]=a,o.val.forEach(s=>{t(a,s);});}else r[o.key]=o.val;},l=n(d);return t(e,l),e}var oe=(d,e,n)=>{let l=r=>{let o=n.triggerPaths.map(i=>r.GetValueByPath(i)),a=Object.create(null);return Object.defineProperty(a,"triggerTargets",{get:()=>o}),Object.defineProperty(a,"affectedTatget",{get:()=>r.GetRenderSchemaByPath(d)[e]}),n.logic({slot:a})};return {value:n.value,targetPath:d,triggerPaths:n.triggerPaths,priority:n.priority??10,logic:l}},ie=(d,e,n)=>{if(!d)throw Error("");let t=d,l=(a,s)=>{e.has(a)||e.set(a,new Set),e.get(a).add(s),n.has(s)||n.set(s,new Set),n.get(s).add(a);};return {SetRule:(a,s,i,c={logic:u=>{}})=>{let u=t(s),h=oe(s,i,{...c,triggerPaths:[a]}),S=[a].map(p=>[p,t(p).value]);if(l(a,s),u.nodeBucket[i])u.nodeBucket[i].setRule(h,S),c.effect&&u.nodeBucket[i].setSideEffect({fn:c.effect,args:c.effectArgs?c.effectArgs:[i]});else {let p=new J(u[i],i,s);p.setRule(h,S),c.effect&&p.setSideEffect({fn:c.effect,args:c.effectArgs?c.effectArgs:[i]}),u.nodeBucket[i]=p;}c.forceNotify&&u.nodeBucket[i].forceNotify();},SetRules:(a,s,i,c={logic:u=>{}})=>{let u=t(s);for(let p of a)l(p,s);let h=oe(s,i,{...c,triggerPaths:a}),S=a.map(p=>[p,t(p).value]);if(u.nodeBucket[i])u.nodeBucket[i].setRules(h,S),c.effect&&u.nodeBucket[i].setSideEffect({fn:c.effect,args:c.effectArgs?c.effectArgs:[i]});else {let p=new J(u[i],i,s);p.setRules(h,S),c.effect&&p.setSideEffect({fn:c.effect,args:c.effectArgs?c.effectArgs:[i]}),u.nodeBucket[i]=p;}c.forceNotify&&u.nodeBucket[i].forceNotify();}}};var le=d=>{let e=d||void 0;if(!e)throw Error("");return {SetStrategy:(t,l,r)=>{e(t).nodeBucket[l].setStrategy(r);}}};var ce=d=>{let e=d||void 0;return {SetValidators:(t,l)=>{let r=e(t),o=(s,i,c)=>s(i,c),a=(s,i,c)=>s(i,c);if(!r.validators)throw Error("validator init error");r.validators.setValidators({logic:s=>o(l.logic,s,e),condition:typeof l.condition=="function"?s=>a(l.condition,s,e):()=>true});}}};function de(){let d=new Map,e=new Map,n=new Set,t=(o,a)=>{d.set(o,a);let s=e.get(o);s&&s(a);};return {SetTrace:(o,a)=>{e.set(o,a);let s=d.get(o)||"idle";return a(s),()=>{e.delete(o);}},useTrace:()=>({apply:a=>{a.on("flow:start",()=>{n.forEach(s=>t(s,"idle")),n.clear(),d.clear();}),a.on("node:release",({path:s,type:i})=>{(i==1||i==2)&&(n.add(s),t(s,"pending"));}),a.on("node:pending",({path:s})=>{n.add(s),(!d.has(s)||d.get(s)==="idle")&&t(s,"pending");}),a.on("node:start",({path:s})=>{n.add(s),t(s,"calculating");}),a.on("node:success",({path:s})=>{t(s,"calculated");}),a.on("node:intercept",({path:s,type:i})=>{i==3&&t(s,"calculating"),i==6&&t(s,"idle");}),a.on("node:stagnate",({path:s})=>{t(s,"pending");}),a.on("node:error",({path:s})=>t(s,"error"));}})}}function ue(d,e,n,t){let l=c=>{let u=d(),h=e(),S=new Set;return u.get(c)?.forEach(p=>S.add(p)),S.size===0?[]:Array.from(S).filter(p=>{let T=h.get(p)||new Set;return !Array.from(T).some(D=>S.has(D))})};return {GetNextDependency:c=>{let u=t();return Array.from(u.get(c)||[])},GetPrevDependency:c=>{let u=n();return Array.from(u.get(c)||[])},GetAllPrevDependency:c=>{let u=e();return Array.from(u.get(c)||[])},GetAllNextDependency:c=>{let u=d();return Array.from(u.get(c)||[])},rebuildDirectDependencyMaps:c=>{let u=new Map,h=new Map;for(let S of c){let p=l(S);u.set(S,new Set(p));for(let T of p)h.has(T)||h.set(T,new Set),h.get(T).add(S);}return {directNextMap:u,directPrevMap:h}}}}function fe(d){let e=t=>{let l=[],r=[],o=new Map,a=t.size,s=0,i=0;for(let[c,u]of t)u===0&&r.push(c);if(r.length===0&&a>0)throw Error("Circular dependency detected");for(;r.length>0;){l.push([...r]);let c=[];for(let u of r){s++,o.set(u,i);let h=d.get(u);if(h)for(let S of h){let p=t.get(S)-1;t.set(S,p),p===0&&c.push(S);}}r=c,i++;}if(s<a)throw Error("Circular dependency detected");return {steps:l,levelMap:o}};return ()=>{let t=new Map;for(let l of d.keys()){let r=Array.from(d.get(l)||[]);t.has(l)||t.set(l,0);for(let o of r){let a=t.get(o)||0;t.set(o,++a);}}return e(t)}}var X=()=>{let d=[];return {on:e=>(d.push(e),()=>{let n=d.indexOf(e);n>-1&&d.splice(n,1);}),call:e=>d.forEach(n=>n(e))}};function pe(){let{on:d,call:e}=X();return {onError:d,callOnError:e}}function ye(){let{on:d,call:e}=X();return {onSuccess:d,callOnSuccess:e}}var he=()=>{let d=new Set,e=new Map,n=(r,o)=>{e.get(r)?.forEach(a=>a(o));},t=(r,o)=>(e.has(r)||e.set(r,new Set),e.get(r).add(o),()=>e.get(r).delete(o));return {usePlugin:r=>{let o=new Set,a=(s,i)=>{let c=t(s,i);return o.add(c),c};return r.apply({on:a}),d.add(r),()=>{o.forEach(s=>s()),o.clear(),d.delete(r);}},emit:n}};function me(){let{on:d,call:e}=X();return {onStart:d,callOnStart:e}}function ge(d,e){let n=false,t=false,l=new Map,r=new Map,o=new Map,a=new Map,s=[],i=new Map,{GetNextDependency:u,GetPrevDependency:h,GetAllPrevDependency:S,GetAllNextDependency:p,rebuildDirectDependencyMaps:T}=ue(()=>l,()=>r,()=>a,()=>o),N={},M={};if(e.modules.useHistory){let{Undo:I,Redo:j,PushIntoHistory:Q,CreateHistoryAction:Z,initCanUndo:Pe,initCanRedo:Se}=e.modules.useHistory();N.pushIntoHistory=Q,N.createHistoryAction=Z,M={Undo:I,Redo:j,initCanUndo:Pe,initCanRedo:Se};}let{onError:D,callOnError:F}=pe(),{onSuccess:V,callOnSuccess:Y}=ye(),{onStart:_,callOnStart:H}=me(),{emit:q,usePlugin:z}=he(),{SetTrace:W,useTrace:$}=de(),g=$();z(g);let{schema:w,GetFormData:G,GetRenderSchemaByPath:y,GetGroupByPath:U,notifyAll:R,convertToRenderSchema:k}=se(d,{useGreedy:e.config.useGreedy},{GetDependencyOrder:()=>s,GetAllNextDependency:p,GetNextDependency:u,GetPrevDependency:h,GetAllPrevDependency:S,GetPathToLevelMap:()=>i},N,{callOnError:F,callOnSuccess:Y,callOnStart:H,emit:q},e.UITrigger),C=(I,j)=>{let Q=U(I),Z=k(j,I);return Q.children.push(Z),Q.dirtySignal.value++,Z},{SetRule:E,SetRules:P}=ie(y,l,r),{SetStrategy:b}=le(y),{SetValidators:A}=ce(y),x=fe(l),f=()=>{let I=x();s=I.steps,i=I.levelMap;},m=()=>{t||(t=true,Promise.resolve().then(()=>{if(f(),n){let{directNextMap:I,directPrevMap:j}=T(s.flat());o=I,a=j;}}).finally(()=>{t=false,n=false;}));};return {schema:w,SetRule:(...I)=>{E.apply(null,I),n=true,m();},SetRules:(...I)=>{P.apply(null,I),n=true,m();},SetStrategy:b,SetValidators:A,SetTrace:W,usePlugin:z,SetValue:(I,j)=>{y(I).dependOn(()=>j);},GetValue:(I,j="value")=>y(I)[j],GetFormData:G,GetGroupByPath:U,notifyAll:async()=>{f(),await R();},AddNewSchema:C,GetAllDependency:()=>l,GetDependencyOrder:()=>s,historyExports:M,onError:D,onSuccess:V,onStart:_}}var te=new Map,ve=(d,e,n)=>{try{if(typeof n.UITrigger.signalCreateor!="function"||typeof n.UITrigger.signalTrigger!="function")throw Error("ui trigger undefined");if(te.has(d))throw Error("engineID repeated");let t=ge(e,{config:n.config||{useGreedy:!1},UITrigger:n.UITrigger,modules:n.modules||{},plugins:{}}),{schema:l,GetFormData:r,SetRule:o,SetRules:a,SetStrategy:s,SetValidators:i,SetValue:c,GetValue:u,usePlugin:h,GetGroupByPath:S,notifyAll:p,SetTrace:T,GetAllDependency:N,GetDependencyOrder:M,AddNewSchema:D,historyExports:F,onError:V,onSuccess:Y,onStart:_}=t,q={...{config:{SetRule:o,SetRules:a,SetStrategy:s,SetValidators:i,notifyAll:p,SetTrace:T,usePlugin:h},data:{schema:l,GetFormData:r,AddNewSchema:D,SetValue:c,GetValue:u,GetGroupByPath:S},dependency:{GetAllDependency:N,GetDependencyOrder:M},hooks:{onError:V,onSuccess:Y,onStart:_}}},z=n.modules;return z&&Object.keys(z).forEach(W=>{let $=W;if($.startsWith("use")){let g=$.slice(3);$=g.charAt(0).toLowerCase()+g.slice(1);}W==="useHistory"&&F&&Object.keys(F).length>0&&(q[$]=F);}),te.set(d,q),q}catch(t){throw Error(t)}},dt=()=>(d,e,n)=>Fe(d,e,n),ut=d=>{let e=te.get(d);if(e)return e;throw Error("[MeshFlow] Engine ID not found.")},ft=d=>{te.delete(d);},Fe=ve;export{ft as deleteEngine,ut as useEngine,ve as useEngineManager,Fe as useMeshFlow,dt as useMeshFlowDefiner};
1
+ var Z=class{computedRules=[];store={OR:(e,n)=>{let t,c,r=this.computedRules;for(let l=0;l<r.length;l++){let o=r[l],s=o.logic(e);if(s instanceof Promise)return (async()=>{let i=await s;if(o.entityId==="__base__"?c=i:i&&(t=i),typeof t>"u")for(let u=l+1;u<r.length;u++){let f=r[u],p=f.logic(e),P=p instanceof Promise?await p:p;if(f.entityId==="__base__"){c=P;continue}if(P){t=f.value;break}}return typeof t>"u"&&(t=c),{res:t,version:n}})();let d=s;if(o.entityId==="__base__"){c=d;continue}if(d){t=o.value;break}}return typeof t>"u"&&(t=c),{res:t,version:n}},PRIORITY:(e,n)=>{let t,c=this.computedRules;for(let r=0;r<c.length;r++){let o=c[r].logic(e);if(o instanceof Promise)return (async()=>{let s=await o;if(s!==void 0)return {res:s,version:n};for(let d=r+1;d<c.length;d++){let i=c[d].logic(e),u=i instanceof Promise?await i:i;if(u!==void 0)return {res:u,version:n}}return {res:void 0,version:n}})();if(o!==void 0)return {res:o,version:n}}return {res:t,version:n}}};CurrentStrategy=()=>{};CurrentStrategyType="PRIORITY";getRules=()=>{};constructor(e){this.getRules=e,this.CurrentStrategy=this.store.PRIORITY,this.updateComputedRules();}updateComputedRules(){let e=this.getRules();this.CurrentStrategyType==="PRIORITY"?this.computedRules=Array.from(e.values()).map(n=>Array.from(n)).flat().sort((n,t)=>t.priority-n.priority):this.computedRules=Array.from(e.values()).map(n=>Array.from(n)).flat();}setStrategy(e){this.CurrentStrategy=this.store[e],this.updateComputedRules();}evaluate(e,n){return this.CurrentStrategy(e,n)}},X=class{path;strategy;contract;rules=new Map;isValue=false;id=0;cache=void 0;pendingPromise=null;version=0;deps=new Map;_forceNotify=false;promiseToken=null;effectArray=[];constructor(e,n,t){let c=()=>this.rules;this.strategy=new Z(c),this.path=t,this.isValue=n==="value",this.contract=this.inferType(e),this.cache=e,this.setRule({priority:0,entityId:"__base__",logic:()=>e});}forceNotify(){this._forceNotify=true;}isForceNotify(){return this._forceNotify}setStrategy(e){this.strategy.setStrategy(e);}setDefaultRule(e){let n=new Set;n.add(e),this.rules.set("defaultRules",n);}setRules(e,n){n&&this.updateDeps(n);let t=++this.id,c={...e,entityId:t};for(let r of e.triggerPaths)this.rules.has(r)||this.rules.set(r,new Set),this.rules.get(r).add(c);return this.strategy.updateComputedRules(),()=>{for(let r of e.triggerPaths){let l=this.rules.get(r);l&&(l.delete(c),l.size===0&&(this.rules.delete(r),this.deps.delete(r)));}this.strategy.updateComputedRules();}}updateDeps(e){for(let[n,t]of e)this.deps.set(n,t);}setRule(e,n){if(n&&this.updateDeps(n),typeof e.entityId=="string"){this.setDefaultRule(e);return}let t=++this.id,c={...e,entityId:t};if(e)for(let r of e.triggerPaths)this.rules.has(r)||this.rules.set(r,new Set),this.rules.get(r).add(c);return this.strategy.updateComputedRules(),()=>{for(let r of e.triggerPaths){let l=this.rules.get(r);l&&(l.delete(c),l.size===0&&(this.rules.delete(r),this.deps.delete(r)));}this.strategy.updateComputedRules();}}setSideEffect(e){this.effectArray.push(e);}getSideEffect(){return [...this.effectArray]}evaluate(e){let n=null;if(e.GetToken&&(n=e.GetToken()),this.pendingPromise&&this.promiseToken!==n&&(this.pendingPromise=null,this.promiseToken=null),this.pendingPromise)return this.pendingPromise;let t=false;if(typeof e.triggerPath=="string"){t=true;let l=this.deps.get(e.triggerPath),o=e.GetValueByPath(e.triggerPath);if(typeof l=="object"||typeof o=="object")t=false;else {let s=Array.from(this.deps.keys());for(let d of s){let i=this.deps.get(d),u=e.GetValueByPath(d);if(i!==u){t=false;break}}}}if(t)return this.cache;this.promiseToken=n;let c=++this.version,r=this.strategy.evaluate(e,c);if(!(r instanceof Promise)){let{res:l,version:o}=r;return this.finalizeSync(l,o,e,n)}return this.pendingPromise=(async()=>{try{let{res:l,version:o}=await r;return this.finalizeSync(l,o,e,n)}catch(l){throw {path:this.path,error:l}}finally{this.promiseToken===n&&(this.pendingPromise=null,this.promiseToken=null);}})(),this.pendingPromise}finalizeSync(e,n,t,c){return c!==this.promiseToken||n<this.version?this.cache:(this.cache=e,this.deps.forEach((r,l)=>{this.deps.set(l,t.GetValueByPath(l));}),e)}inferType(e){return Array.isArray(e)?"array":typeof e}};var te=(a,e,n)=>{let c=r=>{let l=n.triggerPaths.map(d=>r.GetValueByPath(d).value),o=Object.create(null);return Object.defineProperty(o,"triggerTargets",{get:()=>l||[]}),Object.defineProperty(o,"affectedTatget",{get:()=>r.GetRenderSchemaByPath(a)[e]}),n.logic({slot:o})};return {value:n.value,targetPath:a,triggerPaths:n.triggerPaths,priority:n.priority??10,logic:c}},ne=(a,e,n,t)=>{if(!a)throw Error("");let c=a,r=(s,d)=>{e.has(s)||e.set(s,new Set),e.get(s).add(d),n.has(d)||n.set(d,new Set),n.get(d).add(s);};return {SetRule:(s,d,i,u={logic:()=>{}})=>{let f=c(d),p=te(d,i,{...u,triggerPaths:[s]}),P=[s].map(g=>[g,c(g).state.value]);if(r(s,d),f.nodeBucket[i])f.nodeBucket[i].setRule(p,P),u.effect&&f.nodeBucket[i].setSideEffect({fn:u.effect,args:u.effectArgs?u.effectArgs:[i]});else {let g=f.meta[i],m=new X(g,i,d);m.setRule(p,P),u.effect&&m.setSideEffect({fn:u.effect,args:u.effectArgs?u.effectArgs:[i]}),f.nodeBucket[i]=m;}f.state[i]=f.meta[i],u.forceNotify&&f.nodeBucket[i].forceNotify();},SetRules:(s,d,i,u={logic:()=>{}})=>{let f=c(d);for(let g of s)r(g,d);let p=te(d,i,{...u,triggerPaths:s}),P=s.map(g=>[g,c(g).state.value]);if(f.nodeBucket[i])f.nodeBucket[i].setRules(p,P),u.effect&&f.nodeBucket[i].setSideEffect({fn:u.effect,args:u.effectArgs?u.effectArgs:[i]});else {let g=f.meta[i],m=new X(g,i,d);m.setRules(p,P),u.effect&&m.setSideEffect({fn:u.effect,args:u.effectArgs?u.effectArgs:[i]}),f.nodeBucket[i]=m;}f.state[i]=f.meta[i],u.forceNotify&&f.nodeBucket[i].forceNotify();}}};var re=a=>{let e=a||void 0;if(!e)throw Error("");return {SetStrategy:(t,c,r)=>{e(t).nodeBucket[c].setStrategy(r);}}};function se(){let a=new Map,e=new Map,n=new Set,t=(l,o)=>{a.set(l,o);let s=e.get(l);s&&s(o);};return {SetTrace:(l,o)=>{e.set(l,o);let s=a.get(l)||"idle";return o(s),{cancel:()=>{e.delete(l);}}},useTrace:()=>({apply:o=>{o.on("flow:start",()=>{n.forEach(s=>t(s,"idle")),n.clear(),a.clear();}),o.on("node:release",({path:s,type:d})=>{(d==1||d==2)&&(n.add(s),t(s,"pending"));}),o.on("node:pending",({path:s})=>{n.add(s),(!a.has(s)||a.get(s)==="idle")&&t(s,"pending");}),o.on("node:start",({path:s})=>{n.add(s),t(s,"calculating");}),o.on("node:success",({path:s})=>{t(s,"calculated");}),o.on("node:intercept",({path:s,type:d})=>{d==3&&t(s,"calculating"),d==6&&t(s,"idle");}),o.on("node:stagnate",({path:s})=>{t(s,"pending");}),o.on("node:error",({path:s})=>t(s,"error"));}})}}function ae(a,e,n,t){let c=i=>{let u=a(),f=e(),p=new Set;return u.get(i)?.forEach(P=>p.add(P)),p.size===0?[]:Array.from(p).filter(P=>{let g=f.get(P)||new Set;return !Array.from(g).some(N=>p.has(N))})};return {GetNextDependency:i=>{let u=t();return Array.from(u.get(i)||[])},GetPrevDependency:i=>{let u=n();return Array.from(u.get(i)||[])},GetAllPrevDependency:i=>{let u=e();return Array.from(u.get(i)||[])},GetAllNextDependency:i=>{let u=a();return Array.from(u.get(i)||[])},rebuildDirectDependencyMaps:i=>{let u=new Map,f=new Map;for(let p of i){let P=c(p);u.set(p,new Set(P));for(let g of P)f.has(g)||f.set(g,new Set),f.get(g).add(p);}return {directNextMap:u,directPrevMap:f}}}}function oe(a){let e=t=>{let c=[],r=[],l=new Map,o=t.size,s=0,d=0;for(let[i,u]of t)u===0&&r.push(i);if(r.length===0&&o>0)throw Error("Circular dependency detected");for(;r.length>0;){c.push([...r]);let i=[];for(let u of r){s++,l.set(u,d);let f=a.get(u);if(f)for(let p of f){let P=t.get(p)-1;t.set(p,P),P===0&&i.push(p);}}r=i,d++;}if(s<o)throw Error("Circular dependency detected");return {steps:c,levelMap:l}};return ()=>{let t=new Map;for(let c of a.keys()){let r=Array.from(a.get(c)||[]);t.has(c)||t.set(c,0);for(let l of r){let o=t.get(l)||0;t.set(l,++o);}}return e(t)}}var q=()=>{let a=[];return {on:e=>(a.push(e),()=>{let n=a.indexOf(e);n>-1&&a.splice(n,1);}),call:e=>a.forEach(n=>{n(e);})}};function ie(){let{on:a,call:e}=q();return {onError:a,callOnError:e}}function le(){let{on:a,call:e}=q();return {onSuccess:a,callOnSuccess:e}}var ce=()=>{let a=new Set,e=new Map,n=(r,l)=>{e.get(r)?.forEach(o=>o(l));},t=(r,l)=>(e.has(r)||e.set(r,new Set),e.get(r).add(l),()=>e.get(r).delete(l));return {usePlugin:r=>{let l=new Set,o=(s,d)=>{let i=t(s,d);return l.add(i),i};return r.apply({on:o}),a.add(r),()=>{l.forEach(s=>s()),l.clear(),a.delete(r);}},emit:n}};function ue(){let{on:a,call:e}=q();return {onStart:a,callOnStart:e}}var de=(a={frameQuota:12})=>{let e=performance.now(),n=0,t=false,c=()=>!!navigator?.scheduling?.isInputPending?.({includeContinuous:true});return {getIsFirstFrame:()=>t,reset(){e=performance.now(),n=0,t=true;},shouldYield(){let r=performance.now();return n++,!!((n>=5||t)&&(n=0,r-e>a.frameQuota||c()))},async yieldToMain(){return new Promise(r=>{Pe(()=>{e=performance.now(),n=0,t&&(t=false),r();});})}}},Pe=a=>{let{port1:e,port2:n}=new MessageChannel;e.onmessage=a,n.postMessage(null);};function fe(a,e,n,t,c){let r=new Map,l=a.useGreedy,o=de();return async(d,i)=>{let f=Symbol("token"),p=d||"__NOTIFY_ALL__";r.set(p,f);let P=false;o.reset();let g=new Set,m=new Set,_=new Set;i.forEach(I=>{_.add(I),e.GetAllNextDependency(I).forEach(v=>_.add(v));});let N=new Map,C=new Map,M=new Set,L=e.GetPathToLevelMap(),A=0,z=0,H=I=>{e.GetAllNextDependency(I).forEach($=>{let G=L.get($)||0;G>z&&(z=G);});};d?(A=L.get(d)??0,H(d),g.add(d)):i.forEach(I=>H(I)),i.forEach(I=>{M.add(I);});let y=performance.now();t.emit("flow:start",{path:p}),t.callOnStart({path:p});let R=false,O=30,Q=I=>{let{target:v,trigger:$}=I,G=false,D=false,k=n.GetNodeByPath(v),W=[],E=(h,T)=>{if(g.has(h)||m.has(h)||M.has(h))return;let K=0,x=L.get(h)??0;if(N.has(h))K=N.get(h)-1;else {if(x>A&&N.size>O){C.has(x)||C.set(x,new Set),C.get(x).add(h),t.emit("node:intercept",{path:h,type:7});return}let F=e.GetPrevDependency(h),S=0;for(let b of F){if(g.has(b))continue;(L.get(b)??0)>A&&S++;}K=S;}if(K<=0){let F=M.has(h),S=m.has(h);if(F||S){t.emit("node:intercept",{path:h,type:S?3:3.1});return}N.delete(h),M.add(h),t.emit("node:release",{path:h,type:T,detail:{path:v}});}else N.set(h,K);},B=(h=[])=>{if(r.get(p)!==f)return;if(h.length){let x={},F=k.proxy;for(let S of h){let b=(S.args||[]).reduce((U,Y)=>(U[Y]=F[Y],U),{});try{let U=S.fn(b);U&&typeof U=="object"&&Object.assign(x,U);}catch(U){}}for(let S in x)if(S in k.state)k.state[S]=x[S];else throw {error:`wrong effect in ${k.path}`};G=true;}G&&c.flushPathSet.add(v),t.emit("node:success",{path:v}),g.add(v);let T=e.GetNextDependency(v);(G||D)&&e.GetAllNextDependency(v).forEach(F=>_.add(F));for(let x of T){if(g.has(x)){t.emit("node:intercept",{path:x,type:2});continue}if(m.has(x)||M.has(x)){t.emit("node:intercept",{path:x,type:m.has(x)?3:3.1});continue}if(G||D)E(x,1);else if(N.has(x))E(x,2);else {let S=L.get(x);C.has(S)||C.set(S,new Set);let b=C.get(S);b.has(x)||(b.add(x),t.emit("node:stagnate",{path:x,type:1}));}}m.delete(v),(async()=>{if(!P){let x=m.size,F=M.size;t.emit("flow:fire",{path:v,type:1,detail:{active:x,pending:F,blocked:N.size}}),j();}})();},V=h=>{t.emit("node:error",{path:v,error:h});let T=Symbol("abort");r.set(p,T),M.clear(),N.clear(),m.clear(),t.callOnError(h);},w=(h,T)=>{let K=false;h!==k[T]&&(k[T]=h,k.state[T]=h,G=true,t.emit("node:bucket:success",{path:v,key:T,value:h}),T==="value"&&(K=true)),k.nodeBucket[T].isForceNotify()&&(D=true),(K||D)&&H(v);};t.emit("node:start",{path:v});try{let h=[];for(let T in k.nodeBucket){let K=k.nodeBucket[T];h.push(...K.getSideEffect());let x=K.evaluate({affectKey:T,triggerPath:$,GetRenderSchemaByPath:F=>n.GetNodeByPath(F).proxy,GetValueByPath:F=>n.GetNodeByPath(F).state,GetToken:()=>f});if(x instanceof Promise){let F=x.then(S=>{r.get(p)===f&&w(S,T);});W.push(F);}else w(x,T);}if(W.length>0)return Promise.all(W).then(()=>{B(h);}).catch(V);B(h);return}catch(h){V(h);}},j=async()=>{if(r.get(p)!==f){P=false;return}P=true;let I=o.getIsFirstFrame(),v=0,$=()=>l&&I?30:1/0,G=0,D=$();try{for(;r.get(p)===f;){let k=G>=D,W=o.shouldYield();if(k||W){if(G>0&&(v++,(I||v%2===0)&&c.requestUpdate()),await o.yieldToMain(),r.get(p)!==f)break;G=0,I=o.getIsFirstFrame();}if(M.size>0&&m.size<5){for(let E of M){if(m.size>=5||G>=D)break;let B=L.get(E)??0,V=e.GetPrevDependency(E),w=V.length>1;if((!l||w)&&B>A){M.delete(E);let T=V.filter(K=>_.has(K)&&!g.has(K)).length;N.set(E,T||0),t.emit("node:intercept",{path:E,type:T>0?4:5,detail:{targetLevel:B,currentLevel:A,pendingParentsCount:T}});continue}if(M.delete(E),m.add(E),t.emit("node:processing",{path:E}),Q({target:E,trigger:d}),G++,G>=D||o.shouldYield())break}if(M.size>0)continue}if(G<D&&l&&N.size>0&&m.size<5){let E=!1,B=0;for(let[V,w]of N)if(w<=0){let h=L.get(V)??0,T=e.GetPrevDependency(V);if(h>A&&T.length>1)continue;if(N.delete(V),M.add(V),B++,E=!0,t.emit("node:release",{path:V,type:4}),B>=D)break}if(B>0)continue;if(E){if(o.shouldYield()&&(await o.yieldToMain(),r.get(p)!==f))break;continue}}if(m.size===0&&M.size===0){let E=new Set;for(let w of C.keys())E.add(w);for(let[w]of N){let h=L.get(w)??0;h>A&&E.add(h);}let B=Array.from(E).sort((w,h)=>w-h),V=B[0];if(B.length>0&&V<=z){let w=B[0];if(w<=z){A=w;let h=C.get(w);h&&(h.forEach(T=>M.add(T)),C.delete(w));for(let[T]of N)(L.get(T)??0)===w&&(N.delete(T),M.add(T),t.emit("node:release",{path:T,type:3,detail:{level:w}}));continue}}else {C.forEach((w,h)=>{w.forEach(T=>{g.add(T),t.emit("node:intercept",{path:T,type:6});});}),C.clear();for(let[w]of N)g.add(w),t.emit("node:intercept",{path:w,type:6});N.clear();break}}M.size>0&&m.size>=5&&t.emit("flow:wait",{type:2});break}}finally{if(P=false,m.size+N.size+M.size===0){if(r.get(p)===f&&!R){R=true,t.emit("flow:end",{type:1}),c.requestUpdate();let W=performance.now();t.emit("flow:success",{duration:(W-y).toFixed(2)+"ms"}),Promise.resolve().then(()=>{t.callOnSuccess();});}}else t.emit("flow:wait",{type:1,detail:{nums:m.size}});}};j();}}function ee(a){let{path:e,uid:n,type:t,meta:c,dirtySignal:r,triggerUI:l,state:o}=a,s=null,i={path:e,uid:n,type:t,meta:c,dirtySignal:r,createView:(u={})=>{let f=new Proxy(u,{get(p,P){let g=P;return g in a.state?a.state[g]:g in a?a[g]:c&&g in c?c[g]:Reflect.get(p,P)},set(p,P,g){let m=P;return m in a.state?(a.state[m]=g,l(),true):Reflect.set(p,P,g)},ownKeys(p){let P=new Set([...Reflect.ownKeys(p),...Object.keys(o||{}),...Object.keys(c||{})]);return Array.from(P)},getOwnPropertyDescriptor(p,P){return o&&P in o||c&&P in c?{enumerable:true,configurable:true}:Reflect.getOwnPropertyDescriptor(p,P)}});return s=f,f}};return "children"in a?{...i,children:a.children}:{...i,state:a.state,nodeBucket:a.nodeBucket,notifyKeys:a.notifyKeys,dependOn:a.dependOn,get proxy(){return s}}}function ye(a,e,n,t,c,r){let l=0,o=new Map,s=new Map,d=new Map,i=false,u=new Set,g=async()=>{let y=Array.from(u);u.clear();for(let R of y){let O=M(R);r.signalTrigger(O.dirtySignal);}},m=()=>{i||(i=true,requestAnimationFrame(()=>{try{for(;u.size>0;)g();}finally{i=false;}}));},_=fe({useGreedy:e.useGreedy},n,{GetNodeByPath:M},c,{requestUpdate:m,flushPathSet:u}),N=y=>{if(o.has(y.path))throw new Error(`[MeshFlow] Duplicate Path: ${String(y.path)}`);let R=++l,O={path:y.path,getNode:I=>M(I)},Q=I=>{let v=I({...O}),$=M(y.path);if(t.createHistoryAction&&t.pushIntoHistory){let G=t.createHistoryAction([{path:y.path,value:$.state.value},{path:y.path,value:v}],D=>{let k=M(D.path);k.state.value=D.value,A(D.path);});t.pushIntoHistory(G);}$.state.value=v,A(y.path);},j=ee({uid:R,path:y.path,state:y.state,meta:y.meta,nodeBucket:y.nodeBucket,dirtySignal:y.dirtySignal,notifyKeys:y.notifyKeys,dependOn:Q,triggerUI:()=>r.signalTrigger(y.dirtySignal)});return o.set(j.path,R),s.set(R,j),j},C=y=>{if(o.has(y.path))throw new Error(`[MeshFlow] Duplicate Path: ${String(y.path)}`);let R=++l,O=ee({uid:R,path:y.path,state:{},meta:y,nodeBucket:{},children:y.children});return o.set(O.path,R),d.set(R,O),O};function M(y){let R=o.get(y),O=s.get(R);if(!O)throw Error("wrong ID");return O}function L(y){let R=o.get(y);return d.get(R)}let A=y=>{if(!M(y))throw Error("Node undefined");u.add(y),m();let O=n.GetNextDependency(y);z(O,y);};function z(y,R){_(R,y);}return {registerNode:N,registerGroupNode:C,GetNodeByPath:M,GetGroupByPath:L,notify:A,notifyAll:async()=>{Promise.resolve().then(async()=>{let y=n.GetDependencyOrder();if(!y||y.length===0)return;let R=y[0];try{_(null,R);}catch(O){throw c.callOnError(O),O}finally{m();}});},UITrigger:r,UidToNodeMap:s}}function pe(a,e){let n=false,t=false,c=new Map,r=new Map,l=new Map,o=new Map,s=[],d=new Map,{GetNextDependency:u,GetPrevDependency:f,GetAllPrevDependency:p,GetAllNextDependency:P,rebuildDirectDependencyMaps:g}=ae(()=>c,()=>r,()=>o,()=>l),m={},_={};if(e.modules.useHistory){let{Undo:S,Redo:b,PushIntoHistory:U,CreateHistoryAction:Y,initCanUndo:he,initCanRedo:ge}=e.modules.useHistory();m.pushIntoHistory=U,m.createHistoryAction=Y,_={Undo:S,Redo:b,initCanUndo:he,initCanRedo:ge};}let{onError:N,callOnError:C}=ie(),{onSuccess:M,callOnSuccess:L}=le(),{onStart:A,callOnStart:z}=ue(),{emit:H,usePlugin:y}=ce(),{SetTrace:R,useTrace:O}=se(),Q=O();y(Q);let j=ye(a,{useGreedy:e.config.useGreedy},{GetDependencyOrder:()=>s,GetAllNextDependency:P,GetNextDependency:u,GetPrevDependency:f,GetAllPrevDependency:p,GetPathToLevelMap:()=>d},m,{callOnError:C,callOnSuccess:L,callOnStart:z,emit:H},e.UITrigger),{GetGroupByPath:I,GetNodeByPath:v,notifyAll:$}=j,G={};if(e.modules.useInternalForm){let{uiSchema:S,GetFormData:b}=e.modules.useInternalForm(j,a);G={uiSchema:S,GetFormData:b};}let D={};if(e.modules.useSchemaValidators){let{SetValidators:S}=e.modules.useSchemaValidators(v);D={SetValidators:S};}let{SetRule:k,SetRules:W}=ne(v,c,r),{SetStrategy:E}=re(v),B=oe(c),V=()=>{let S=B();s=S.steps,d=S.levelMap;},w=()=>{t||(t=true,Promise.resolve().then(()=>{if(V(),n){let{directNextMap:S,directPrevMap:b}=g(s.flat());l=S,o=b;}}).finally(()=>{t=false,n=false;}));};return {SetRule:(S,b,U,Y)=>{k(S,b,U,Y),n=true,w();},SetRules:(S,b,U,Y)=>{W(S,b,U,Y),n=true,w();},SetStrategy:E,SetTrace:R,usePlugin:y,SetValue:(S,b)=>{v(S).dependOn(()=>b);},GetValue:(S,b="value")=>v(S)[b],GetGroupByPath:I,notifyAll:async()=>{V(),await $();},GetAllDependency:()=>c,GetDependencyOrder:()=>s,historyExports:_,formExports:G,validatorExports:D,onError:N,onSuccess:M,onStart:A}}var J=new Map,me=(a,e,n)=>{try{if(typeof n.UITrigger.signalCreator!="function"||typeof n.UITrigger.signalTrigger!="function")throw Error("ui trigger undefined");if(J.has(a))throw Error("engineID repeated");let t=pe(e,{config:n.config||{useGreedy:!1},UITrigger:n.UITrigger,modules:n.modules||{},plugins:{}}),{SetRule:c,SetRules:r,SetStrategy:l,SetValue:o,GetValue:s,usePlugin:d,GetGroupByPath:i,notifyAll:u,SetTrace:f,GetAllDependency:p,GetDependencyOrder:P,historyExports:g,formExports:m,validatorExports:_,onError:N,onSuccess:C,onStart:M}=t,A={...{config:{SetRule:c,SetRules:r,SetStrategy:l,notifyAll:u,SetTrace:f,usePlugin:d},data:{SetValue:o,GetValue:s,GetGroupByPath:i},dependency:{GetAllDependency:p,GetDependencyOrder:P},hooks:{onError:N,onSuccess:C,onStart:M}}},z=n.modules;return z&&Object.keys(z).forEach(H=>{let y=H;if(y.startsWith("use")){let R=y.slice(3);y=R.charAt(0).toLowerCase()+R.slice(1);}H==="useHistory"&&g&&Object.keys(g).length>0&&(A[y]=g),H==="useInternalForm"&&Object.keys(m).length>0&&(A[y]=m),H==="useSchemaValidators"&&Object.keys(_).length>0&&(A[y]=_);}),J.set(a,A),A}catch(t){throw Error(t)}},Ze=()=>(a,e,n)=>Se(a,e,n),et=a=>{let e=J.get(a);if(e)return e;throw Error("[MeshFlow] Engine ID not found.")},tt=a=>{J.delete(a);},Se=me;export{tt as deleteEngine,et as useEngine,me as useEngineManager,Se as useMeshFlow,Ze as useMeshFlowDefiner};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meshflow/core",
3
- "version": "0.1.8",
3
+ "version": "0.2.1",
4
4
  "description": "A logic orchestration engine utilizing topological scheduling and watermark control to resolve asynchronous race conditions in complex dependency linkages.”",
5
5
  "main": "./index.cjs",
6
6
  "module": "./index.js",