@flowgram.ai/variable-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2067 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var __decorateClass = (decorators, target, key, kind) => {
20
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
21
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
22
+ if (decorator = decorators[i])
23
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
24
+ if (kind && result) __defProp(target, key, result);
25
+ return result;
26
+ };
27
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
28
+
29
+ // src/index.ts
30
+ var src_exports = {};
31
+ __export(src_exports, {
32
+ ASTFactory: () => ASTFactory,
33
+ ASTKind: () => ASTKind,
34
+ ASTNode: () => ASTNode,
35
+ ASTNodeFlags: () => ASTNodeFlags,
36
+ ASTRegisters: () => ASTRegisters,
37
+ ArrayType: () => ArrayType,
38
+ BaseExpression: () => BaseExpression,
39
+ BaseType: () => BaseType,
40
+ BaseVariableField: () => BaseVariableField,
41
+ BooleanType: () => BooleanType,
42
+ DataNode: () => DataNode,
43
+ EnumerateExpression: () => EnumerateExpression,
44
+ ExpressionList: () => ExpressionList,
45
+ IntegerType: () => IntegerType,
46
+ KeyPathExpression: () => KeyPathExpression,
47
+ KeyPathExpressionV2: () => KeyPathExpressionV2,
48
+ ListNode: () => ListNode,
49
+ MapNode: () => MapNode,
50
+ MapType: () => MapType,
51
+ NumberType: () => NumberType,
52
+ ObjectType: () => ObjectType,
53
+ Property: () => Property,
54
+ Scope: () => Scope,
55
+ ScopeChain: () => ScopeChain,
56
+ ScopeOutputData: () => ScopeOutputData,
57
+ ScopeProvider: () => ScopeProvider,
58
+ StringType: () => StringType,
59
+ VariableContainerModule: () => VariableContainerModule,
60
+ VariableDeclaration: () => VariableDeclaration,
61
+ VariableDeclarationList: () => VariableDeclarationList,
62
+ VariableEngine: () => VariableEngine,
63
+ VariableEngineProvider: () => VariableEngineProvider,
64
+ VariableFieldKeyRenameService: () => VariableFieldKeyRenameService,
65
+ VariableTable: () => VariableTable,
66
+ injectToAST: () => injectToAST,
67
+ postConstructAST: () => postConstructAST,
68
+ useAvailableVariables: () => useAvailableVariables,
69
+ useCurrentScope: () => useCurrentScope,
70
+ useScopeAvailable: () => useScopeAvailable,
71
+ useScopeContext: () => useScopeContext
72
+ });
73
+ module.exports = __toCommonJS(src_exports);
74
+
75
+ // src/variable-container-module.ts
76
+ var import_inversify7 = require("inversify");
77
+
78
+ // src/variable-engine.ts
79
+ var import_rxjs6 = require("rxjs");
80
+ var import_inversify5 = require("inversify");
81
+ var import_utils10 = require("@flowgram.ai/utils");
82
+ var import_utils11 = require("@flowgram.ai/utils");
83
+
84
+ // src/utils/toDisposable.tsx
85
+ var import_utils = require("@flowgram.ai/utils");
86
+ function subsToDisposable(subscription) {
87
+ return import_utils.Disposable.create(() => subscription.unsubscribe());
88
+ }
89
+
90
+ // src/utils/memo.ts
91
+ var createMemo = () => {
92
+ const _memoCache = /* @__PURE__ */ new Map();
93
+ const memo = (key, fn) => {
94
+ if (_memoCache.has(key)) {
95
+ return _memoCache.get(key);
96
+ }
97
+ const data = fn();
98
+ _memoCache.set(key, data);
99
+ return data;
100
+ };
101
+ const clear = (key) => {
102
+ if (key) {
103
+ _memoCache.delete(key);
104
+ } else {
105
+ _memoCache.clear();
106
+ }
107
+ };
108
+ memo.clear = clear;
109
+ return memo;
110
+ };
111
+
112
+ // src/scope/scope-chain.ts
113
+ var import_inversify = require("inversify");
114
+ var import_utils2 = require("@flowgram.ai/utils");
115
+
116
+ // src/providers.ts
117
+ var VariableEngineProvider = Symbol("DynamicVariableEngine");
118
+ var ContainerProvider = Symbol("ContainerProvider");
119
+
120
+ // src/scope/scope-chain.ts
121
+ var ScopeChain = class {
122
+ constructor() {
123
+ this.toDispose = new import_utils2.DisposableCollection();
124
+ }
125
+ get variableEngine() {
126
+ return this.variableEngineProvider();
127
+ }
128
+ /**
129
+ * 所有作用域依赖关系刷新
130
+ */
131
+ refreshAllChange() {
132
+ this.variableEngine.getAllScopes().forEach((_scope) => {
133
+ _scope.refreshCovers();
134
+ _scope.refreshDeps();
135
+ });
136
+ }
137
+ dispose() {
138
+ this.toDispose.dispose();
139
+ }
140
+ get disposed() {
141
+ return this.toDispose.disposed;
142
+ }
143
+ get onDispose() {
144
+ return this.toDispose.onDispose;
145
+ }
146
+ };
147
+ __decorateClass([
148
+ (0, import_inversify.inject)(VariableEngineProvider)
149
+ ], ScopeChain.prototype, "variableEngineProvider", 2);
150
+ ScopeChain = __decorateClass([
151
+ (0, import_inversify.injectable)()
152
+ ], ScopeChain);
153
+
154
+ // src/scope/scope.ts
155
+ var import_utils9 = require("@flowgram.ai/utils");
156
+
157
+ // src/ast/types.ts
158
+ var ASTKind = /* @__PURE__ */ ((ASTKind2) => {
159
+ ASTKind2["String"] = "String";
160
+ ASTKind2["Number"] = "Number";
161
+ ASTKind2["Integer"] = "Integer";
162
+ ASTKind2["Boolean"] = "Boolean";
163
+ ASTKind2["Object"] = "Object";
164
+ ASTKind2["Array"] = "Array";
165
+ ASTKind2["Map"] = "Map";
166
+ ASTKind2["Union"] = "Union";
167
+ ASTKind2["Any"] = "Any";
168
+ ASTKind2["Property"] = "Property";
169
+ ASTKind2["VariableDeclaration"] = "VariableDeclaration";
170
+ ASTKind2["VariableDeclarationList"] = "VariableDeclarationList";
171
+ ASTKind2["KeyPathExpression"] = "KeyPathExpression";
172
+ ASTKind2["EnumerateExpression"] = "EnumerateExpression";
173
+ ASTKind2["ExpressionList"] = "ExpressionList";
174
+ ASTKind2["ListNode"] = "ListNode";
175
+ ASTKind2["DataNode"] = "DataNode";
176
+ ASTKind2["MapNode"] = "MapNode";
177
+ return ASTKind2;
178
+ })(ASTKind || {});
179
+
180
+ // src/ast/ast-registers.ts
181
+ var import_lodash3 = require("lodash");
182
+ var import_inversify2 = require("inversify");
183
+
184
+ // src/ast/utils/inversify.ts
185
+ var injectToAST = (serviceIdentifier) => function(target, propertyKey) {
186
+ if (!serviceIdentifier) {
187
+ throw new Error(
188
+ `ServiceIdentifier ${serviceIdentifier} in @lazyInject is Empty, it might be caused by file circular dependency, please check it.`
189
+ );
190
+ }
191
+ const descriptor = {
192
+ get() {
193
+ const container = this.scope.variableEngine.container;
194
+ return container.get(serviceIdentifier);
195
+ },
196
+ set() {
197
+ },
198
+ configurable: true,
199
+ enumerable: true
200
+ };
201
+ return descriptor;
202
+ };
203
+ var POST_CONSTRUCT_AST_SYMBOL = Symbol("post_construct_ast");
204
+ var postConstructAST = () => (target, propertyKey) => {
205
+ if (!Reflect.hasMetadata(POST_CONSTRUCT_AST_SYMBOL, target)) {
206
+ Reflect.defineMetadata(POST_CONSTRUCT_AST_SYMBOL, propertyKey, target);
207
+ } else {
208
+ throw Error("Duplication Post Construct AST");
209
+ }
210
+ };
211
+
212
+ // src/ast/utils/helpers.ts
213
+ function updateChildNodeHelper({
214
+ getChildNode,
215
+ updateChildNode,
216
+ removeChildNode,
217
+ nextJSON
218
+ }) {
219
+ const currNode = getChildNode();
220
+ const isNewKind = currNode?.kind !== nextJSON?.kind;
221
+ const isNewKey = nextJSON?.key && nextJSON?.key !== currNode?.key;
222
+ if (isNewKind || isNewKey) {
223
+ if (currNode) {
224
+ currNode.dispose();
225
+ removeChildNode();
226
+ }
227
+ if (nextJSON) {
228
+ const newNode = this.createChildNode(nextJSON);
229
+ updateChildNode(newNode);
230
+ this.fireChange();
231
+ return newNode;
232
+ } else {
233
+ this.fireChange();
234
+ }
235
+ } else if (nextJSON) {
236
+ currNode?.fromJSON(nextJSON);
237
+ }
238
+ return currNode;
239
+ }
240
+ function parseTypeJsonOrKind(typeJSONOrKind) {
241
+ return typeof typeJSONOrKind === "string" ? { kind: typeJSONOrKind } : typeJSONOrKind;
242
+ }
243
+ function getAllChildren(ast) {
244
+ return [...ast.children, ...ast.children.map((_child) => getAllChildren(_child)).flat()];
245
+ }
246
+
247
+ // src/ast/flags.ts
248
+ var ASTNodeFlags = /* @__PURE__ */ ((ASTNodeFlags2) => {
249
+ ASTNodeFlags2[ASTNodeFlags2["None"] = 0] = "None";
250
+ ASTNodeFlags2[ASTNodeFlags2["VariableField"] = 1] = "VariableField";
251
+ ASTNodeFlags2[ASTNodeFlags2["Expression"] = 4] = "Expression";
252
+ ASTNodeFlags2[ASTNodeFlags2["BasicType"] = 8] = "BasicType";
253
+ ASTNodeFlags2[ASTNodeFlags2["DrilldownType"] = 16] = "DrilldownType";
254
+ ASTNodeFlags2[ASTNodeFlags2["EnumerateType"] = 32] = "EnumerateType";
255
+ ASTNodeFlags2[ASTNodeFlags2["UnionType"] = 64] = "UnionType";
256
+ ASTNodeFlags2[ASTNodeFlags2["VariableType"] = 120] = "VariableType";
257
+ return ASTNodeFlags2;
258
+ })(ASTNodeFlags || {});
259
+
260
+ // src/ast/ast-node.ts
261
+ var import_rxjs = require("rxjs");
262
+ var import_nanoid = require("nanoid");
263
+ var import_fast_equals = require("fast-equals");
264
+ var import_utils3 = require("@flowgram.ai/utils");
265
+ var ASTNode = class _ASTNode {
266
+ /**
267
+ * 构造函数
268
+ * @param createParams 创建 ASTNode 的必要参数
269
+ * @param injectOptions 依赖注入各种模块
270
+ */
271
+ constructor({ key, parent, scope }, opts) {
272
+ /**
273
+ * 节点 Flags,记录一些 Flag 信息
274
+ */
275
+ this.flags = 0 /* None */;
276
+ /**
277
+ * 节点的版本号,每 fireChange 一次 version + 1
278
+ */
279
+ this._version = 0;
280
+ /**
281
+ * 更新锁
282
+ */
283
+ this.changeLocked = false;
284
+ /**
285
+ * Batch Update 相关参数
286
+ */
287
+ this._batch = {
288
+ batching: false,
289
+ hasChangesInBatch: false
290
+ };
291
+ /**
292
+ * AST 节点变化事件,基于 Rxjs 实现
293
+ * - 使用了 BehaviorSubject, 在订阅时会自动触发一次事件,事件为当前值
294
+ */
295
+ this.value$ = new import_rxjs.BehaviorSubject(this);
296
+ /**
297
+ * 子节点
298
+ */
299
+ this._children = /* @__PURE__ */ new Set();
300
+ /**
301
+ * 删除节点处理事件列表
302
+ */
303
+ this.toDispose = new import_utils3.DisposableCollection(
304
+ import_utils3.Disposable.create(() => {
305
+ this.parent?.fireChange();
306
+ this.children.forEach((child) => child.dispose());
307
+ })
308
+ );
309
+ /**
310
+ * 销毁时触发的回调
311
+ */
312
+ this.onDispose = this.toDispose.onDispose;
313
+ this.scope = scope;
314
+ this.parent = parent;
315
+ this.opts = opts;
316
+ this.key = key || (0, import_nanoid.nanoid)();
317
+ this.fromJSON = this.withBatchUpdate(this.fromJSON.bind(this));
318
+ this.dispatchGlobalEvent({ type: "NewAST" });
319
+ }
320
+ /**
321
+ * AST 节点的类型
322
+ */
323
+ get kind() {
324
+ if (!this.constructor.kind) {
325
+ throw new Error(`ASTNode Registry need a kind: ${this.constructor.name}`);
326
+ }
327
+ return this.constructor.kind;
328
+ }
329
+ /**
330
+ * 获取当前节点所有子节点
331
+ */
332
+ get children() {
333
+ return Array.from(this._children);
334
+ }
335
+ /**
336
+ * 转化为 ASTNodeJSON
337
+ * @returns
338
+ */
339
+ toJSON() {
340
+ console.warn("[VariableEngine] Please Implement toJSON method for " + this.kind);
341
+ return {
342
+ kind: this.kind
343
+ };
344
+ }
345
+ /**
346
+ * 创建子节点
347
+ * @param json 子节点的 AST JSON
348
+ * @returns
349
+ */
350
+ createChildNode(json) {
351
+ const astRegisters = this.scope.variableEngine.astRegisters;
352
+ const child = astRegisters.createAST(json, {
353
+ parent: this,
354
+ scope: this.scope
355
+ });
356
+ this._children.add(child);
357
+ child.toDispose.push(
358
+ import_utils3.Disposable.create(() => {
359
+ this._children.delete(child);
360
+ })
361
+ );
362
+ return child;
363
+ }
364
+ /**
365
+ * 更新子节点,快速实现子节点更新消费逻辑
366
+ * @param keyInThis 当前对象上的指定 key
367
+ */
368
+ updateChildNodeByKey(keyInThis, nextJSON) {
369
+ this.withBatchUpdate(updateChildNodeHelper).call(this, {
370
+ getChildNode: () => this[keyInThis],
371
+ updateChildNode: (_node) => this[keyInThis] = _node,
372
+ removeChildNode: () => this[keyInThis] = void 0,
373
+ nextJSON
374
+ });
375
+ }
376
+ /**
377
+ * 批处理更新,批处理函数内所有的 fireChange 都合并成一个
378
+ * @param updater 批处理函数
379
+ * @returns
380
+ */
381
+ withBatchUpdate(updater) {
382
+ return (...args) => {
383
+ if (this._batch.batching) {
384
+ return updater.call(this, ...args);
385
+ }
386
+ this._batch.hasChangesInBatch = false;
387
+ this._batch.batching = true;
388
+ const res = updater.call(this, ...args);
389
+ this._batch.batching = false;
390
+ if (this._batch.hasChangesInBatch) {
391
+ this.fireChange();
392
+ }
393
+ this._batch.hasChangesInBatch = false;
394
+ return res;
395
+ };
396
+ }
397
+ /**
398
+ * 触发当前节点更新
399
+ */
400
+ fireChange() {
401
+ if (this.changeLocked || this.disposed) {
402
+ return;
403
+ }
404
+ if (this._batch.batching) {
405
+ this._batch.hasChangesInBatch = true;
406
+ return;
407
+ }
408
+ this._version++;
409
+ this.value$.next(this);
410
+ this.dispatchGlobalEvent({ type: "UpdateAST" });
411
+ this.parent?.fireChange();
412
+ }
413
+ /**
414
+ * 节点的版本值
415
+ * - 通过 NodeA === NodeB && versionA === versionB 可以比较两者是否相等
416
+ */
417
+ get version() {
418
+ return this._version;
419
+ }
420
+ /**
421
+ * 节点唯一 hash 值
422
+ */
423
+ get hash() {
424
+ return `${this._version}${this.kind}${this.key}`;
425
+ }
426
+ /**
427
+ * 监听 AST 节点的变化
428
+ * @param observer 监听回调
429
+ * @param selector 监听指定数据
430
+ * @returns
431
+ */
432
+ subscribe(observer, { selector, debounceAnimation, triggerOnInit } = {}) {
433
+ return subsToDisposable(
434
+ this.value$.pipe(
435
+ (0, import_rxjs.map)(() => selector ? selector(this) : this),
436
+ (0, import_rxjs.distinctUntilChanged)(
437
+ (a, b) => (0, import_fast_equals.shallowEqual)(a, b),
438
+ (value) => {
439
+ if (value instanceof _ASTNode) {
440
+ return value.hash;
441
+ }
442
+ return value;
443
+ }
444
+ ),
445
+ // 默认跳过 BehaviorSubject 第一次触发
446
+ triggerOnInit ? (0, import_rxjs.tap)(() => null) : (0, import_rxjs.skip)(1),
447
+ // 每个 animationFrame 内所有更新合并成一个
448
+ debounceAnimation ? (0, import_rxjs.debounceTime)(0, import_rxjs.animationFrameScheduler) : (0, import_rxjs.tap)(() => null)
449
+ ).subscribe(observer)
450
+ );
451
+ }
452
+ dispatchGlobalEvent(event) {
453
+ this.scope.event.dispatch({
454
+ ...event,
455
+ ast: this
456
+ });
457
+ }
458
+ /**
459
+ * 销毁
460
+ */
461
+ dispose() {
462
+ if (this.toDispose.disposed) {
463
+ return;
464
+ }
465
+ this.toDispose.dispose();
466
+ this.dispatchGlobalEvent({ type: "DisposeAST" });
467
+ this.value$.complete();
468
+ this.value$.unsubscribe();
469
+ }
470
+ get disposed() {
471
+ return this.toDispose.disposed;
472
+ }
473
+ };
474
+
475
+ // src/ast/type/base-type.ts
476
+ var BaseType = class extends ASTNode {
477
+ constructor() {
478
+ super(...arguments);
479
+ this.flags = 8 /* BasicType */;
480
+ }
481
+ /**
482
+ * 类型是否一致,节点有额外信息判断,请参考 extraTypeInfoEqual
483
+ * @param targetTypeJSON
484
+ */
485
+ isTypeEqual(targetTypeJSONOrKind) {
486
+ const targetTypeJSON = parseTypeJsonOrKind(targetTypeJSONOrKind);
487
+ if (targetTypeJSON?.kind === "Union" /* Union */) {
488
+ return (targetTypeJSON?.types || [])?.some(
489
+ (_subType) => this.isTypeEqual(_subType)
490
+ );
491
+ }
492
+ return this.kind === targetTypeJSON?.kind;
493
+ }
494
+ /**
495
+ * 可下钻类型需实现
496
+ * @param keyPath
497
+ */
498
+ getByKeyPath(keyPath = []) {
499
+ throw new Error(`Get By Key Path is not implemented for Type: ${this.kind}`);
500
+ }
501
+ toJSON() {
502
+ return {
503
+ kind: this.kind
504
+ };
505
+ }
506
+ };
507
+
508
+ // src/ast/type/array.ts
509
+ var ArrayType = class extends BaseType {
510
+ constructor() {
511
+ super(...arguments);
512
+ this.flags = 16 /* DrilldownType */ | 32 /* EnumerateType */;
513
+ }
514
+ fromJSON({ items }) {
515
+ this.updateChildNodeByKey("items", parseTypeJsonOrKind(items));
516
+ }
517
+ // items 类型是否可下钻
518
+ get canDrilldownItems() {
519
+ return !!(this.items?.flags & 16 /* DrilldownType */);
520
+ }
521
+ getByKeyPath(keyPath) {
522
+ const [curr, ...rest] = keyPath || [];
523
+ if (curr === "0" && this.canDrilldownItems) {
524
+ return this.items.getByKeyPath(rest);
525
+ }
526
+ return void 0;
527
+ }
528
+ isTypeEqual(targetTypeJSONOrKind) {
529
+ const targetTypeJSON = parseTypeJsonOrKind(targetTypeJSONOrKind);
530
+ const isSuperEqual = super.isTypeEqual(targetTypeJSONOrKind);
531
+ if (targetTypeJSON?.weak || targetTypeJSON?.kind === "Union" /* Union */) {
532
+ return isSuperEqual;
533
+ }
534
+ return targetTypeJSON && isSuperEqual && // 弱比较,只需要比较 Kind 即可
535
+ (targetTypeJSON?.weak || this.customStrongEqual(targetTypeJSON));
536
+ }
537
+ /**
538
+ * Array 强比较
539
+ * @param targetTypeJSON
540
+ * @returns
541
+ */
542
+ customStrongEqual(targetTypeJSON) {
543
+ if (!this.items) {
544
+ return !targetTypeJSON?.items;
545
+ }
546
+ return this.items?.isTypeEqual(targetTypeJSON.items);
547
+ }
548
+ toJSON() {
549
+ return {
550
+ kind: "Array" /* Array */,
551
+ items: this.items?.toJSON()
552
+ };
553
+ }
554
+ };
555
+ ArrayType.kind = "Array" /* Array */;
556
+
557
+ // src/ast/type/string.ts
558
+ var StringType = class extends BaseType {
559
+ constructor() {
560
+ super(...arguments);
561
+ this.flags = 8 /* BasicType */;
562
+ }
563
+ fromJSON() {
564
+ }
565
+ };
566
+ StringType.kind = "String" /* String */;
567
+
568
+ // src/ast/type/integer.ts
569
+ var IntegerType = class extends BaseType {
570
+ constructor() {
571
+ super(...arguments);
572
+ this.flags = 8 /* BasicType */;
573
+ }
574
+ fromJSON() {
575
+ }
576
+ };
577
+ IntegerType.kind = "Integer" /* Integer */;
578
+
579
+ // src/ast/type/boolean.ts
580
+ var BooleanType = class extends BaseType {
581
+ fromJSON() {
582
+ }
583
+ };
584
+ BooleanType.kind = "Boolean" /* Boolean */;
585
+
586
+ // src/ast/type/number.ts
587
+ var NumberType = class extends BaseType {
588
+ fromJSON() {
589
+ }
590
+ };
591
+ NumberType.kind = "Number" /* Number */;
592
+
593
+ // src/ast/type/map.ts
594
+ var MapType = class extends BaseType {
595
+ fromJSON({ keyType = "String" /* String */, valueType }) {
596
+ this.updateChildNodeByKey("keyType", parseTypeJsonOrKind(keyType));
597
+ this.updateChildNodeByKey("valueType", parseTypeJsonOrKind(valueType));
598
+ }
599
+ // Value 类型是否可下钻,后续实现
600
+ // get canDrilldownValue(): boolean {
601
+ // return !!(this.valueType.flags & ASTNodeFlags.DrilldownType);
602
+ // }
603
+ // getByKeyPath(keyPath: string[]): BaseVariableField | undefined {
604
+ // const [curr, ...rest] = keyPath || [];
605
+ // if (curr === '*' && this.canDrilldownValue) {
606
+ // return this.valueType.getByKeyPath(rest);
607
+ // }
608
+ // return undefined;
609
+ // }
610
+ isTypeEqual(targetTypeJSONOrKind) {
611
+ const targetTypeJSON = parseTypeJsonOrKind(targetTypeJSONOrKind);
612
+ const isSuperEqual = super.isTypeEqual(targetTypeJSONOrKind);
613
+ if (targetTypeJSON?.weak || targetTypeJSON?.kind === "Union" /* Union */) {
614
+ return isSuperEqual;
615
+ }
616
+ return targetTypeJSON && isSuperEqual && // 弱比较,只需要比较 Kind 即可
617
+ (targetTypeJSON?.weak || this.customStrongEqual(targetTypeJSON));
618
+ }
619
+ /**
620
+ * Map 强比较
621
+ * @param targetTypeJSON
622
+ * @returns
623
+ */
624
+ customStrongEqual(targetTypeJSON) {
625
+ const { keyType = "String" /* String */, valueType } = targetTypeJSON;
626
+ const isValueTypeEqual = !valueType && !this.valueType || this.valueType?.isTypeEqual(valueType);
627
+ return isValueTypeEqual && this.keyType?.isTypeEqual(keyType);
628
+ }
629
+ toJSON() {
630
+ return {
631
+ kind: "Map" /* Map */,
632
+ keyType: this.keyType?.toJSON(),
633
+ valueType: this.valueType?.toJSON()
634
+ };
635
+ }
636
+ };
637
+ // public flags: ASTNodeFlags = ASTNodeFlags.DrilldownType | ASTNodeFlags.EnumerateType;
638
+ MapType.kind = "Map" /* Map */;
639
+
640
+ // src/ast/type/object.ts
641
+ var import_lodash = require("lodash");
642
+ var ObjectType = class extends BaseType {
643
+ constructor() {
644
+ super(...arguments);
645
+ this.flags = 16 /* DrilldownType */;
646
+ this.propertyTable = /* @__PURE__ */ new Map();
647
+ }
648
+ fromJSON({ properties }) {
649
+ const removedKeys = new Set(this.propertyTable.keys());
650
+ const prev = [...this.properties || []];
651
+ this.properties = (properties || []).map((property) => {
652
+ const existProperty = this.propertyTable.get(property.key);
653
+ removedKeys.delete(property.key);
654
+ if (existProperty) {
655
+ existProperty.fromJSON(property);
656
+ return existProperty;
657
+ } else {
658
+ const newProperty = this.createChildNode({
659
+ ...property,
660
+ kind: "Property" /* Property */
661
+ });
662
+ this.fireChange();
663
+ this.propertyTable.set(property.key, newProperty);
664
+ return newProperty;
665
+ }
666
+ });
667
+ removedKeys.forEach((key) => {
668
+ const property = this.propertyTable.get(key);
669
+ property?.dispose();
670
+ this.propertyTable.delete(key);
671
+ this.fireChange();
672
+ });
673
+ this.dispatchGlobalEvent({
674
+ type: "ObjectPropertiesChange",
675
+ payload: {
676
+ prev,
677
+ next: [...this.properties]
678
+ }
679
+ });
680
+ }
681
+ toJSON() {
682
+ return {
683
+ kind: "Object" /* Object */,
684
+ properties: this.properties.map((_property) => _property.toJSON())
685
+ };
686
+ }
687
+ /**
688
+ * 根据 KeyPath 找到对应的变量
689
+ * @param keyPath 变量路径
690
+ * @returns
691
+ */
692
+ getByKeyPath(keyPath) {
693
+ const [curr, ...restKeyPath] = keyPath;
694
+ const property = this.propertyTable.get(curr);
695
+ if (!restKeyPath.length) {
696
+ return property;
697
+ }
698
+ if (property?.type && property?.type?.flags & 16 /* DrilldownType */) {
699
+ return property.type.getByKeyPath(restKeyPath);
700
+ }
701
+ return void 0;
702
+ }
703
+ isTypeEqual(targetTypeJSONOrKind) {
704
+ const targetTypeJSON = parseTypeJsonOrKind(targetTypeJSONOrKind);
705
+ const isSuperEqual = super.isTypeEqual(targetTypeJSONOrKind);
706
+ if (targetTypeJSON?.weak || targetTypeJSON?.kind === "Union" /* Union */) {
707
+ return isSuperEqual;
708
+ }
709
+ return targetTypeJSON && isSuperEqual && // 弱比较,只需要比较 Kind 即可
710
+ (targetTypeJSON?.weak || this.customStrongEqual(targetTypeJSON));
711
+ }
712
+ /**
713
+ * Object 类型强比较
714
+ * @param targetTypeJSON
715
+ * @returns
716
+ */
717
+ customStrongEqual(targetTypeJSON) {
718
+ const targetProperties = targetTypeJSON.properties || [];
719
+ const sourcePropertyKeys = Array.from(this.propertyTable.keys());
720
+ const targetPropertyKeys = targetProperties.map((_target) => _target.key);
721
+ const isKeyStrongEqual = !(0, import_lodash.xor)(sourcePropertyKeys, targetPropertyKeys).length;
722
+ return isKeyStrongEqual && targetProperties.every((targetProperty) => {
723
+ const sourceProperty = this.propertyTable.get(targetProperty.key);
724
+ return sourceProperty && sourceProperty.key === targetProperty.key && sourceProperty.type?.isTypeEqual(targetProperty?.type);
725
+ });
726
+ }
727
+ };
728
+ ObjectType.kind = "Object" /* Object */;
729
+
730
+ // src/ast/expression/base-expression.ts
731
+ var import_rxjs2 = require("rxjs");
732
+ var import_fast_equals2 = require("fast-equals");
733
+
734
+ // src/ast/utils/variable-field.ts
735
+ function getParentFields(ast) {
736
+ let curr = ast.parent;
737
+ const res = [];
738
+ while (curr) {
739
+ if (curr.flags & 1 /* VariableField */) {
740
+ res.push(curr);
741
+ }
742
+ curr = curr.parent;
743
+ }
744
+ return res;
745
+ }
746
+
747
+ // src/ast/expression/base-expression.ts
748
+ var BaseExpression = class extends ASTNode {
749
+ constructor(params, opts) {
750
+ super(params, opts);
751
+ this.flags = 4 /* Expression */;
752
+ /**
753
+ * 引用变量
754
+ */
755
+ this._refs = [];
756
+ this.refreshRefs$ = new import_rxjs2.Subject();
757
+ /**
758
+ * 监听引用变量变化
759
+ * 监听 [a.b.c] -> [a.b]
760
+ */
761
+ this.refs$ = this.refreshRefs$.pipe(
762
+ (0, import_rxjs2.map)(() => this.getRefFields()),
763
+ (0, import_rxjs2.distinctUntilChanged)(import_fast_equals2.shallowEqual),
764
+ (0, import_rxjs2.switchMap)(
765
+ (refs) => !refs?.length ? (0, import_rxjs2.of)([]) : (0, import_rxjs2.combineLatest)(
766
+ refs.map(
767
+ (ref) => ref ? ref.value$ : (0, import_rxjs2.of)(void 0)
768
+ )
769
+ )
770
+ ),
771
+ (0, import_rxjs2.share)()
772
+ );
773
+ this.toDispose.push(
774
+ subsToDisposable(
775
+ this.refs$.subscribe((_refs) => {
776
+ this._refs = _refs;
777
+ this.fireChange();
778
+ })
779
+ )
780
+ );
781
+ }
782
+ /**
783
+ * 获取全局变量表,方便表达式获取引用变量
784
+ */
785
+ get globalVariableTable() {
786
+ return this.scope.variableEngine.globalVariableTable;
787
+ }
788
+ /**
789
+ * 父变量字段,通过由近而远的方式进行排序
790
+ */
791
+ get parentFields() {
792
+ return getParentFields(this);
793
+ }
794
+ get refs() {
795
+ return this._refs;
796
+ }
797
+ /**
798
+ * 刷新变量引用
799
+ */
800
+ refreshRefs() {
801
+ this.refreshRefs$.next();
802
+ }
803
+ };
804
+
805
+ // src/ast/expression/expression-list.ts
806
+ var ExpressionList = class extends ASTNode {
807
+ fromJSON({ expressions }) {
808
+ this.expressions = expressions.map((_expression, idx) => {
809
+ const prevExpression = this.expressions[idx];
810
+ if (prevExpression.kind !== _expression.kind) {
811
+ prevExpression.dispose();
812
+ this.fireChange();
813
+ return this.createChildNode(_expression);
814
+ }
815
+ prevExpression.fromJSON(_expression);
816
+ return prevExpression;
817
+ });
818
+ }
819
+ toJSON() {
820
+ return {
821
+ kind: "ExpressionList" /* ExpressionList */,
822
+ properties: this.expressions.map((_expression) => _expression.toJSON())
823
+ };
824
+ }
825
+ };
826
+ ExpressionList.kind = "ExpressionList" /* ExpressionList */;
827
+
828
+ // src/ast/expression/keypath-expression.ts
829
+ var import_fast_equals3 = require("fast-equals");
830
+ var KeyPathExpression = class extends BaseExpression {
831
+ constructor(params, opts) {
832
+ super(params, opts);
833
+ this._keyPath = [];
834
+ this.toDispose.pushAll([
835
+ // 可以用变量列表变化时候 (有新增或者删除时)
836
+ this.scope.available.onVariableListChange(() => {
837
+ this.refreshRefs();
838
+ }),
839
+ // this._keyPath 指向的可引用变量发生变化时,刷新引用数据
840
+ this.scope.available.onAnyVariableChange((_v) => {
841
+ if (_v.key === this._keyPath[0]) {
842
+ this.refreshRefs();
843
+ }
844
+ })
845
+ ]);
846
+ }
847
+ get keyPath() {
848
+ return this._keyPath;
849
+ }
850
+ getRefFields() {
851
+ const ref = this.scope.available.getByKeyPath(this._keyPath);
852
+ return ref ? [ref] : [];
853
+ }
854
+ get returnType() {
855
+ const [refNode] = this._refs || [];
856
+ if (refNode && refNode.flags & 1 /* VariableField */) {
857
+ return refNode.type;
858
+ }
859
+ return;
860
+ }
861
+ /**
862
+ * 业务重改该方法可快速定制自己的 Path 表达式
863
+ * - 只需要将业务的 Path 解析为变量系统的 KeyPath 即可
864
+ * @param json 业务定义的 Path 表达式
865
+ * @returns
866
+ */
867
+ parseToKeyPath(json) {
868
+ return json.keyPath;
869
+ }
870
+ fromJSON(json) {
871
+ const keyPath = this.parseToKeyPath(json);
872
+ if (!(0, import_fast_equals3.shallowEqual)(keyPath, this._keyPath)) {
873
+ this._keyPath = keyPath;
874
+ this.refreshRefs();
875
+ }
876
+ }
877
+ toJSON() {
878
+ return {
879
+ kind: "KeyPathExpression" /* KeyPathExpression */,
880
+ keyPath: this._keyPath
881
+ };
882
+ }
883
+ };
884
+ KeyPathExpression.kind = "KeyPathExpression" /* KeyPathExpression */;
885
+
886
+ // src/ast/expression/enumerate-expression.ts
887
+ var EnumerateExpression = class extends BaseExpression {
888
+ get enumerateFor() {
889
+ return this._enumerateFor;
890
+ }
891
+ get returnType() {
892
+ const childReturnType = this.enumerateFor?.returnType;
893
+ if (childReturnType?.kind === "Array" /* Array */) {
894
+ return childReturnType.items;
895
+ }
896
+ return void 0;
897
+ }
898
+ getRefFields() {
899
+ return [];
900
+ }
901
+ fromJSON({ enumerateFor: expression }) {
902
+ this.updateChildNodeByKey("_enumerateFor", expression);
903
+ }
904
+ toJSON() {
905
+ return {
906
+ kind: "EnumerateExpression" /* EnumerateExpression */,
907
+ enumerateFor: this.enumerateFor?.toJSON()
908
+ };
909
+ }
910
+ };
911
+ EnumerateExpression.kind = "EnumerateExpression" /* EnumerateExpression */;
912
+
913
+ // src/ast/expression/keypath-expression-v2.ts
914
+ var import_fast_equals4 = require("fast-equals");
915
+
916
+ // src/ast/utils/expression.ts
917
+ var import_lodash2 = require("lodash");
918
+ function getAllRefs(ast) {
919
+ return getAllChildren(ast).filter((_child) => _child.flags & 4 /* Expression */).map((_child) => _child.refs).flat().filter(Boolean);
920
+ }
921
+ function checkRefCycle(curr, refNodes) {
922
+ if ((0, import_lodash2.intersection)(curr.scope.coverScopes, refNodes.map((_ref) => _ref?.scope).filter(Boolean)).length === 0) {
923
+ return false;
924
+ }
925
+ const visited = /* @__PURE__ */ new Set();
926
+ const queue = [...refNodes];
927
+ while (queue.length) {
928
+ const currNode = queue.shift();
929
+ visited.add(currNode);
930
+ for (const ref of getAllRefs(currNode).filter((_ref) => !visited.has(_ref))) {
931
+ queue.push(ref);
932
+ }
933
+ }
934
+ return (0, import_lodash2.intersection)(Array.from(visited), getParentFields(curr)).length > 0;
935
+ }
936
+
937
+ // src/ast/expression/keypath-expression-v2.ts
938
+ var KeyPathExpressionV2 = class extends BaseExpression {
939
+ constructor(params, opts) {
940
+ super(params, opts);
941
+ this._keyPath = [];
942
+ this.toDispose.pushAll([
943
+ // 可以用变量列表变化时候 (有新增或者删除时)
944
+ this.scope.available.onVariableListChange(() => {
945
+ this.refreshRefs();
946
+ }),
947
+ // this._keyPath 指向的可引用变量发生变化时,刷新引用数据
948
+ this.scope.available.onAnyVariableChange((_v) => {
949
+ if (_v.key === this._keyPath[0]) {
950
+ this.refreshRefs();
951
+ }
952
+ }),
953
+ subsToDisposable(
954
+ this.refs$.subscribe((_type) => {
955
+ const [ref] = this._refs;
956
+ if (this.prevRefTypeHash !== ref?.type?.hash) {
957
+ this.prevRefTypeHash = ref?.type?.hash;
958
+ this.updateChildNodeByKey("_returnType", this.getReturnTypeJSONByRef(ref));
959
+ }
960
+ })
961
+ )
962
+ ]);
963
+ }
964
+ get keyPath() {
965
+ return this._keyPath;
966
+ }
967
+ getRefFields() {
968
+ const ref = this.scope.available.getByKeyPath(this._keyPath);
969
+ if (checkRefCycle(this, [ref])) {
970
+ console.warn(
971
+ "[CustomKeyPathExpression] checkRefCycle: Reference Cycle Existed",
972
+ this.parentFields.map((_field) => _field.key).reverse()
973
+ );
974
+ return [];
975
+ }
976
+ return ref ? [ref] : [];
977
+ }
978
+ get returnType() {
979
+ return this._returnType;
980
+ }
981
+ /**
982
+ * 业务重改该方法可快速定制自己的 Path 表达式
983
+ * - 只需要将业务的 Path 解析为变量系统的 KeyPath 即可
984
+ * @param json 业务定义的 Path 表达式
985
+ * @returns
986
+ */
987
+ parseToKeyPath(json) {
988
+ return json.keyPath;
989
+ }
990
+ fromJSON(json) {
991
+ const keyPath = this.parseToKeyPath(json);
992
+ if (!(0, import_fast_equals4.shallowEqual)(keyPath, this._keyPath)) {
993
+ this._keyPath = keyPath;
994
+ this.refreshRefs();
995
+ }
996
+ }
997
+ getReturnTypeJSONByRef(_ref) {
998
+ return _ref?.type?.toJSON();
999
+ }
1000
+ toJSON() {
1001
+ return {
1002
+ kind: "KeyPathExpression" /* KeyPathExpression */,
1003
+ keyPath: this._keyPath
1004
+ };
1005
+ }
1006
+ };
1007
+ KeyPathExpressionV2.kind = "KeyPathExpression" /* KeyPathExpression */;
1008
+
1009
+ // src/ast/declaration/variable-declaration.ts
1010
+ var import_utils4 = require("@flowgram.ai/utils");
1011
+
1012
+ // src/ast/declaration/base-variable-field.ts
1013
+ var import_fast_equals5 = require("fast-equals");
1014
+ var BaseVariableField = class extends ASTNode {
1015
+ constructor() {
1016
+ super(...arguments);
1017
+ this.flags = 1 /* VariableField */;
1018
+ this._meta = {};
1019
+ }
1020
+ /**
1021
+ * 父变量字段,通过由近而远的方式进行排序
1022
+ */
1023
+ get parentFields() {
1024
+ return getParentFields(this);
1025
+ }
1026
+ get meta() {
1027
+ return this._meta;
1028
+ }
1029
+ get type() {
1030
+ return this._initializer?.returnType || this._type;
1031
+ }
1032
+ get initializer() {
1033
+ return this._initializer;
1034
+ }
1035
+ /**
1036
+ * 解析 VariableDeclarationJSON 从而生成变量声明节点
1037
+ */
1038
+ fromJSON({ type, initializer, meta }) {
1039
+ this.updateType(type);
1040
+ this.updateInitializer(initializer);
1041
+ this.updateMeta(meta);
1042
+ }
1043
+ updateType(type) {
1044
+ const nextTypeJson = typeof type === "string" ? { kind: type } : type;
1045
+ this.updateChildNodeByKey("_type", nextTypeJson);
1046
+ }
1047
+ updateInitializer(nextInitializer) {
1048
+ this.updateChildNodeByKey("_initializer", nextInitializer);
1049
+ }
1050
+ updateMeta(nextMeta) {
1051
+ if (!(0, import_fast_equals5.shallowEqual)(nextMeta, this._meta)) {
1052
+ this._meta = nextMeta;
1053
+ this.fireChange();
1054
+ }
1055
+ }
1056
+ /**
1057
+ * 根据 keyPath 去找下钻的变量字段
1058
+ * @param keyPath
1059
+ * @returns
1060
+ */
1061
+ getByKeyPath(keyPath) {
1062
+ if (this.type?.flags & 16 /* DrilldownType */) {
1063
+ return this.type.getByKeyPath(keyPath);
1064
+ }
1065
+ return void 0;
1066
+ }
1067
+ /**
1068
+ * 监听类型变化
1069
+ * @param observer
1070
+ * @returns
1071
+ */
1072
+ onTypeChange(observer) {
1073
+ return this.subscribe(observer, { selector: (curr) => curr.type });
1074
+ }
1075
+ /**
1076
+ * 转换为 JSON
1077
+ * @returns
1078
+ */
1079
+ toJSON() {
1080
+ return {
1081
+ kind: this.kind,
1082
+ key: this.key,
1083
+ type: this.type?.toJSON(),
1084
+ initializer: this.initializer?.toJSON(),
1085
+ meta: this._meta
1086
+ };
1087
+ }
1088
+ };
1089
+
1090
+ // src/ast/declaration/variable-declaration.ts
1091
+ var VariableDeclaration = class extends BaseVariableField {
1092
+ constructor(params) {
1093
+ super(params);
1094
+ this._order = 0;
1095
+ this.scope.output.addVariableToTable(this);
1096
+ this.toDispose.push(
1097
+ import_utils4.Disposable.create(() => {
1098
+ this.scope.output.setHasChanges();
1099
+ this.scope.output.removeVariableFromTable(this.key);
1100
+ })
1101
+ );
1102
+ }
1103
+ get order() {
1104
+ return this._order;
1105
+ }
1106
+ /**
1107
+ * 解析 VariableDeclarationJSON 从而生成变量声明节点
1108
+ */
1109
+ fromJSON({ order, ...rest }) {
1110
+ this.updateOrder(order);
1111
+ super.fromJSON(rest);
1112
+ }
1113
+ updateOrder(order = 0) {
1114
+ if (order !== this._order) {
1115
+ this._order = order;
1116
+ this.scope.output.setHasChanges();
1117
+ this.fireChange();
1118
+ }
1119
+ }
1120
+ // 监听类型变化
1121
+ onTypeChange(observer) {
1122
+ return this.subscribe(observer, { selector: (curr) => curr.type });
1123
+ }
1124
+ };
1125
+ VariableDeclaration.kind = "VariableDeclaration" /* VariableDeclaration */;
1126
+
1127
+ // src/ast/declaration/variable-declaration-list.ts
1128
+ var VariableDeclarationList = class extends ASTNode {
1129
+ constructor() {
1130
+ super(...arguments);
1131
+ this.declarationTable = /* @__PURE__ */ new Map();
1132
+ }
1133
+ fromJSON({ declarations, startOrder }) {
1134
+ const removedKeys = new Set(this.declarationTable.keys());
1135
+ const prev = [...this.declarations || []];
1136
+ this.declarations = (declarations || []).map(
1137
+ (declaration, idx) => {
1138
+ const order = (startOrder || 0) + idx;
1139
+ const declarationKey = declaration.key || this.declarations?.[idx]?.key;
1140
+ const existDeclaration = this.declarationTable.get(declarationKey);
1141
+ if (declarationKey) {
1142
+ removedKeys.delete(declarationKey);
1143
+ }
1144
+ if (existDeclaration) {
1145
+ existDeclaration.fromJSON({ order, ...declaration });
1146
+ return existDeclaration;
1147
+ } else {
1148
+ const newDeclaration = this.createChildNode({
1149
+ order,
1150
+ ...declaration,
1151
+ kind: "VariableDeclaration" /* VariableDeclaration */
1152
+ });
1153
+ this.fireChange();
1154
+ this.declarationTable.set(newDeclaration.key, newDeclaration);
1155
+ return newDeclaration;
1156
+ }
1157
+ }
1158
+ );
1159
+ removedKeys.forEach((key) => {
1160
+ const declaration = this.declarationTable.get(key);
1161
+ declaration?.dispose();
1162
+ this.declarationTable.delete(key);
1163
+ });
1164
+ this.dispatchGlobalEvent({
1165
+ type: "VariableListChange",
1166
+ payload: {
1167
+ prev,
1168
+ next: [...this.declarations]
1169
+ }
1170
+ });
1171
+ }
1172
+ toJSON() {
1173
+ return {
1174
+ kind: "VariableDeclarationList" /* VariableDeclarationList */,
1175
+ properties: this.declarations.map((_declaration) => _declaration.toJSON())
1176
+ };
1177
+ }
1178
+ };
1179
+ VariableDeclarationList.kind = "VariableDeclarationList" /* VariableDeclarationList */;
1180
+
1181
+ // src/ast/declaration/property.ts
1182
+ var Property = class extends BaseVariableField {
1183
+ };
1184
+ Property.kind = "Property" /* Property */;
1185
+
1186
+ // src/ast/common/data-node.ts
1187
+ var import_fast_equals6 = require("fast-equals");
1188
+ var DataNode = class extends ASTNode {
1189
+ get data() {
1190
+ return this._data;
1191
+ }
1192
+ fromJSON(json) {
1193
+ const { kind, ...restData } = json;
1194
+ if (!(0, import_fast_equals6.shallowEqual)(restData, this._data)) {
1195
+ this._data = restData;
1196
+ this.fireChange();
1197
+ }
1198
+ }
1199
+ toJSON() {
1200
+ return {
1201
+ kind: "DataNode" /* DataNode */,
1202
+ ...this._data
1203
+ };
1204
+ }
1205
+ partialUpdate(nextData) {
1206
+ if (!(0, import_fast_equals6.shallowEqual)(nextData, this._data)) {
1207
+ this._data = {
1208
+ ...this._data,
1209
+ ...nextData
1210
+ };
1211
+ this.fireChange();
1212
+ }
1213
+ }
1214
+ };
1215
+ DataNode.kind = "DataNode" /* DataNode */;
1216
+
1217
+ // src/ast/common/list-node.ts
1218
+ var ListNode = class extends ASTNode {
1219
+ get list() {
1220
+ return this._list;
1221
+ }
1222
+ fromJSON({ list }) {
1223
+ this._list.slice(list.length).forEach((_item) => {
1224
+ _item.dispose();
1225
+ this.fireChange();
1226
+ });
1227
+ this._list = list.map((_item, idx) => {
1228
+ const prevItem = this._list[idx];
1229
+ if (prevItem.kind !== _item.kind) {
1230
+ prevItem.dispose();
1231
+ this.fireChange();
1232
+ return this.createChildNode(_item);
1233
+ }
1234
+ prevItem.fromJSON(_item);
1235
+ return prevItem;
1236
+ });
1237
+ }
1238
+ toJSON() {
1239
+ return {
1240
+ kind: "ListNode" /* ListNode */,
1241
+ list: this._list.map((item) => item.toJSON())
1242
+ };
1243
+ }
1244
+ };
1245
+ ListNode.kind = "ListNode" /* ListNode */;
1246
+
1247
+ // src/ast/common/map-node.ts
1248
+ var MapNode = class extends ASTNode {
1249
+ constructor() {
1250
+ super(...arguments);
1251
+ this.map = /* @__PURE__ */ new Map();
1252
+ }
1253
+ fromJSON({ map: map4 }) {
1254
+ const removedKeys = new Set(this.map.keys());
1255
+ for (const [key, item] of map4 || []) {
1256
+ removedKeys.delete(key);
1257
+ this.set(key, item);
1258
+ }
1259
+ for (const removeKey of Array.from(removedKeys)) {
1260
+ this.remove(removeKey);
1261
+ }
1262
+ }
1263
+ toJSON() {
1264
+ return {
1265
+ kind: "MapNode" /* MapNode */,
1266
+ map: Array.from(this.map.entries())
1267
+ };
1268
+ }
1269
+ /**
1270
+ * 往 Map 中设置 ASTNode
1271
+ * @param key ASTNode 的索引,
1272
+ * @param json
1273
+ */
1274
+ set(key, nextJSON) {
1275
+ return this.withBatchUpdate(updateChildNodeHelper).call(this, {
1276
+ getChildNode: () => this.get(key),
1277
+ removeChildNode: () => this.map.delete(key),
1278
+ updateChildNode: (nextNode) => this.map.set(key, nextNode),
1279
+ nextJSON
1280
+ });
1281
+ }
1282
+ /**
1283
+ * 移除指定 ASTNode
1284
+ * @param key
1285
+ */
1286
+ remove(key) {
1287
+ this.get(key)?.dispose();
1288
+ this.map.delete(key);
1289
+ this.fireChange();
1290
+ }
1291
+ /**
1292
+ * 获取 ASTNode
1293
+ * @param key
1294
+ * @returns
1295
+ */
1296
+ get(key) {
1297
+ return this.map.get(key);
1298
+ }
1299
+ };
1300
+ MapNode.kind = "MapNode" /* MapNode */;
1301
+
1302
+ // src/ast/ast-registers.ts
1303
+ var ASTRegisters = class {
1304
+ /**
1305
+ * 核心 AST 节点注册
1306
+ */
1307
+ constructor() {
1308
+ this.injectors = /* @__PURE__ */ new Map();
1309
+ this.astMap = /* @__PURE__ */ new Map();
1310
+ this.registerAST(StringType);
1311
+ this.registerAST(NumberType);
1312
+ this.registerAST(BooleanType);
1313
+ this.registerAST(IntegerType);
1314
+ this.registerAST(ObjectType);
1315
+ this.registerAST(ArrayType);
1316
+ this.registerAST(MapType);
1317
+ this.registerAST(Property);
1318
+ this.registerAST(VariableDeclaration);
1319
+ this.registerAST(VariableDeclarationList);
1320
+ this.registerAST(KeyPathExpression);
1321
+ this.registerAST(EnumerateExpression);
1322
+ this.registerAST(ExpressionList);
1323
+ this.registerAST(MapNode);
1324
+ this.registerAST(DataNode);
1325
+ }
1326
+ /**
1327
+ * 创建 AST 节点
1328
+ * @param param 创建参数
1329
+ * @returns
1330
+ */
1331
+ createAST(json, { parent, scope }) {
1332
+ const Registry = this.astMap.get(json.kind);
1333
+ if (!Registry) {
1334
+ throw Error(`ASTKind: ${String(json.kind)} can not find its ASTNode Registry`);
1335
+ }
1336
+ const injector = this.injectors.get(json.kind);
1337
+ const node = new Registry(
1338
+ {
1339
+ key: json.key,
1340
+ scope,
1341
+ parent
1342
+ },
1343
+ injector?.() || {}
1344
+ );
1345
+ node.changeLocked = true;
1346
+ node.fromJSON((0, import_lodash3.omit)(json, ["key", "kind"]));
1347
+ node.changeLocked = false;
1348
+ if (Reflect.hasMetadata(POST_CONSTRUCT_AST_SYMBOL, node)) {
1349
+ const postConstructKey = Reflect.getMetadata(POST_CONSTRUCT_AST_SYMBOL, node);
1350
+ node[postConstructKey]?.();
1351
+ }
1352
+ return node;
1353
+ }
1354
+ /**
1355
+ * 根据 AST 节点类型获取节点 Registry
1356
+ * @param kind
1357
+ * @returns
1358
+ */
1359
+ getASTRegistryByKind(kind) {
1360
+ return this.astMap.get(kind);
1361
+ }
1362
+ /**
1363
+ * 注册 AST 节点
1364
+ * @param ASTNode
1365
+ * @param injector
1366
+ */
1367
+ registerAST(ASTNode2, injector) {
1368
+ this.astMap.set(ASTNode2.kind, ASTNode2);
1369
+ if (injector) {
1370
+ this.injectors.set(ASTNode2.kind, injector);
1371
+ }
1372
+ }
1373
+ };
1374
+ ASTRegisters = __decorateClass([
1375
+ (0, import_inversify2.injectable)()
1376
+ ], ASTRegisters);
1377
+
1378
+ // src/ast/factory.ts
1379
+ var ASTFactory;
1380
+ ((ASTFactory2) => {
1381
+ ASTFactory2.createString = () => ({ kind: "String" /* String */ });
1382
+ ASTFactory2.createNumber = () => ({ kind: "Number" /* Number */ });
1383
+ ASTFactory2.createBoolean = () => ({ kind: "Boolean" /* Boolean */ });
1384
+ ASTFactory2.createInteger = () => ({ kind: "Integer" /* Integer */ });
1385
+ ASTFactory2.createObject = (json) => ({
1386
+ kind: "Object" /* Object */,
1387
+ ...json
1388
+ });
1389
+ ASTFactory2.createArray = (json) => ({
1390
+ kind: "Array" /* Array */,
1391
+ ...json
1392
+ });
1393
+ ASTFactory2.createMap = (json) => ({
1394
+ kind: "Map" /* Map */,
1395
+ ...json
1396
+ });
1397
+ ASTFactory2.createUnion = (json) => ({
1398
+ kind: "Union" /* Union */,
1399
+ ...json
1400
+ });
1401
+ ASTFactory2.createVariableDeclaration = (json) => ({
1402
+ kind: "VariableDeclaration" /* VariableDeclaration */,
1403
+ ...json
1404
+ });
1405
+ ASTFactory2.createProperty = (json) => ({
1406
+ kind: "Property" /* Property */,
1407
+ ...json
1408
+ });
1409
+ ASTFactory2.createVariableDeclarationList = (json) => ({
1410
+ kind: "VariableDeclarationList" /* VariableDeclarationList */,
1411
+ ...json
1412
+ });
1413
+ ASTFactory2.createEnumerateExpression = (json) => ({
1414
+ kind: "EnumerateExpression" /* EnumerateExpression */,
1415
+ ...json
1416
+ });
1417
+ ASTFactory2.createKeyPathExpression = (json) => ({
1418
+ kind: "KeyPathExpression" /* KeyPathExpression */,
1419
+ ...json
1420
+ });
1421
+ })(ASTFactory || (ASTFactory = {}));
1422
+
1423
+ // src/scope/variable-table.ts
1424
+ var import_rxjs3 = require("rxjs");
1425
+ var import_utils5 = require("@flowgram.ai/utils");
1426
+ var import_utils6 = require("@flowgram.ai/utils");
1427
+ var VariableTable = class {
1428
+ constructor(parentTable) {
1429
+ this.parentTable = parentTable;
1430
+ this.table = /* @__PURE__ */ new Map();
1431
+ this.onDataChangeEmitter = new import_utils5.Emitter();
1432
+ this.variables$ = new import_rxjs3.Subject();
1433
+ // 监听变量列表中的单个变量变化
1434
+ this.anyVariableChange$ = this.variables$.pipe(
1435
+ (0, import_rxjs3.switchMap)(
1436
+ (_variables) => (0, import_rxjs3.merge)(
1437
+ ..._variables.map(
1438
+ (_v) => _v.value$.pipe(
1439
+ // 跳过 BehaviorSubject 第一个
1440
+ (0, import_rxjs3.skip)(1)
1441
+ )
1442
+ )
1443
+ )
1444
+ ),
1445
+ (0, import_rxjs3.share)()
1446
+ );
1447
+ this.onDataChange = this.onDataChangeEmitter.event;
1448
+ this._version = 0;
1449
+ }
1450
+ /**
1451
+ * 监听任意变量变化
1452
+ * @param observer 监听器,变量变化时会吐出值
1453
+ * @returns
1454
+ */
1455
+ onAnyVariableChange(observer) {
1456
+ return subsToDisposable(this.anyVariableChange$.subscribe(observer));
1457
+ }
1458
+ /**
1459
+ * 列表或者任意变量变化
1460
+ * @param observer
1461
+ */
1462
+ onAnyChange(observer) {
1463
+ const disposables = new import_utils6.DisposableCollection();
1464
+ disposables.pushAll([this.onDataChange(observer), this.onAnyVariableChange(observer)]);
1465
+ return disposables;
1466
+ }
1467
+ fireChange() {
1468
+ this._version++;
1469
+ this.onDataChangeEmitter.fire();
1470
+ this.parentTable?.fireChange();
1471
+ }
1472
+ get version() {
1473
+ return this._version;
1474
+ }
1475
+ get variables() {
1476
+ return Array.from(this.table.values());
1477
+ }
1478
+ get variableKeys() {
1479
+ return Array.from(this.table.keys());
1480
+ }
1481
+ /**
1482
+ * 根据 keyPath 找到对应的变量,或 Property 节点
1483
+ * @param keyPath
1484
+ * @returns
1485
+ */
1486
+ getByKeyPath(keyPath) {
1487
+ const [variableKey, ...propertyKeys] = keyPath || [];
1488
+ if (!variableKey) {
1489
+ return;
1490
+ }
1491
+ const variable = this.getVariableByKey(variableKey);
1492
+ return propertyKeys.length ? variable?.getByKeyPath(propertyKeys) : variable;
1493
+ }
1494
+ /**
1495
+ * 根据 key 值找到相应的变量
1496
+ * @param key
1497
+ * @returns
1498
+ */
1499
+ getVariableByKey(key) {
1500
+ return this.table.get(key);
1501
+ }
1502
+ /**
1503
+ * 往 variableTable 添加输出变量
1504
+ * @param variable
1505
+ */
1506
+ addVariableToTable(variable) {
1507
+ this.table.set(variable.key, variable);
1508
+ if (this.parentTable) {
1509
+ this.parentTable.addVariableToTable(variable);
1510
+ }
1511
+ this.variables$.next(this.variables);
1512
+ }
1513
+ /**
1514
+ * 从 variableTable 中移除变量
1515
+ * @param key
1516
+ */
1517
+ removeVariableFromTable(key) {
1518
+ this.table.delete(key);
1519
+ if (this.parentTable) {
1520
+ this.parentTable.removeVariableFromTable(key);
1521
+ }
1522
+ this.variables$.next(this.variables);
1523
+ }
1524
+ dispose() {
1525
+ this.variableKeys.forEach((_key) => this.parentTable?.removeVariableFromTable(_key));
1526
+ this.onDataChangeEmitter.dispose();
1527
+ }
1528
+ };
1529
+
1530
+ // src/scope/datas/scope-output-data.ts
1531
+ var ScopeOutputData = class {
1532
+ constructor(scope) {
1533
+ this.scope = scope;
1534
+ this.memo = createMemo();
1535
+ this._hasChanges = false;
1536
+ this.variableTable = new VariableTable(scope.variableEngine.globalVariableTable);
1537
+ this.scope.toDispose.pushAll([
1538
+ // AST 根节点更新时,检查在这次 AST 变化期间节点是否有变化
1539
+ this.scope.ast.subscribe(() => {
1540
+ if (this._hasChanges) {
1541
+ this.memo.clear();
1542
+ this.notifyCoversChange();
1543
+ this.variableTable.fireChange();
1544
+ this._hasChanges = false;
1545
+ }
1546
+ }),
1547
+ this.variableTable
1548
+ ]);
1549
+ }
1550
+ get variableEngine() {
1551
+ return this.scope.variableEngine;
1552
+ }
1553
+ get globalVariableTable() {
1554
+ return this.scope.variableEngine.globalVariableTable;
1555
+ }
1556
+ get onDataChange() {
1557
+ return this.variableTable.onDataChange.bind(this.variableTable);
1558
+ }
1559
+ get onAnyVariableChange() {
1560
+ return this.variableTable.onAnyVariableChange.bind(this.variableTable);
1561
+ }
1562
+ /**
1563
+ * 作用域输出变量
1564
+ */
1565
+ get variables() {
1566
+ return this.memo(
1567
+ "variables",
1568
+ () => this.variableTable.variables.sort((a, b) => a.order - b.order)
1569
+ );
1570
+ }
1571
+ /**
1572
+ * 输出的变量 keys
1573
+ */
1574
+ get variableKeys() {
1575
+ return this.memo("variableKeys", () => this.variableTable.variableKeys);
1576
+ }
1577
+ addVariableToTable(variable) {
1578
+ if (variable.scope !== this.scope) {
1579
+ throw Error("VariableDeclaration must be a ast node in scope");
1580
+ }
1581
+ this.variableTable.addVariableToTable(variable);
1582
+ this._hasChanges = true;
1583
+ }
1584
+ // 标记为发生了变化,用于变量排序变化的场景
1585
+ setHasChanges() {
1586
+ this._hasChanges = true;
1587
+ }
1588
+ removeVariableFromTable(key) {
1589
+ this.variableTable.removeVariableFromTable(key);
1590
+ this._hasChanges = true;
1591
+ }
1592
+ getVariableByKey(key) {
1593
+ return this.variableTable.getVariableByKey(key);
1594
+ }
1595
+ // 通知覆盖作用域更新可用变量
1596
+ notifyCoversChange() {
1597
+ this.scope.coverScopes.forEach((scope) => scope.available.refresh());
1598
+ }
1599
+ };
1600
+
1601
+ // src/scope/datas/scope-available-data.ts
1602
+ var import_rxjs4 = require("rxjs");
1603
+ var import_lodash4 = require("lodash");
1604
+ var import_fast_equals7 = require("fast-equals");
1605
+ var import_utils7 = require("@flowgram.ai/utils");
1606
+ var import_utils8 = require("@flowgram.ai/utils");
1607
+ var ScopeAvailableData = class {
1608
+ constructor(scope) {
1609
+ this.scope = scope;
1610
+ this.memo = createMemo();
1611
+ this.refresh$ = new import_rxjs4.Subject();
1612
+ this._variables = [];
1613
+ /**
1614
+ * 监听
1615
+ */
1616
+ this.variables$ = this.refresh$.pipe(
1617
+ // 输出变量是否 version 发生变化
1618
+ (0, import_rxjs4.map)(() => (0, import_lodash4.flatten)(this.depScopes.map((scope) => scope.output.variables || []))),
1619
+ // 变量列表浅比较
1620
+ (0, import_rxjs4.distinctUntilChanged)(import_fast_equals7.shallowEqual),
1621
+ (0, import_rxjs4.share)()
1622
+ );
1623
+ // 监听变量列表中的单个变量变化
1624
+ this.anyVariableChange$ = this.variables$.pipe(
1625
+ (0, import_rxjs4.switchMap)(
1626
+ (_variables) => (0, import_rxjs4.merge)(
1627
+ ..._variables.map(
1628
+ (_v) => _v.value$.pipe(
1629
+ // 跳过 BehaviorSubject 第一个
1630
+ (0, import_rxjs4.skip)(1)
1631
+ )
1632
+ )
1633
+ )
1634
+ ),
1635
+ (0, import_rxjs4.share)()
1636
+ );
1637
+ this.onDataChangeEmitter = new import_utils8.Emitter();
1638
+ /**
1639
+ * 监听变量列表变化 + 任意子变量变化
1640
+ */
1641
+ this.onDataChange = this.onDataChangeEmitter.event;
1642
+ this.scope.toDispose.pushAll([
1643
+ this.onVariableListChange((_variables) => {
1644
+ this._variables = _variables;
1645
+ this.memo.clear();
1646
+ this.onDataChangeEmitter.fire(this._variables);
1647
+ }),
1648
+ this.onAnyVariableChange(() => {
1649
+ this.onDataChangeEmitter.fire(this._variables);
1650
+ }),
1651
+ import_utils7.Disposable.create(() => {
1652
+ this.refresh$.complete();
1653
+ this.refresh$.unsubscribe();
1654
+ })
1655
+ ]);
1656
+ }
1657
+ get globalVariableTable() {
1658
+ return this.scope.variableEngine.globalVariableTable;
1659
+ }
1660
+ // 刷新可访问变量列表
1661
+ refresh() {
1662
+ if (this.scope.disposed) {
1663
+ return;
1664
+ }
1665
+ this.refresh$.next();
1666
+ }
1667
+ /**
1668
+ * 监听任意变量变化
1669
+ * @param observer 监听器,变量变化时会吐出值
1670
+ * @returns
1671
+ */
1672
+ onAnyVariableChange(observer) {
1673
+ return subsToDisposable(this.anyVariableChange$.subscribe(observer));
1674
+ }
1675
+ /**
1676
+ * 监听变量列表变化
1677
+ * @param observer
1678
+ * @returns
1679
+ */
1680
+ onVariableListChange(observer) {
1681
+ return subsToDisposable(this.variables$.subscribe(observer));
1682
+ }
1683
+ /**
1684
+ * 获取可消费变量
1685
+ */
1686
+ get variables() {
1687
+ return this._variables;
1688
+ }
1689
+ /**
1690
+ * 获取可访问的变量 keys
1691
+ */
1692
+ get variableKeys() {
1693
+ return this.memo("availableKeys", () => this._variables.map((_v) => _v.key));
1694
+ }
1695
+ /**
1696
+ * 返回依赖的作用域
1697
+ */
1698
+ get depScopes() {
1699
+ return this.scope.depScopes;
1700
+ }
1701
+ /**
1702
+ * 通过 keyPath 找到可用变量
1703
+ * @param keyPath
1704
+ * @returns
1705
+ */
1706
+ getByKeyPath(keyPath = []) {
1707
+ if (!this.variableKeys.includes(keyPath[0])) {
1708
+ return;
1709
+ }
1710
+ return this.globalVariableTable.getByKeyPath(keyPath);
1711
+ }
1712
+ };
1713
+
1714
+ // src/scope/datas/scope-event-data.ts
1715
+ var import_rxjs5 = require("rxjs");
1716
+ var ScopeEventData = class {
1717
+ constructor(scope) {
1718
+ this.scope = scope;
1719
+ this.event$ = new import_rxjs5.Subject();
1720
+ scope.toDispose.pushAll([
1721
+ this.subscribe((_action) => {
1722
+ scope.variableEngine.fireGlobalEvent(_action);
1723
+ })
1724
+ ]);
1725
+ }
1726
+ dispatch(action) {
1727
+ if (this.scope.disposed) {
1728
+ return;
1729
+ }
1730
+ this.event$.next(action);
1731
+ }
1732
+ subscribe(observer) {
1733
+ return subsToDisposable(this.event$.subscribe(observer));
1734
+ }
1735
+ on(type, observer) {
1736
+ return subsToDisposable(
1737
+ this.event$.pipe((0, import_rxjs5.filter)((_action) => _action.type === type)).subscribe(observer)
1738
+ );
1739
+ }
1740
+ };
1741
+
1742
+ // src/scope/scope.ts
1743
+ var Scope = class {
1744
+ constructor(options) {
1745
+ /**
1746
+ * 数据缓存
1747
+ */
1748
+ this.memo = createMemo();
1749
+ this.toDispose = new import_utils9.DisposableCollection();
1750
+ this.onDispose = this.toDispose.onDispose;
1751
+ this.id = options.id;
1752
+ this.meta = options.meta || {};
1753
+ this.variableEngine = options.variableEngine;
1754
+ this.event = new ScopeEventData(this);
1755
+ this.ast = this.variableEngine.astRegisters.createAST(
1756
+ {
1757
+ kind: "MapNode" /* MapNode */,
1758
+ key: this.id
1759
+ },
1760
+ {
1761
+ scope: this
1762
+ }
1763
+ );
1764
+ this.output = new ScopeOutputData(this);
1765
+ this.available = new ScopeAvailableData(this);
1766
+ }
1767
+ refreshCovers() {
1768
+ this.memo.clear("covers");
1769
+ }
1770
+ refreshDeps() {
1771
+ this.memo.clear("deps");
1772
+ this.available.refresh();
1773
+ }
1774
+ get depScopes() {
1775
+ return this.memo(
1776
+ "deps",
1777
+ () => this.variableEngine.chain.getDeps(this).filter((_scope) => Boolean(_scope) && !_scope?.disposed)
1778
+ );
1779
+ }
1780
+ get coverScopes() {
1781
+ return this.memo(
1782
+ "covers",
1783
+ () => this.variableEngine.chain.getCovers(this).filter((_scope) => Boolean(_scope) && !_scope?.disposed)
1784
+ );
1785
+ }
1786
+ dispose() {
1787
+ this.ast.dispose();
1788
+ this.toDispose.dispose();
1789
+ this.coverScopes.forEach((_scope) => _scope.refreshDeps());
1790
+ this.depScopes.forEach((_scope) => _scope.refreshCovers());
1791
+ }
1792
+ get disposed() {
1793
+ return this.toDispose.disposed;
1794
+ }
1795
+ };
1796
+
1797
+ // src/variable-engine.ts
1798
+ var VariableEngine = class {
1799
+ constructor(chain, astRegisters) {
1800
+ this.chain = chain;
1801
+ this.astRegisters = astRegisters;
1802
+ this.toDispose = new import_utils10.DisposableCollection();
1803
+ this.memo = createMemo();
1804
+ this.scopeMap = /* @__PURE__ */ new Map();
1805
+ this.globalEvent$ = new import_rxjs6.Subject();
1806
+ this.onScopeChangeEmitter = new import_utils11.Emitter();
1807
+ this.globalVariableTable = new VariableTable();
1808
+ this.onScopeChange = this.onScopeChangeEmitter.event;
1809
+ this.toDispose.pushAll([
1810
+ chain,
1811
+ import_utils10.Disposable.create(() => {
1812
+ this.getAllScopes().forEach((scope) => scope.dispose());
1813
+ this.globalVariableTable.dispose();
1814
+ })
1815
+ ]);
1816
+ }
1817
+ get container() {
1818
+ return this.containerProvider();
1819
+ }
1820
+ dispose() {
1821
+ this.toDispose.dispose();
1822
+ }
1823
+ // 根据 scopeId 找到作用域
1824
+ getScopeById(scopeId) {
1825
+ return this.scopeMap.get(scopeId);
1826
+ }
1827
+ // 移除作用域
1828
+ removeScopeById(scopeId) {
1829
+ this.getScopeById(scopeId)?.dispose();
1830
+ }
1831
+ // 获取 Scope,如果 Scope 存在且类型相同,则会直接使用
1832
+ createScope(id, meta) {
1833
+ let scope = this.getScopeById(id);
1834
+ if (!scope) {
1835
+ scope = new Scope({ variableEngine: this, meta, id });
1836
+ this.scopeMap.set(id, scope);
1837
+ this.onScopeChangeEmitter.fire({ type: "add", scope });
1838
+ scope.toDispose.pushAll([
1839
+ scope.ast.subscribe(() => {
1840
+ this.onScopeChangeEmitter.fire({ type: "update", scope });
1841
+ }),
1842
+ // 可用变量发生变化
1843
+ scope.available.onDataChange(() => {
1844
+ this.onScopeChangeEmitter.fire({ type: "available", scope });
1845
+ })
1846
+ ]);
1847
+ scope.onDispose(() => {
1848
+ this.scopeMap.delete(id);
1849
+ this.onScopeChangeEmitter.fire({ type: "delete", scope });
1850
+ });
1851
+ }
1852
+ return scope;
1853
+ }
1854
+ // 获取系统中所有的作用域
1855
+ getAllScopes({
1856
+ sort
1857
+ } = {}) {
1858
+ const allScopes = Array.from(this.scopeMap.values());
1859
+ if (sort) {
1860
+ const sortScopes = this.chain.sortAll();
1861
+ const remainScopes = new Set(allScopes);
1862
+ sortScopes.forEach((_scope) => remainScopes.delete(_scope));
1863
+ return [...sortScopes, ...Array.from(remainScopes)];
1864
+ }
1865
+ return [...allScopes];
1866
+ }
1867
+ fireGlobalEvent(event) {
1868
+ this.globalEvent$.next(event);
1869
+ }
1870
+ onGlobalEvent(type, observer) {
1871
+ return subsToDisposable(
1872
+ this.globalEvent$.subscribe((_action) => {
1873
+ if (_action.type === type) {
1874
+ observer(_action);
1875
+ }
1876
+ })
1877
+ );
1878
+ }
1879
+ };
1880
+ __decorateClass([
1881
+ (0, import_inversify5.inject)(ContainerProvider)
1882
+ ], VariableEngine.prototype, "containerProvider", 2);
1883
+ __decorateClass([
1884
+ (0, import_inversify5.preDestroy)()
1885
+ ], VariableEngine.prototype, "dispose", 1);
1886
+ VariableEngine = __decorateClass([
1887
+ (0, import_inversify5.injectable)(),
1888
+ __decorateParam(0, (0, import_inversify5.inject)(ScopeChain)),
1889
+ __decorateParam(1, (0, import_inversify5.inject)(ASTRegisters))
1890
+ ], VariableEngine);
1891
+
1892
+ // src/services/variable-field-key-rename-service.ts
1893
+ var import_lodash5 = require("lodash");
1894
+ var import_inversify6 = require("inversify");
1895
+ var import_utils12 = require("@flowgram.ai/utils");
1896
+ var VariableFieldKeyRenameService = class {
1897
+ constructor() {
1898
+ this.toDispose = new import_utils12.DisposableCollection();
1899
+ this.renameEmitter = new import_utils12.Emitter();
1900
+ // 没有被 rename 的字段通过 disposeInList 透出,让业务区分变量是 rename 删除的,还是真正从列表中删除的
1901
+ this.disposeInListEmitter = new import_utils12.Emitter();
1902
+ this.onRename = this.renameEmitter.event;
1903
+ this.onDisposeInList = this.disposeInListEmitter.event;
1904
+ }
1905
+ handleFieldListChange(ast, prev, next) {
1906
+ if (!ast || !prev?.length || !next?.length) {
1907
+ this.notifyFieldsDispose(prev, next);
1908
+ return;
1909
+ }
1910
+ if (prev.length !== next.length) {
1911
+ this.notifyFieldsDispose(prev, next);
1912
+ return;
1913
+ }
1914
+ let renameNodeInfo = null;
1915
+ let existFieldChanged = false;
1916
+ for (const [index, prevField] of prev.entries()) {
1917
+ const nextField = next[index];
1918
+ if (prevField.key !== nextField.key) {
1919
+ if (existFieldChanged) {
1920
+ this.notifyFieldsDispose(prev, next);
1921
+ return;
1922
+ }
1923
+ existFieldChanged = true;
1924
+ if (prevField.type?.kind === nextField.type?.kind) {
1925
+ renameNodeInfo = { before: prevField, after: nextField };
1926
+ }
1927
+ }
1928
+ }
1929
+ if (!renameNodeInfo) {
1930
+ this.notifyFieldsDispose(prev, next);
1931
+ return;
1932
+ }
1933
+ this.renameEmitter.fire(renameNodeInfo);
1934
+ }
1935
+ notifyFieldsDispose(prev, next) {
1936
+ const removedFields = (0, import_lodash5.difference)(prev || [], next || []);
1937
+ removedFields.forEach((_field) => this.disposeInListEmitter.fire(_field));
1938
+ }
1939
+ init() {
1940
+ this.toDispose.pushAll([
1941
+ this.variableEngine.onGlobalEvent(
1942
+ "VariableListChange",
1943
+ (_action) => {
1944
+ this.handleFieldListChange(_action.ast, _action.payload?.prev, _action.payload?.next);
1945
+ }
1946
+ ),
1947
+ this.variableEngine.onGlobalEvent(
1948
+ "ObjectPropertiesChange",
1949
+ (_action) => {
1950
+ this.handleFieldListChange(_action.ast, _action.payload?.prev, _action.payload?.next);
1951
+ }
1952
+ )
1953
+ ]);
1954
+ }
1955
+ dispose() {
1956
+ this.toDispose.dispose();
1957
+ }
1958
+ };
1959
+ __decorateClass([
1960
+ (0, import_inversify6.inject)(VariableEngine)
1961
+ ], VariableFieldKeyRenameService.prototype, "variableEngine", 2);
1962
+ __decorateClass([
1963
+ (0, import_inversify6.postConstruct)()
1964
+ ], VariableFieldKeyRenameService.prototype, "init", 1);
1965
+ __decorateClass([
1966
+ (0, import_inversify6.preDestroy)()
1967
+ ], VariableFieldKeyRenameService.prototype, "dispose", 1);
1968
+ VariableFieldKeyRenameService = __decorateClass([
1969
+ (0, import_inversify6.injectable)()
1970
+ ], VariableFieldKeyRenameService);
1971
+
1972
+ // src/variable-container-module.ts
1973
+ var VariableContainerModule = new import_inversify7.ContainerModule((bind) => {
1974
+ bind(VariableEngine).toSelf().inSingletonScope();
1975
+ bind(ASTRegisters).toSelf().inSingletonScope();
1976
+ bind(VariableFieldKeyRenameService).toSelf().inSingletonScope();
1977
+ bind(VariableEngineProvider).toDynamicValue((ctx) => () => ctx.container.get(VariableEngine));
1978
+ bind(ContainerProvider).toDynamicValue((ctx) => () => ctx.container);
1979
+ });
1980
+
1981
+ // src/react/context.tsx
1982
+ var import_react = require("react");
1983
+ var ScopeContext = (0, import_react.createContext)(null);
1984
+ var ScopeProvider = ScopeContext.Provider;
1985
+ var useScopeContext = () => (0, import_react.useContext)(ScopeContext);
1986
+ var useCurrentScope = () => (0, import_react.useContext)(ScopeContext)?.scope;
1987
+
1988
+ // src/react/hooks/useScopeAvailable.ts
1989
+ var import_react2 = require("react");
1990
+ var import_core = require("@flowgram.ai/core");
1991
+ function useScopeAvailable() {
1992
+ const scope = useCurrentScope();
1993
+ const refresh = (0, import_core.useRefresh)();
1994
+ (0, import_react2.useEffect)(() => {
1995
+ const disposable = scope.available.onDataChange(() => {
1996
+ refresh();
1997
+ });
1998
+ return () => disposable.dispose();
1999
+ }, []);
2000
+ return scope.available;
2001
+ }
2002
+
2003
+ // src/react/hooks/useAvailableVariables.ts
2004
+ var import_react3 = require("react");
2005
+ var import_core2 = require("@flowgram.ai/core");
2006
+ function useAvailableVariables() {
2007
+ const scope = useCurrentScope();
2008
+ const variableEngine = (0, import_core2.useService)(VariableEngine);
2009
+ const refresh = (0, import_core2.useRefresh)();
2010
+ (0, import_react3.useEffect)(() => {
2011
+ if (!scope) {
2012
+ const disposable2 = variableEngine.globalVariableTable.onAnyChange(() => {
2013
+ refresh();
2014
+ });
2015
+ return () => disposable2.dispose();
2016
+ }
2017
+ const disposable = scope.available.onDataChange(() => {
2018
+ refresh();
2019
+ });
2020
+ return () => disposable.dispose();
2021
+ }, []);
2022
+ return scope ? scope.available.variables : variableEngine.globalVariableTable.variables;
2023
+ }
2024
+ // Annotate the CommonJS export names for ESM import in node:
2025
+ 0 && (module.exports = {
2026
+ ASTFactory,
2027
+ ASTKind,
2028
+ ASTNode,
2029
+ ASTNodeFlags,
2030
+ ASTRegisters,
2031
+ ArrayType,
2032
+ BaseExpression,
2033
+ BaseType,
2034
+ BaseVariableField,
2035
+ BooleanType,
2036
+ DataNode,
2037
+ EnumerateExpression,
2038
+ ExpressionList,
2039
+ IntegerType,
2040
+ KeyPathExpression,
2041
+ KeyPathExpressionV2,
2042
+ ListNode,
2043
+ MapNode,
2044
+ MapType,
2045
+ NumberType,
2046
+ ObjectType,
2047
+ Property,
2048
+ Scope,
2049
+ ScopeChain,
2050
+ ScopeOutputData,
2051
+ ScopeProvider,
2052
+ StringType,
2053
+ VariableContainerModule,
2054
+ VariableDeclaration,
2055
+ VariableDeclarationList,
2056
+ VariableEngine,
2057
+ VariableEngineProvider,
2058
+ VariableFieldKeyRenameService,
2059
+ VariableTable,
2060
+ injectToAST,
2061
+ postConstructAST,
2062
+ useAvailableVariables,
2063
+ useCurrentScope,
2064
+ useScopeAvailable,
2065
+ useScopeContext
2066
+ });
2067
+ //# sourceMappingURL=index.js.map