@schemx/vue 0.1.21 → 0.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +12 -12
  2. package/dist/components/FormGroup/index.d.ts +1 -1
  3. package/dist/components/FormItem/index.d.ts +1 -1
  4. package/dist/components/FormItem/index.d.ts.map +1 -1
  5. package/dist/hocs/index.d.ts +0 -1
  6. package/dist/hocs/index.d.ts.map +1 -1
  7. package/dist/hocs/withRemoteOptions.d.ts +3 -3
  8. package/dist/hocs/withRemoteOptions.d.ts.map +1 -1
  9. package/dist/hooks/index.d.ts +5 -7
  10. package/dist/hooks/index.d.ts.map +1 -1
  11. package/dist/hooks/useContext.d.ts +15 -3
  12. package/dist/hooks/useContext.d.ts.map +1 -1
  13. package/dist/hooks/useDictionary.d.ts +11 -4
  14. package/dist/hooks/useDictionary.d.ts.map +1 -1
  15. package/dist/hooks/useEffect.d.ts +1 -1
  16. package/dist/hooks/useField.d.ts +32 -1
  17. package/dist/hooks/useField.d.ts.map +1 -1
  18. package/dist/hooks/useForm.d.ts +4 -4
  19. package/dist/hooks/useForm.d.ts.map +1 -1
  20. package/dist/hooks/useViewSchemas.d.ts +1 -1
  21. package/dist/hooks/useWatch.d.ts +1 -1
  22. package/dist/index.cjs +6 -1
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.ts +4 -2
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.mjs +2591 -1081
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/types/dictionary.d.ts +150 -0
  29. package/dist/types/dictionary.d.ts.map +1 -0
  30. package/dist/types/field.d.ts +1 -1
  31. package/dist/types/form.d.ts +1 -1
  32. package/dist/types/index.d.ts +1 -0
  33. package/dist/types/index.d.ts.map +1 -1
  34. package/dist/utils/dynamic.d.ts +1 -1
  35. package/dist/utils/helpers.d.ts +1 -1
  36. package/dist/utils/rendererProvider.d.ts +1 -1
  37. package/dist/utils/rulesProvider.d.ts +1 -1
  38. package/dist/utils/validation.d.ts +1 -1
  39. package/package.json +2 -2
  40. package/dist/hooks/useFieldContext.d.ts +0 -23
  41. package/dist/hooks/useFieldContext.d.ts.map +0 -1
  42. package/dist/index.umd.js +0 -2
  43. package/dist/index.umd.js.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,10 +1,114 @@
1
1
  import "./style.css";
2
- import { computed, provide, onUnmounted, inject, shallowRef, ref, onMounted, watchEffect, onScopeDispose, defineComponent, createVNode, toRef, h as h$1, createTextVNode, watch, openBlock, createElementBlock, normalizeClass, Fragment, renderList, unref, createBlock, createSlots, withCtx, renderSlot, mergeProps } from "vue";
3
- import classnames from "classnames";
4
- import { omit } from "es-toolkit";
5
2
  var __defProp = Object.defineProperty;
6
3
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
4
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ import { computed, provide, onUnmounted, inject, shallowRef, ref, onMounted, watchEffect, onScopeDispose, defineComponent, createVNode, toRef, h as h$1, createTextVNode, watch, openBlock, createElementBlock, normalizeClass, Fragment, renderList, unref, createBlock, createSlots, withCtx, renderSlot, mergeProps } from "vue";
6
+ function _mergeNamespaces(n2, m2) {
7
+ for (var i2 = 0; i2 < m2.length; i2++) {
8
+ const e2 = m2[i2];
9
+ if (typeof e2 !== "string" && !Array.isArray(e2)) {
10
+ for (const k in e2) {
11
+ if (k !== "default" && !(k in n2)) {
12
+ const d2 = Object.getOwnPropertyDescriptor(e2, k);
13
+ if (d2) {
14
+ Object.defineProperty(n2, k, d2.get ? d2 : {
15
+ enumerable: true,
16
+ get: () => e2[k]
17
+ });
18
+ }
19
+ }
20
+ }
21
+ }
22
+ }
23
+ return Object.freeze(Object.defineProperty(n2, Symbol.toStringTag, { value: "Module" }));
24
+ }
25
+ var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
26
+ function getDefaultExportFromCjs(x2) {
27
+ return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
28
+ }
29
+ function getAugmentedNamespace(n2) {
30
+ if (n2.__esModule) return n2;
31
+ var f = n2.default;
32
+ if (typeof f == "function") {
33
+ var a2 = function a3() {
34
+ if (this instanceof a3) {
35
+ return Reflect.construct(f, arguments, this.constructor);
36
+ }
37
+ return f.apply(this, arguments);
38
+ };
39
+ a2.prototype = f.prototype;
40
+ } else a2 = {};
41
+ Object.defineProperty(a2, "__esModule", { value: true });
42
+ Object.keys(n2).forEach(function(k) {
43
+ var d2 = Object.getOwnPropertyDescriptor(n2, k);
44
+ Object.defineProperty(a2, k, d2.get ? d2 : {
45
+ enumerable: true,
46
+ get: function() {
47
+ return n2[k];
48
+ }
49
+ });
50
+ });
51
+ return a2;
52
+ }
53
+ var classnames$1 = { exports: {} };
54
+ /*!
55
+ Copyright (c) 2018 Jed Watson.
56
+ Licensed under the MIT License (MIT), see
57
+ http://jedwatson.github.io/classnames
58
+ */
59
+ (function(module) {
60
+ (function() {
61
+ var hasOwn = {}.hasOwnProperty;
62
+ function classNames() {
63
+ var classes = "";
64
+ for (var i2 = 0; i2 < arguments.length; i2++) {
65
+ var arg = arguments[i2];
66
+ if (arg) {
67
+ classes = appendClass(classes, parseValue(arg));
68
+ }
69
+ }
70
+ return classes;
71
+ }
72
+ function parseValue(arg) {
73
+ if (typeof arg === "string" || typeof arg === "number") {
74
+ return arg;
75
+ }
76
+ if (typeof arg !== "object") {
77
+ return "";
78
+ }
79
+ if (Array.isArray(arg)) {
80
+ return classNames.apply(null, arg);
81
+ }
82
+ if (arg.toString !== Object.prototype.toString && !arg.toString.toString().includes("[native code]")) {
83
+ return arg.toString();
84
+ }
85
+ var classes = "";
86
+ for (var key in arg) {
87
+ if (hasOwn.call(arg, key) && arg[key]) {
88
+ classes = appendClass(classes, key);
89
+ }
90
+ }
91
+ return classes;
92
+ }
93
+ function appendClass(value, newClass) {
94
+ if (!newClass) {
95
+ return value;
96
+ }
97
+ if (value) {
98
+ return value + " " + newClass;
99
+ }
100
+ return value + newClass;
101
+ }
102
+ if (module.exports) {
103
+ classNames.default = classNames;
104
+ module.exports = classNames;
105
+ } else {
106
+ window.classNames = classNames;
107
+ }
108
+ })();
109
+ })(classnames$1);
110
+ var classnamesExports = classnames$1.exports;
111
+ const classnames = /* @__PURE__ */ getDefaultExportFromCjs(classnamesExports);
8
112
  var i = Symbol.for("preact-signals");
9
113
  function t() {
10
114
  if (!(s > 1)) {
@@ -136,13 +240,10 @@ l.prototype.U = function(i2) {
136
240
  l.prototype.subscribe = function(i2) {
137
241
  var t2 = this;
138
242
  return j(function() {
139
- var n2 = t2.value, o2 = r;
140
- r = void 0;
141
- try {
142
- i2(n2);
143
- } finally {
144
- r = o2;
145
- }
243
+ var n2 = t2.value;
244
+ o(function() {
245
+ return i2(n2);
246
+ });
146
247
  }, { name: "sub" });
147
248
  };
148
249
  l.prototype.valueOf = function() {
@@ -221,14 +322,11 @@ function b(i2) {
221
322
  i2.s = n2;
222
323
  }
223
324
  function p(i2, t2) {
224
- l.call(this, void 0);
325
+ l.call(this, void 0, t2);
225
326
  this.x = i2;
226
327
  this.s = void 0;
227
328
  this.g = d - 1;
228
329
  this.f = 4;
229
- this.W = null == t2 ? void 0 : t2.watched;
230
- this.Z = null == t2 ? void 0 : t2.unwatched;
231
- this.name = null == t2 ? void 0 : t2.name;
232
330
  }
233
331
  p.prototype = new l();
234
332
  p.prototype.h = function() {
@@ -293,6 +391,9 @@ Object.defineProperty(p.prototype, "value", { get: function() {
293
391
  if (16 & this.f) throw this.v;
294
392
  return this.v;
295
393
  } });
394
+ function g(i2, t2) {
395
+ return new p(i2, t2);
396
+ }
296
397
  function S(i2) {
297
398
  var n2 = i2.m;
298
399
  i2.m = void 0;
@@ -631,6 +732,14 @@ function isPlainObject(value) {
631
732
  function isUnsafeProperty(key) {
632
733
  return key === "__proto__";
633
734
  }
735
+ function omit(obj, keys) {
736
+ const result = { ...obj };
737
+ for (let i2 = 0; i2 < keys.length; i2++) {
738
+ const key = keys[i2];
739
+ delete result[key];
740
+ }
741
+ return result;
742
+ }
634
743
  function pick(obj, keys) {
635
744
  const result = {};
636
745
  for (let i2 = 0; i2 < keys.length; i2++) {
@@ -954,33 +1063,59 @@ function defaultNormalizeFieldKey(key) {
954
1063
  }
955
1064
  return String(key);
956
1065
  }
957
- function createSignalEffect(fn) {
958
- return j(fn);
1066
+ function createSignalEffect(fn, options = {}) {
1067
+ if (!options.once) {
1068
+ return j(fn);
1069
+ }
1070
+ const disposeRef = {};
1071
+ disposeRef.current = j(() => {
1072
+ var _a;
1073
+ fn();
1074
+ (_a = disposeRef.current) == null ? void 0 : _a.call(disposeRef);
1075
+ });
1076
+ return () => {
1077
+ var _a;
1078
+ return (_a = disposeRef.current) == null ? void 0 : _a.call(disposeRef);
1079
+ };
959
1080
  }
960
1081
  function createDebouncedSignalEffect(collect, run, wait = 16, options = {}) {
961
- const debouncedRun = debounce(run, wait, { edges: options.edges });
962
1082
  let initialized = false;
1083
+ const wrappedRun = (value) => {
1084
+ run(value);
1085
+ if (options.once) {
1086
+ teardown();
1087
+ }
1088
+ };
1089
+ const debouncedRun = debounce(wrappedRun, wait, { edges: options.edges });
963
1090
  const disposeEffect = createSignalEffect(() => {
964
1091
  const value = collect();
965
1092
  if (!initialized && options.immediate) {
966
1093
  initialized = true;
967
- run(value);
1094
+ wrappedRun(value);
968
1095
  return;
969
1096
  }
970
1097
  initialized = true;
971
1098
  debouncedRun(value);
972
1099
  });
973
- return () => {
1100
+ const teardown = () => {
974
1101
  disposeEffect();
975
1102
  debouncedRun.cancel();
976
1103
  };
1104
+ return teardown;
977
1105
  }
978
1106
  function batchUpdates(fn) {
979
1107
  n(fn);
980
1108
  }
981
1109
  class SignalMapImpl {
982
1110
  constructor() {
1111
+ /** 每个 key 独占一个 signal,保证字段级更新能细粒度触发 */
983
1112
  __publicField(this, "signals", /* @__PURE__ */ new Map());
1113
+ /**
1114
+ * 结构版本 signal,用于追踪“新 key 创建”事件。
1115
+ *
1116
+ * effect 读取缺失 key 时会依赖这个版本;之后创建该 key 会推进版本,
1117
+ * 让 effect 重新执行并订阅新 key 对应的 signal。
1118
+ */
984
1119
  __publicField(this, "version", createSignal(0));
985
1120
  }
986
1121
  /**
@@ -1095,6 +1230,9 @@ class SignalMapImpl {
1095
1230
  function createSignalMap() {
1096
1231
  return new SignalMapImpl();
1097
1232
  }
1233
+ function createComputed(compute, options) {
1234
+ return g(compute, options);
1235
+ }
1098
1236
  function isBaseSchema(schema) {
1099
1237
  return !isGroupSchema(schema) && !isDependencySchema(schema);
1100
1238
  }
@@ -1131,7 +1269,8 @@ function getGroupFieldMissing(schema) {
1131
1269
  function getDependencyFieldMissing(schema) {
1132
1270
  const missing = [];
1133
1271
  if (!isLegalComponentType(schema)) missing.push("componentType");
1134
- if (!Object.hasOwn(schema, "to") || !Array.isArray(schema.to)) missing.push("to");
1272
+ if (!Object.hasOwn(schema, "to") || !Array.isArray(schema.to) || schema.to.length === 0)
1273
+ missing.push("to");
1135
1274
  if (typeof schema.renderer !== "function") missing.push("renderer");
1136
1275
  return missing;
1137
1276
  }
@@ -1142,6 +1281,7 @@ function buildWarnMessage(index, schema, missing) {
1142
1281
  function normalizeSchemas(schemas) {
1143
1282
  const result = [];
1144
1283
  const missings = [];
1284
+ let changed = false;
1145
1285
  for (let i2 = 0; i2 < schemas.length; i2++) {
1146
1286
  const schema = schemas[i2];
1147
1287
  let missing = [];
@@ -1149,16 +1289,21 @@ function normalizeSchemas(schemas) {
1149
1289
  missing = getGroupFieldMissing(schema);
1150
1290
  if (missing.length > 0) {
1151
1291
  missings.push(buildWarnMessage(i2, schema, missing));
1292
+ changed = true;
1152
1293
  continue;
1153
1294
  }
1154
- result.push({
1155
- ...schema,
1156
- children: normalizeSchemas(schema.children)
1157
- });
1295
+ const normalizedChildren = normalizeSchemas(schema.children);
1296
+ if (normalizedChildren === schema.children) {
1297
+ result.push(schema);
1298
+ } else {
1299
+ result.push({ ...schema, children: normalizedChildren });
1300
+ changed = true;
1301
+ }
1158
1302
  } else if (isDependencySchema(schema)) {
1159
1303
  missing = getDependencyFieldMissing(schema);
1160
1304
  if (missing.length > 0) {
1161
1305
  missings.push(buildWarnMessage(i2, schema, missing));
1306
+ changed = true;
1162
1307
  continue;
1163
1308
  }
1164
1309
  result.push(schema);
@@ -1166,13 +1311,16 @@ function normalizeSchemas(schemas) {
1166
1311
  missing = getBaseFieldMissing(schema);
1167
1312
  if (missing.length > 0) {
1168
1313
  missings.push(buildWarnMessage(i2, schema, missing));
1314
+ changed = true;
1169
1315
  continue;
1170
1316
  }
1171
1317
  result.push(schema);
1318
+ } else {
1319
+ changed = true;
1172
1320
  }
1173
1321
  }
1174
1322
  if (missings.length) console.warn(missings.join("\n"));
1175
- return result;
1323
+ return changed ? result : schemas;
1176
1324
  }
1177
1325
  function toString(value) {
1178
1326
  if (value == null) return "";
@@ -1456,7 +1604,9 @@ const defaultConfig = {
1456
1604
  const defaultConfigKey = Object.keys(defaultConfig);
1457
1605
  class ValidatorImpl {
1458
1606
  constructor() {
1607
+ /** 校验规则映射表:字段路径 → 规则条目 */
1459
1608
  __publicField(this, "rules", /* @__PURE__ */ new Map());
1609
+ /** 校验错误映射表:字段路径 → 错误信息数组(响应式) */
1460
1610
  __publicField(this, "errors", createSignalMap());
1461
1611
  }
1462
1612
  /**
@@ -1746,7 +1896,9 @@ class RendererRegistry {
1746
1896
  * @param defaultType - 默认渲染器类型,未找到指定类型时回退使用
1747
1897
  */
1748
1898
  constructor(defaultType) {
1899
+ /** 渲染器存储 */
1749
1900
  __publicField(this, "renderers");
1901
+ /** 默认渲染器类型 */
1750
1902
  __publicField(this, "defaultType");
1751
1903
  this.renderers = /* @__PURE__ */ new Map();
1752
1904
  this.defaultType = defaultType;
@@ -1949,6 +2101,7 @@ class ValidatorsRegistry {
1949
2101
  * 创建空的规则注册中心。
1950
2102
  */
1951
2103
  constructor() {
2104
+ /** Validators 存储 */
1952
2105
  __publicField(this, "validators");
1953
2106
  this.validators = /* @__PURE__ */ new Map();
1954
2107
  }
@@ -2134,277 +2287,1427 @@ class ValidatorsRegistry {
2134
2287
  function createValidatorsRegistry() {
2135
2288
  return new ValidatorsRegistry();
2136
2289
  }
2137
- function createSchemas(schemas = []) {
2138
- const source = createSignal(schemas);
2139
- const getValue = () => {
2140
- return source.value;
2141
- };
2142
- const peek = () => {
2143
- return source.peek();
2290
+ var build = {};
2291
+ var extendStatics = function(d2, b2) {
2292
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b3) {
2293
+ d3.__proto__ = b3;
2294
+ } || function(d3, b3) {
2295
+ for (var p2 in b3) if (Object.prototype.hasOwnProperty.call(b3, p2)) d3[p2] = b3[p2];
2144
2296
  };
2145
- const set2 = (nextSchemas) => {
2146
- source.value = nextSchemas;
2297
+ return extendStatics(d2, b2);
2298
+ };
2299
+ function __extends(d2, b2) {
2300
+ if (typeof b2 !== "function" && b2 !== null)
2301
+ throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
2302
+ extendStatics(d2, b2);
2303
+ function __() {
2304
+ this.constructor = d2;
2305
+ }
2306
+ d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
2307
+ }
2308
+ var __assign = function() {
2309
+ __assign = Object.assign || function __assign2(t2) {
2310
+ for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
2311
+ s2 = arguments[i2];
2312
+ for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2)) t2[p2] = s2[p2];
2313
+ }
2314
+ return t2;
2147
2315
  };
2148
- const update = (updater) => {
2149
- source.value = updater(source.peek());
2316
+ return __assign.apply(this, arguments);
2317
+ };
2318
+ function __rest(s2, e2) {
2319
+ var t2 = {};
2320
+ for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2) && e2.indexOf(p2) < 0)
2321
+ t2[p2] = s2[p2];
2322
+ if (s2 != null && typeof Object.getOwnPropertySymbols === "function")
2323
+ for (var i2 = 0, p2 = Object.getOwnPropertySymbols(s2); i2 < p2.length; i2++) {
2324
+ if (e2.indexOf(p2[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p2[i2]))
2325
+ t2[p2[i2]] = s2[p2[i2]];
2326
+ }
2327
+ return t2;
2328
+ }
2329
+ function __decorate(decorators, target, key, desc) {
2330
+ var c2 = arguments.length, r2 = c2 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d2;
2331
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r2 = Reflect.decorate(decorators, target, key, desc);
2332
+ else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d2 = decorators[i2]) r2 = (c2 < 3 ? d2(r2) : c2 > 3 ? d2(target, key, r2) : d2(target, key)) || r2;
2333
+ return c2 > 3 && r2 && Object.defineProperty(target, key, r2), r2;
2334
+ }
2335
+ function __param(paramIndex, decorator) {
2336
+ return function(target, key) {
2337
+ decorator(target, key, paramIndex);
2150
2338
  };
2151
- const subscribe = (listener) => {
2152
- let isInitialNotify = true;
2153
- const unsubscribe = source.subscribe((value) => {
2154
- if (isInitialNotify) {
2155
- isInitialNotify = false;
2156
- return;
2157
- }
2158
- listener(value);
2339
+ }
2340
+ function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
2341
+ function accept(f) {
2342
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
2343
+ return f;
2344
+ }
2345
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
2346
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
2347
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
2348
+ var _2, done = false;
2349
+ for (var i2 = decorators.length - 1; i2 >= 0; i2--) {
2350
+ var context = {};
2351
+ for (var p2 in contextIn) context[p2] = p2 === "access" ? {} : contextIn[p2];
2352
+ for (var p2 in contextIn.access) context.access[p2] = contextIn.access[p2];
2353
+ context.addInitializer = function(f) {
2354
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
2355
+ extraInitializers.push(accept(f || null));
2356
+ };
2357
+ var result = (0, decorators[i2])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
2358
+ if (kind === "accessor") {
2359
+ if (result === void 0) continue;
2360
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
2361
+ if (_2 = accept(result.get)) descriptor.get = _2;
2362
+ if (_2 = accept(result.set)) descriptor.set = _2;
2363
+ if (_2 = accept(result.init)) initializers.unshift(_2);
2364
+ } else if (_2 = accept(result)) {
2365
+ if (kind === "field") initializers.unshift(_2);
2366
+ else descriptor[key] = _2;
2367
+ }
2368
+ }
2369
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
2370
+ done = true;
2371
+ }
2372
+ function __runInitializers(thisArg, initializers, value) {
2373
+ var useValue = arguments.length > 2;
2374
+ for (var i2 = 0; i2 < initializers.length; i2++) {
2375
+ value = useValue ? initializers[i2].call(thisArg, value) : initializers[i2].call(thisArg);
2376
+ }
2377
+ return useValue ? value : void 0;
2378
+ }
2379
+ function __propKey(x2) {
2380
+ return typeof x2 === "symbol" ? x2 : "".concat(x2);
2381
+ }
2382
+ function __setFunctionName(f, name, prefix) {
2383
+ if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
2384
+ return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
2385
+ }
2386
+ function __metadata(metadataKey, metadataValue) {
2387
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
2388
+ }
2389
+ function __awaiter(thisArg, _arguments, P, generator) {
2390
+ function adopt(value) {
2391
+ return value instanceof P ? value : new P(function(resolve) {
2392
+ resolve(value);
2159
2393
  });
2160
- return () => {
2161
- unsubscribe();
2394
+ }
2395
+ return new (P || (P = Promise))(function(resolve, reject) {
2396
+ function fulfilled(value) {
2397
+ try {
2398
+ step(generator.next(value));
2399
+ } catch (e2) {
2400
+ reject(e2);
2401
+ }
2402
+ }
2403
+ function rejected(value) {
2404
+ try {
2405
+ step(generator["throw"](value));
2406
+ } catch (e2) {
2407
+ reject(e2);
2408
+ }
2409
+ }
2410
+ function step(result) {
2411
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
2412
+ }
2413
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
2414
+ });
2415
+ }
2416
+ function __generator(thisArg, body) {
2417
+ var _2 = { label: 0, sent: function() {
2418
+ if (t2[0] & 1) throw t2[1];
2419
+ return t2[1];
2420
+ }, trys: [], ops: [] }, f, y2, t2, g2 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
2421
+ return g2.next = verb(0), g2["throw"] = verb(1), g2["return"] = verb(2), typeof Symbol === "function" && (g2[Symbol.iterator] = function() {
2422
+ return this;
2423
+ }), g2;
2424
+ function verb(n2) {
2425
+ return function(v2) {
2426
+ return step([n2, v2]);
2162
2427
  };
2163
- };
2164
- return {
2165
- signal: source,
2166
- get value() {
2167
- return getValue();
2168
- },
2169
- peek,
2170
- set: set2,
2171
- update,
2172
- subscribe
2173
- };
2428
+ }
2429
+ function step(op) {
2430
+ if (f) throw new TypeError("Generator is already executing.");
2431
+ while (g2 && (g2 = 0, op[0] && (_2 = 0)), _2) try {
2432
+ if (f = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
2433
+ if (y2 = 0, t2) op = [op[0] & 2, t2.value];
2434
+ switch (op[0]) {
2435
+ case 0:
2436
+ case 1:
2437
+ t2 = op;
2438
+ break;
2439
+ case 4:
2440
+ _2.label++;
2441
+ return { value: op[1], done: false };
2442
+ case 5:
2443
+ _2.label++;
2444
+ y2 = op[1];
2445
+ op = [0];
2446
+ continue;
2447
+ case 7:
2448
+ op = _2.ops.pop();
2449
+ _2.trys.pop();
2450
+ continue;
2451
+ default:
2452
+ if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
2453
+ _2 = 0;
2454
+ continue;
2455
+ }
2456
+ if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
2457
+ _2.label = op[1];
2458
+ break;
2459
+ }
2460
+ if (op[0] === 6 && _2.label < t2[1]) {
2461
+ _2.label = t2[1];
2462
+ t2 = op;
2463
+ break;
2464
+ }
2465
+ if (t2 && _2.label < t2[2]) {
2466
+ _2.label = t2[2];
2467
+ _2.ops.push(op);
2468
+ break;
2469
+ }
2470
+ if (t2[2]) _2.ops.pop();
2471
+ _2.trys.pop();
2472
+ continue;
2473
+ }
2474
+ op = body.call(thisArg, _2);
2475
+ } catch (e2) {
2476
+ op = [6, e2];
2477
+ y2 = 0;
2478
+ } finally {
2479
+ f = t2 = 0;
2480
+ }
2481
+ if (op[0] & 5) throw op[1];
2482
+ return { value: op[0] ? op[1] : void 0, done: true };
2483
+ }
2174
2484
  }
2175
- function isSchemxSchemas(schemas) {
2176
- if (!schemas || Array.isArray(schemas)) {
2177
- return false;
2485
+ var __createBinding = Object.create ? function(o2, m2, k, k2) {
2486
+ if (k2 === void 0) k2 = k;
2487
+ var desc = Object.getOwnPropertyDescriptor(m2, k);
2488
+ if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) {
2489
+ desc = { enumerable: true, get: function() {
2490
+ return m2[k];
2491
+ } };
2178
2492
  }
2179
- const candidate = schemas;
2180
- return typeof candidate.peek === "function" && typeof candidate.set === "function" && typeof candidate.update === "function" && typeof candidate.subscribe === "function";
2493
+ Object.defineProperty(o2, k2, desc);
2494
+ } : function(o2, m2, k, k2) {
2495
+ if (k2 === void 0) k2 = k;
2496
+ o2[k2] = m2[k];
2497
+ };
2498
+ function __exportStar(m2, o2) {
2499
+ for (var p2 in m2) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(o2, p2)) __createBinding(o2, m2, p2);
2181
2500
  }
2182
- class CompileErrorImpl extends Error {
2183
- constructor(message, schema) {
2184
- super(message);
2185
- __publicField(this, "schemaKey");
2186
- __publicField(this, "schemaName");
2187
- this.name = "CompileError";
2188
- if (schema && "name" in schema) {
2189
- this.schemaName = schema.name;
2501
+ function __values(o2) {
2502
+ var s2 = typeof Symbol === "function" && Symbol.iterator, m2 = s2 && o2[s2], i2 = 0;
2503
+ if (m2) return m2.call(o2);
2504
+ if (o2 && typeof o2.length === "number") return {
2505
+ next: function() {
2506
+ if (o2 && i2 >= o2.length) o2 = void 0;
2507
+ return { value: o2 && o2[i2++], done: !o2 };
2190
2508
  }
2191
- if (schema && "key" in schema && schema.key) {
2192
- this.schemaKey = schema.key;
2509
+ };
2510
+ throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined.");
2511
+ }
2512
+ function __read(o2, n2) {
2513
+ var m2 = typeof Symbol === "function" && o2[Symbol.iterator];
2514
+ if (!m2) return o2;
2515
+ var i2 = m2.call(o2), r2, ar = [], e2;
2516
+ try {
2517
+ while ((n2 === void 0 || n2-- > 0) && !(r2 = i2.next()).done) ar.push(r2.value);
2518
+ } catch (error) {
2519
+ e2 = { error };
2520
+ } finally {
2521
+ try {
2522
+ if (r2 && !r2.done && (m2 = i2["return"])) m2.call(i2);
2523
+ } finally {
2524
+ if (e2) throw e2.error;
2193
2525
  }
2194
2526
  }
2527
+ return ar;
2195
2528
  }
2196
- const CompileError = CompileErrorImpl;
2197
- function compileToDescriptors(schemas, options = {}, parentKey = "") {
2198
- const descriptors = [];
2199
- const normalized = normalizeSchemas(schemas);
2200
- for (let i2 = 0; i2 < normalized.length; i2++) {
2201
- const schema = normalized[i2];
2202
- let descriptor = void 0;
2203
- if (isGroupSchema(schema)) {
2204
- descriptor = compileGroup(schema, i2, options, parentKey);
2205
- } else if (isDependencySchema(schema)) {
2206
- descriptor = compileDependencySlot(schema, i2, parentKey);
2207
- } else {
2208
- descriptor = compileField(schema, i2, options, parentKey);
2529
+ function __spread() {
2530
+ for (var ar = [], i2 = 0; i2 < arguments.length; i2++)
2531
+ ar = ar.concat(__read(arguments[i2]));
2532
+ return ar;
2533
+ }
2534
+ function __spreadArrays() {
2535
+ for (var s2 = 0, i2 = 0, il = arguments.length; i2 < il; i2++) s2 += arguments[i2].length;
2536
+ for (var r2 = Array(s2), k = 0, i2 = 0; i2 < il; i2++)
2537
+ for (var a2 = arguments[i2], j2 = 0, jl = a2.length; j2 < jl; j2++, k++)
2538
+ r2[k] = a2[j2];
2539
+ return r2;
2540
+ }
2541
+ function __spreadArray(to, from, pack) {
2542
+ if (pack || arguments.length === 2) for (var i2 = 0, l2 = from.length, ar; i2 < l2; i2++) {
2543
+ if (ar || !(i2 in from)) {
2544
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i2);
2545
+ ar[i2] = from[i2];
2209
2546
  }
2210
- descriptors.push(descriptor);
2211
2547
  }
2212
- return descriptors;
2548
+ return to.concat(ar || Array.prototype.slice.call(from));
2213
2549
  }
2214
- function compileField(schema, index, options = {}, parentKey = "") {
2215
- const key = schema.key ?? (parentKey ? `field:${parentKey}/${schema.name}` : `field:${schema.name}`);
2216
- const normalizedSchema = buildNormalizedFieldSchema(schema, options);
2217
- return {
2218
- type: "field",
2219
- key,
2220
- name: schema.name,
2221
- rendererType: schema.componentType,
2222
- schema: normalizedSchema,
2223
- dependencies: schema.dependencies
2224
- };
2550
+ function __await(v2) {
2551
+ return this instanceof __await ? (this.v = v2, this) : new __await(v2);
2225
2552
  }
2226
- function compileGroup(schema, index, options = {}, parentKey = "") {
2227
- const key = schema.key ?? (parentKey ? `group:${parentKey}/${index}` : `group:${index}`);
2228
- const { children: rawChildren, ...schemaWithoutChildren } = schema;
2229
- const children = compileToDescriptors(rawChildren, options, key);
2230
- return {
2231
- type: "group",
2232
- key,
2233
- schema: {
2234
- ...schemaWithoutChildren,
2235
- key
2236
- },
2237
- children
2238
- };
2553
+ function __asyncGenerator(thisArg, _arguments, generator) {
2554
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
2555
+ var g2 = generator.apply(thisArg, _arguments || []), i2, q = [];
2556
+ return i2 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i2[Symbol.asyncIterator] = function() {
2557
+ return this;
2558
+ }, i2;
2559
+ function awaitReturn(f) {
2560
+ return function(v2) {
2561
+ return Promise.resolve(v2).then(f, reject);
2562
+ };
2563
+ }
2564
+ function verb(n2, f) {
2565
+ if (g2[n2]) {
2566
+ i2[n2] = function(v2) {
2567
+ return new Promise(function(a2, b2) {
2568
+ q.push([n2, v2, a2, b2]) > 1 || resume(n2, v2);
2569
+ });
2570
+ };
2571
+ if (f) i2[n2] = f(i2[n2]);
2572
+ }
2573
+ }
2574
+ function resume(n2, v2) {
2575
+ try {
2576
+ step(g2[n2](v2));
2577
+ } catch (e2) {
2578
+ settle(q[0][3], e2);
2579
+ }
2580
+ }
2581
+ function step(r2) {
2582
+ r2.value instanceof __await ? Promise.resolve(r2.value.v).then(fulfill, reject) : settle(q[0][2], r2);
2583
+ }
2584
+ function fulfill(value) {
2585
+ resume("next", value);
2586
+ }
2587
+ function reject(value) {
2588
+ resume("throw", value);
2589
+ }
2590
+ function settle(f, v2) {
2591
+ if (f(v2), q.shift(), q.length) resume(q[0][0], q[0][1]);
2592
+ }
2239
2593
  }
2240
- function compileDependencySlot(schema, index, parentKey = "") {
2241
- const key = schema.key ?? (parentKey ? `dependency:${parentKey}/${index}` : `dependency:${index}`);
2242
- if (!schema.to || schema.to.length === 0) {
2243
- throw new CompileError("Dependency schema must have non-empty trigger fields", schema);
2594
+ function __asyncDelegator(o2) {
2595
+ var i2, p2;
2596
+ return i2 = {}, verb("next"), verb("throw", function(e2) {
2597
+ throw e2;
2598
+ }), verb("return"), i2[Symbol.iterator] = function() {
2599
+ return this;
2600
+ }, i2;
2601
+ function verb(n2, f) {
2602
+ i2[n2] = o2[n2] ? function(v2) {
2603
+ return (p2 = !p2) ? { value: __await(o2[n2](v2)), done: false } : f ? f(v2) : v2;
2604
+ } : f;
2244
2605
  }
2245
- const trigger = [...schema.to];
2246
- const renderer = (formApi, abortSignal) => {
2247
- const values = formApi.getValues();
2248
- return schema.renderer(values, formApi, {
2249
- abortSignal
2250
- });
2251
- };
2252
- return {
2253
- type: "dependency",
2254
- key,
2255
- trigger,
2256
- renderer
2257
- };
2258
2606
  }
2259
- function buildNormalizedFieldSchema(schema, options = {}) {
2260
- const {
2261
- componentProps: cp,
2262
- visible,
2263
- readonly,
2264
- disabled,
2265
- required,
2266
- placeholder,
2267
- rules,
2268
- validationTrigger,
2269
- dependencies: _dependencies,
2270
- ...rest
2271
- } = schema;
2272
- const mergedVisible = visible ?? defaultConfig.visible;
2273
- const mergedReadonly = readonly ?? options.readonly ?? defaultConfig.readonly;
2274
- const mergedDisabled = disabled ?? options.disabled ?? defaultConfig.disabled;
2275
- const mergedAlign = mergedReadonly ? "right" : (cp == null ? void 0 : cp.align) ?? rest.contentAlign;
2276
- const mergedPlaceholder = getPlaceholder(schema);
2277
- const componentProps = {
2278
- ...cp,
2279
- readonly: mergedReadonly,
2280
- disabled: mergedDisabled,
2281
- placeholder: mergedPlaceholder,
2282
- align: mergedAlign
2283
- };
2284
- const rulesArray = (Array.isArray(rules) ? rules : [rules]).filter(Boolean);
2285
- const mergedRequired = required ?? (rulesArray.length > 0 || defaultConfig.required);
2286
- const normalizedSchema = {
2287
- ...rest ?? {},
2288
- key: rest.key,
2289
- name: rest.name,
2290
- label: rest.label,
2291
- componentType: rest.componentType,
2292
- visible: mergedVisible,
2293
- readonly: mergedReadonly,
2294
- disabled: mergedDisabled,
2295
- required: mergedRequired,
2296
- placeholder: mergedPlaceholder,
2297
- componentProps,
2298
- labelIcon: rest.labelIcon || defaultConfig.labelIcon,
2299
- labelAlign: rest.labelAlign || defaultConfig.labelAlign,
2300
- labelPosition: rest.labelPosition || defaultConfig.labelPosition,
2301
- labelWidth: rest.labelWidth || defaultConfig.labelWidth,
2302
- colon: rest.colon ?? defaultConfig.colon,
2303
- rules,
2304
- validationTrigger: validationTrigger || defaultConfig.validationTrigger
2305
- };
2306
- if (Object.hasOwn(schema, "initialValue")) {
2307
- normalizedSchema.initialValue = rest.initialValue;
2607
+ function __asyncValues(o2) {
2608
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
2609
+ var m2 = o2[Symbol.asyncIterator], i2;
2610
+ return m2 ? m2.call(o2) : (o2 = typeof __values === "function" ? __values(o2) : o2[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() {
2611
+ return this;
2612
+ }, i2);
2613
+ function verb(n2) {
2614
+ i2[n2] = o2[n2] && function(v2) {
2615
+ return new Promise(function(resolve, reject) {
2616
+ v2 = o2[n2](v2), settle(resolve, reject, v2.done, v2.value);
2617
+ });
2618
+ };
2308
2619
  }
2309
- if (mergedReadonly) {
2310
- normalizedSchema.contentAlign = "right";
2311
- normalizedSchema.labelPosition = "left";
2620
+ function settle(resolve, reject, d2, v2) {
2621
+ Promise.resolve(v2).then(function(v3) {
2622
+ resolve({ value: v3, done: d2 });
2623
+ }, reject);
2312
2624
  }
2313
- return normalizedSchema;
2314
2625
  }
2315
- function getPlaceholder(schema) {
2316
- var _a;
2317
- const existingplaceholder = ((_a = schema.componentProps) == null ? void 0 : _a.placeholder) ?? schema.placeholder;
2318
- if (existingplaceholder == null) {
2319
- return ["input", "text", "textarea"].includes(schema.componentType) ? `请输入${schema.label || schema.name}` : `请选择${schema.label || schema.name}`;
2626
+ function __makeTemplateObject(cooked, raw) {
2627
+ if (Object.defineProperty) {
2628
+ Object.defineProperty(cooked, "raw", { value: raw });
2629
+ } else {
2630
+ cooked.raw = raw;
2320
2631
  }
2321
- return existingplaceholder;
2632
+ return cooked;
2322
2633
  }
2323
- const isFieldDescriptor = (descriptor) => {
2324
- return descriptor.type === "field";
2634
+ var __setModuleDefault = Object.create ? function(o2, v2) {
2635
+ Object.defineProperty(o2, "default", { enumerable: true, value: v2 });
2636
+ } : function(o2, v2) {
2637
+ o2["default"] = v2;
2325
2638
  };
2326
- const isGroupDescriptor = (descriptor) => {
2327
- return descriptor.type === "group";
2328
- };
2329
- const isDependencyDescriptor = (descriptor) => {
2330
- return descriptor.type === "dependency";
2331
- };
2332
- function createFieldModel(descriptor) {
2333
- return {
2334
- snapshot: createSignal(createFieldModelSnapshot(descriptor))
2639
+ var ownKeys = function(o2) {
2640
+ ownKeys = Object.getOwnPropertyNames || function(o3) {
2641
+ var ar = [];
2642
+ for (var k in o3) if (Object.prototype.hasOwnProperty.call(o3, k)) ar[ar.length] = k;
2643
+ return ar;
2335
2644
  };
2336
- }
2337
- function updateFieldModel(model, descriptor, resolved) {
2338
- const nextSnapshot = createFieldModelSnapshot(descriptor, resolved);
2339
- if (isSameFieldModelSnapshot(model.snapshot.peek(), nextSnapshot)) {
2340
- return;
2645
+ return ownKeys(o2);
2646
+ };
2647
+ function __importStar(mod) {
2648
+ if (mod && mod.__esModule) return mod;
2649
+ var result = {};
2650
+ if (mod != null) {
2651
+ for (var k = ownKeys(mod), i2 = 0; i2 < k.length; i2++) if (k[i2] !== "default") __createBinding(result, mod, k[i2]);
2341
2652
  }
2342
- model.snapshot.value = nextSnapshot;
2343
- }
2344
- function createFieldModelSnapshot(descriptor, resolved) {
2345
- const schema = descriptor.schema;
2346
- return {
2347
- visible: (resolved == null ? void 0 : resolved.visible) ?? schema.visible ?? defaultConfig.visible,
2348
- disabled: (resolved == null ? void 0 : resolved.disabled) ?? schema.disabled ?? defaultConfig.disabled,
2349
- readonly: (resolved == null ? void 0 : resolved.readonly) ?? schema.readonly ?? defaultConfig.readonly,
2350
- required: (resolved == null ? void 0 : resolved.required) ?? schema.required ?? defaultConfig.required,
2351
- label: schema.label || "",
2352
- rules: ((resolved == null ? void 0 : resolved.rules) ?? schema.rules) || [],
2353
- placeholder: (resolved == null ? void 0 : resolved.placeholder) ?? schema.placeholder ?? getPlaceholder(schema),
2354
- componentProps: ((resolved == null ? void 0 : resolved.componentProps) ?? schema.componentProps) || {}
2355
- };
2356
- }
2357
- function isSameFieldModelSnapshot(current, next) {
2358
- return current.visible === next.visible && current.disabled === next.disabled && current.readonly === next.readonly && current.required === next.required && current.label === next.label && isSameArrayOrValue(current.rules, next.rules) && current.placeholder === next.placeholder && isShallowEqualRecord(current.componentProps, next.componentProps);
2653
+ __setModuleDefault(result, mod);
2654
+ return result;
2359
2655
  }
2360
- function isSameArrayOrValue(current, next) {
2361
- if (current === next) {
2362
- return true;
2363
- }
2364
- if (!Array.isArray(current) || !Array.isArray(next)) {
2365
- return false;
2656
+ function __importDefault(mod) {
2657
+ return mod && mod.__esModule ? mod : { default: mod };
2658
+ }
2659
+ function __classPrivateFieldGet(receiver, state, kind, f) {
2660
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
2661
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
2662
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
2663
+ }
2664
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
2665
+ if (kind === "m") throw new TypeError("Private method is not writable");
2666
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
2667
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
2668
+ return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
2669
+ }
2670
+ function __classPrivateFieldIn(state, receiver) {
2671
+ if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object");
2672
+ return typeof state === "function" ? receiver === state : state.has(receiver);
2673
+ }
2674
+ function __addDisposableResource(env, value, async) {
2675
+ if (value !== null && value !== void 0) {
2676
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
2677
+ var dispose, inner;
2678
+ if (async) {
2679
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
2680
+ dispose = value[Symbol.asyncDispose];
2681
+ }
2682
+ if (dispose === void 0) {
2683
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
2684
+ dispose = value[Symbol.dispose];
2685
+ if (async) inner = dispose;
2686
+ }
2687
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
2688
+ if (inner) dispose = function() {
2689
+ try {
2690
+ inner.call(this);
2691
+ } catch (e2) {
2692
+ return Promise.reject(e2);
2693
+ }
2694
+ };
2695
+ env.stack.push({ value, dispose, async });
2696
+ } else if (async) {
2697
+ env.stack.push({ async: true });
2366
2698
  }
2367
- return current.length === next.length && current.every((value, index) => value === next[index]);
2699
+ return value;
2368
2700
  }
2369
- function isShallowEqualRecord(current, next) {
2370
- if (current === next) {
2371
- return true;
2701
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
2702
+ var e2 = new Error(message);
2703
+ return e2.name = "SuppressedError", e2.error = error, e2.suppressed = suppressed, e2;
2704
+ };
2705
+ function __disposeResources(env) {
2706
+ function fail(e2) {
2707
+ env.error = env.hasError ? new _SuppressedError(e2, env.error, "An error was suppressed during disposal.") : e2;
2708
+ env.hasError = true;
2709
+ }
2710
+ var r2, s2 = 0;
2711
+ function next() {
2712
+ while (r2 = env.stack.pop()) {
2713
+ try {
2714
+ if (!r2.async && s2 === 1) return s2 = 0, env.stack.push(r2), Promise.resolve().then(next);
2715
+ if (r2.dispose) {
2716
+ var result = r2.dispose.call(r2.value);
2717
+ if (r2.async) return s2 |= 2, Promise.resolve(result).then(next, function(e2) {
2718
+ fail(e2);
2719
+ return next();
2720
+ });
2721
+ } else s2 |= 1;
2722
+ } catch (e2) {
2723
+ fail(e2);
2724
+ }
2725
+ }
2726
+ if (s2 === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
2727
+ if (env.hasError) throw env.error;
2372
2728
  }
2373
- const currentKeys = Object.keys(current);
2374
- const nextKeys = Object.keys(next);
2375
- const currentRecord = current;
2376
- const nextRecord = next;
2377
- return currentKeys.length === nextKeys.length && currentKeys.every((key) => currentRecord[key] === nextRecord[key]);
2729
+ return next();
2378
2730
  }
2731
+ function __rewriteRelativeImportExtension(path, preserveJsx) {
2732
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
2733
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m2, tsx, d2, ext, cm) {
2734
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d2 && (!ext || !cm) ? m2 : d2 + ext + "." + cm.toLowerCase() + "js";
2735
+ });
2736
+ }
2737
+ return path;
2738
+ }
2739
+ const tslib_es6 = {
2740
+ __extends,
2741
+ __assign,
2742
+ __rest,
2743
+ __decorate,
2744
+ __param,
2745
+ __esDecorate,
2746
+ __runInitializers,
2747
+ __propKey,
2748
+ __setFunctionName,
2749
+ __metadata,
2750
+ __awaiter,
2751
+ __generator,
2752
+ __createBinding,
2753
+ __exportStar,
2754
+ __values,
2755
+ __read,
2756
+ __spread,
2757
+ __spreadArrays,
2758
+ __spreadArray,
2759
+ __await,
2760
+ __asyncGenerator,
2761
+ __asyncDelegator,
2762
+ __asyncValues,
2763
+ __makeTemplateObject,
2764
+ __importStar,
2765
+ __importDefault,
2766
+ __classPrivateFieldGet,
2767
+ __classPrivateFieldSet,
2768
+ __classPrivateFieldIn,
2769
+ __addDisposableResource,
2770
+ __disposeResources,
2771
+ __rewriteRelativeImportExtension
2772
+ };
2773
+ const tslib_es6$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
2774
+ __proto__: null,
2775
+ __addDisposableResource,
2776
+ get __assign() {
2777
+ return __assign;
2778
+ },
2779
+ __asyncDelegator,
2780
+ __asyncGenerator,
2781
+ __asyncValues,
2782
+ __await,
2783
+ __awaiter,
2784
+ __classPrivateFieldGet,
2785
+ __classPrivateFieldIn,
2786
+ __classPrivateFieldSet,
2787
+ __createBinding,
2788
+ __decorate,
2789
+ __disposeResources,
2790
+ __esDecorate,
2791
+ __exportStar,
2792
+ __extends,
2793
+ __generator,
2794
+ __importDefault,
2795
+ __importStar,
2796
+ __makeTemplateObject,
2797
+ __metadata,
2798
+ __param,
2799
+ __propKey,
2800
+ __read,
2801
+ __rest,
2802
+ __rewriteRelativeImportExtension,
2803
+ __runInitializers,
2804
+ __setFunctionName,
2805
+ __spread,
2806
+ __spreadArray,
2807
+ __spreadArrays,
2808
+ __values,
2809
+ default: tslib_es6
2810
+ }, Symbol.toStringTag, { value: "Module" }));
2811
+ const require$$0 = /* @__PURE__ */ getAugmentedNamespace(tslib_es6$1);
2812
+ var Polyfill$1 = {};
2813
+ var _Promise = {};
2814
+ var AsyncStack$1 = {};
2815
+ Object.defineProperty(AsyncStack$1, "__esModule", { value: true });
2816
+ AsyncStack$1.AsyncStack = void 0;
2817
+ const GlobalSymbol = Symbol("Global");
2818
+ class AsyncStack {
2819
+ static getCurrent() {
2820
+ const current = this.current;
2821
+ return current;
2822
+ }
2823
+ static set(ctx) {
2824
+ this.current = ctx;
2825
+ }
2826
+ static fork() {
2827
+ const origin = AsyncStack.getCurrent();
2828
+ const fork = new AsyncStack(origin);
2829
+ fork.start();
2830
+ return fork;
2831
+ }
2832
+ constructor(origin) {
2833
+ if (origin !== GlobalSymbol) {
2834
+ this.origin = origin;
2835
+ }
2836
+ }
2837
+ start() {
2838
+ AsyncStack.set(this);
2839
+ }
2840
+ // private yielded = false
2841
+ yield() {
2842
+ AsyncStack.set(this.origin);
2843
+ }
2844
+ }
2845
+ AsyncStack$1.AsyncStack = AsyncStack;
2846
+ AsyncStack.Global = new AsyncStack(GlobalSymbol);
2847
+ AsyncStack.current = AsyncStack.Global;
2848
+ AsyncStack.NO_DATA = Symbol("NO_DATA");
2849
+ var _lib = {};
2850
+ (function(exports) {
2851
+ Object.defineProperty(exports, "__esModule", { value: true });
2852
+ exports.runInStack = exports.withContext = exports.createAsyncResolver = void 0;
2853
+ exports.callWithContext = callWithContext;
2854
+ const AsyncStack_12 = AsyncStack$1;
2855
+ const createAsyncResolver = (stack, callback, onlyOnce = true) => {
2856
+ let called = false;
2857
+ return function(...args) {
2858
+ if (onlyOnce && called)
2859
+ return;
2860
+ called = true;
2861
+ stack.yield();
2862
+ const result = callback.call(this, ...args);
2863
+ return result;
2864
+ };
2865
+ };
2866
+ exports.createAsyncResolver = createAsyncResolver;
2867
+ function callWithContext(originalCallback, args) {
2868
+ const fork = AsyncStack_12.AsyncStack.fork();
2869
+ const patchedArgs = args.map((arg) => {
2870
+ if (typeof arg === "function") {
2871
+ return (0, exports.createAsyncResolver)(fork, arg);
2872
+ }
2873
+ return arg;
2874
+ });
2875
+ const result = originalCallback.call(this, ...patchedArgs);
2876
+ fork.yield();
2877
+ return result;
2878
+ }
2879
+ const withContext = (originalCallback, onlyOnce = true) => {
2880
+ if (typeof originalCallback === "undefined")
2881
+ return void 0;
2882
+ return function(...args) {
2883
+ return callWithContext.call(this, originalCallback, args);
2884
+ };
2885
+ };
2886
+ exports.withContext = withContext;
2887
+ const runInStack = (stackToUse, callback) => {
2888
+ const currentStack = AsyncStack_12.AsyncStack.getCurrent();
2889
+ stackToUse.start();
2890
+ try {
2891
+ const result = callback();
2892
+ currentStack.start();
2893
+ return result;
2894
+ } catch (err) {
2895
+ currentStack.start();
2896
+ throw err;
2897
+ }
2898
+ };
2899
+ exports.runInStack = runInStack;
2900
+ })(_lib);
2901
+ (function(exports) {
2902
+ Object.defineProperty(exports, "__esModule", { value: true });
2903
+ exports.PromiseWithContext = exports.OriginalPromise = void 0;
2904
+ const AsyncStack_12 = AsyncStack$1;
2905
+ const _lib_12 = _lib;
2906
+ exports.OriginalPromise = Promise;
2907
+ class PromiseWithContext extends exports.OriginalPromise {
2908
+ constructor(callback) {
2909
+ super((resolve, reject) => {
2910
+ const fork = AsyncStack_12.AsyncStack.fork();
2911
+ const wrapResolve = (0, _lib_12.createAsyncResolver)(fork, resolve);
2912
+ const wrapReject = (0, _lib_12.createAsyncResolver)(fork, reject);
2913
+ callback(wrapResolve, wrapReject);
2914
+ fork.yield();
2915
+ });
2916
+ }
2917
+ then(...args) {
2918
+ return _lib_12.callWithContext.call(this, super.then, args);
2919
+ }
2920
+ catch(...args) {
2921
+ return _lib_12.callWithContext.call(this, super.catch, args);
2922
+ }
2923
+ finally(...args) {
2924
+ return _lib_12.callWithContext.call(this, super.finally, args);
2925
+ }
2926
+ }
2927
+ exports.PromiseWithContext = PromiseWithContext;
2928
+ Object.getOwnPropertyNames(Promise).forEach((method) => {
2929
+ if (typeof Promise[method] === "function") {
2930
+ PromiseWithContext[method] = exports.OriginalPromise[method].bind(PromiseWithContext);
2931
+ }
2932
+ });
2933
+ })(_Promise);
2934
+ var Events = {};
2935
+ Object.defineProperty(Events, "__esModule", { value: true });
2936
+ Events.addEventListenerWithContext = Events.dispatchWithContext = void 0;
2937
+ const AsyncStack_1 = AsyncStack$1;
2938
+ const _lib_1$1 = _lib;
2939
+ const originalAddEventListerner = EventTarget.prototype.addEventListener;
2940
+ const originalDispatchEvent = EventTarget.prototype.dispatchEvent;
2941
+ const stackByEvent = /* @__PURE__ */ new WeakMap();
2942
+ const dispatchWithContext = function(event) {
2943
+ const stack = AsyncStack_1.AsyncStack.getCurrent();
2944
+ stackByEvent.set(event, stack);
2945
+ return originalDispatchEvent.call(this, event);
2946
+ };
2947
+ Events.dispatchWithContext = dispatchWithContext;
2948
+ const addEventListenerWithContext = function(event, callback, options) {
2949
+ const wrappedCallback = function(event2) {
2950
+ const stackWhenDispatched = stackByEvent.get(event2) || AsyncStack_1.AsyncStack.Global;
2951
+ return (0, _lib_1$1.runInStack)(stackWhenDispatched, () => {
2952
+ return callback.call(this, event2);
2953
+ });
2954
+ };
2955
+ return originalAddEventListerner.call(this, event, wrappedCallback, options);
2956
+ };
2957
+ Events.addEventListenerWithContext = addEventListenerWithContext;
2958
+ Object.defineProperty(Polyfill$1, "__esModule", { value: true });
2959
+ Polyfill$1.Polyfill = void 0;
2960
+ const Promise_1 = _Promise;
2961
+ const Events_1 = Events;
2962
+ const _lib_1 = _lib;
2963
+ const root = typeof commonjsGlobal !== "undefined" && commonjsGlobal || typeof window !== "undefined" && window;
2964
+ class Polyfill {
2965
+ static ensureEnabled() {
2966
+ if (Polyfill.enabled)
2967
+ return;
2968
+ Polyfill.enabled = true;
2969
+ root.Promise = Promise_1.PromiseWithContext;
2970
+ root.setTimeout = (0, _lib_1.withContext)(root.setTimeout);
2971
+ root.setInterval = (0, _lib_1.withContext)(root.setInterval);
2972
+ root.setImmediate = (0, _lib_1.withContext)(root.setImmediate);
2973
+ EventTarget.prototype.addEventListener = Events_1.addEventListenerWithContext;
2974
+ EventTarget.prototype.dispatchEvent = Events_1.dispatchWithContext;
2975
+ }
2976
+ }
2977
+ Polyfill$1.Polyfill = Polyfill;
2978
+ Polyfill.originalSetTimeout = setTimeout;
2979
+ Polyfill.OriginalPromise = Promise_1.OriginalPromise;
2980
+ Polyfill.enabled = false;
2981
+ var AsyncContext$1 = {};
2982
+ var AsyncVariable = {};
2983
+ var runInFork = {};
2984
+ var hasRequiredRunInFork;
2985
+ function requireRunInFork() {
2986
+ if (hasRequiredRunInFork) return runInFork;
2987
+ hasRequiredRunInFork = 1;
2988
+ Object.defineProperty(runInFork, "__esModule", { value: true });
2989
+ runInFork.runInFork = void 0;
2990
+ const runInFork$1 = (callback) => {
2991
+ let result;
2992
+ let error;
2993
+ new Promise((resolve) => {
2994
+ try {
2995
+ result = callback();
2996
+ resolve(result);
2997
+ } catch (err) {
2998
+ error = err;
2999
+ }
3000
+ });
3001
+ if (error) {
3002
+ throw error;
3003
+ }
3004
+ return result;
3005
+ };
3006
+ runInFork.runInFork = runInFork$1;
3007
+ return runInFork;
3008
+ }
3009
+ var hasRequiredAsyncVariable;
3010
+ function requireAsyncVariable() {
3011
+ if (hasRequiredAsyncVariable) return AsyncVariable;
3012
+ hasRequiredAsyncVariable = 1;
3013
+ Object.defineProperty(AsyncVariable, "__esModule", { value: true });
3014
+ AsyncVariable.AsyncVariable = void 0;
3015
+ const AsyncStack_12 = AsyncStack$1;
3016
+ const runInFork_1 = requireRunInFork();
3017
+ let AsyncVariable$1 = class AsyncVariable2 {
3018
+ constructor() {
3019
+ this.data = /* @__PURE__ */ new WeakMap();
3020
+ }
3021
+ static registerVariable(variable, stack) {
3022
+ if (!AsyncVariable2.variableByStack.has(stack)) {
3023
+ AsyncVariable2.variableByStack.set(stack, /* @__PURE__ */ new Set());
3024
+ }
3025
+ AsyncVariable2.variableByStack.get(stack).add(variable);
3026
+ }
3027
+ getBox(stack) {
3028
+ if (!stack)
3029
+ return void 0;
3030
+ const currentBox = this.data.get(stack);
3031
+ if (currentBox)
3032
+ return currentBox;
3033
+ const canWalkOrigin = AsyncVariable2.stopWalkAt.has(stack);
3034
+ if (canWalkOrigin)
3035
+ return void 0;
3036
+ const parentBox = this.getBox(stack.origin);
3037
+ if (parentBox)
3038
+ this.setBox(stack, parentBox);
3039
+ return parentBox;
3040
+ }
3041
+ setBox(stack, box) {
3042
+ AsyncVariable2.registerVariable(this, stack);
3043
+ this.data.set(stack, box);
3044
+ }
3045
+ set(stack, data) {
3046
+ this.setBox(stack, {
3047
+ value: data
3048
+ });
3049
+ }
3050
+ get() {
3051
+ var _a;
3052
+ const current = AsyncStack_12.AsyncStack.getCurrent();
3053
+ return (_a = this.getBox(current)) === null || _a === void 0 ? void 0 : _a.value;
3054
+ }
3055
+ run(data, callback) {
3056
+ return (0, runInFork_1.runInFork)(() => {
3057
+ const current = AsyncStack_12.AsyncStack.getCurrent();
3058
+ this.set(current, data);
3059
+ return callback();
3060
+ });
3061
+ }
3062
+ wrap(data, callback) {
3063
+ return (...args) => this.run(data, () => callback(...args));
3064
+ }
3065
+ };
3066
+ AsyncVariable.AsyncVariable = AsyncVariable$1;
3067
+ AsyncVariable$1.stopWalkAt = /* @__PURE__ */ new WeakSet();
3068
+ AsyncVariable$1.variableByStack = /* @__PURE__ */ new WeakMap();
3069
+ return AsyncVariable;
3070
+ }
3071
+ var AsyncSnapshot = {};
3072
+ var hasRequiredAsyncSnapshot;
3073
+ function requireAsyncSnapshot() {
3074
+ if (hasRequiredAsyncSnapshot) return AsyncSnapshot;
3075
+ hasRequiredAsyncSnapshot = 1;
3076
+ Object.defineProperty(AsyncSnapshot, "__esModule", { value: true });
3077
+ AsyncSnapshot.AsyncSnapshot = void 0;
3078
+ const AsyncStack_12 = AsyncStack$1;
3079
+ const AsyncVariable_1 = requireAsyncVariable();
3080
+ const runInFork_1 = requireRunInFork();
3081
+ let AsyncSnapshot$1 = class AsyncSnapshot2 {
3082
+ capture() {
3083
+ let current = AsyncStack_12.AsyncStack.getCurrent();
3084
+ while (current) {
3085
+ const variables = AsyncVariable_1.AsyncVariable.variableByStack.get(current);
3086
+ variables === null || variables === void 0 ? void 0 : variables.forEach((variable) => {
3087
+ const alreadyHasVariable = this.dataByVariable.has(variable);
3088
+ if (!alreadyHasVariable) {
3089
+ const value = variable.get();
3090
+ this.dataByVariable.set(variable, value);
3091
+ }
3092
+ });
3093
+ current = current.origin;
3094
+ }
3095
+ }
3096
+ constructor() {
3097
+ this.dataByVariable = /* @__PURE__ */ new Map();
3098
+ this.capture();
3099
+ }
3100
+ static create() {
3101
+ const snapshot = new AsyncSnapshot2();
3102
+ return snapshot;
3103
+ }
3104
+ run(callback) {
3105
+ return (0, runInFork_1.runInFork)(() => {
3106
+ const current = AsyncStack_12.AsyncStack.getCurrent();
3107
+ AsyncVariable_1.AsyncVariable.stopWalkAt.add(current);
3108
+ this.dataByVariable.forEach((data, variable) => {
3109
+ variable.set(current, data);
3110
+ });
3111
+ return callback();
3112
+ });
3113
+ }
3114
+ wrap(callback) {
3115
+ return (...args) => this.run(() => callback(...args));
3116
+ }
3117
+ static wrap(callback) {
3118
+ return (0, runInFork_1.runInFork)(() => {
3119
+ const snapshot = AsyncSnapshot2.create();
3120
+ return snapshot.wrap(callback);
3121
+ });
3122
+ }
3123
+ };
3124
+ AsyncSnapshot.AsyncSnapshot = AsyncSnapshot$1;
3125
+ return AsyncSnapshot;
3126
+ }
3127
+ var hasRequiredAsyncContext;
3128
+ function requireAsyncContext() {
3129
+ if (hasRequiredAsyncContext) return AsyncContext$1;
3130
+ hasRequiredAsyncContext = 1;
3131
+ Object.defineProperty(AsyncContext$1, "__esModule", { value: true });
3132
+ AsyncContext$1.AsyncContext = void 0;
3133
+ const AsyncVariable_1 = requireAsyncVariable();
3134
+ const AsyncSnapshot_1 = requireAsyncSnapshot();
3135
+ class AsyncContext2 {
3136
+ }
3137
+ AsyncContext$1.AsyncContext = AsyncContext2;
3138
+ AsyncContext2.Variable = AsyncVariable_1.AsyncVariable;
3139
+ AsyncContext2.Snapshot = AsyncSnapshot_1.AsyncSnapshot;
3140
+ return AsyncContext$1;
3141
+ }
3142
+ (function(exports) {
3143
+ Object.defineProperty(exports, "__esModule", { value: true });
3144
+ const tslib_1 = require$$0;
3145
+ const Polyfill_1 = Polyfill$1;
3146
+ Polyfill_1.Polyfill.ensureEnabled();
3147
+ tslib_1.__exportStar(requireAsyncContext(), exports);
3148
+ })(build);
3149
+ const AsyncContextNS = /* @__PURE__ */ _mergeNamespaces({
3150
+ __proto__: null
3151
+ }, [build]);
3152
+ const CONTEXT_MARK = Symbol("schemx.async-context");
3153
+ const { AsyncContext } = AsyncContextNS;
3154
+ function createContext(name, defaultValue) {
3155
+ const hasDefaultValue = arguments.length >= 2;
3156
+ const variable = new AsyncContext.Variable();
3157
+ const useContext = () => {
3158
+ const value = variable.get();
3159
+ if (value !== void 0) {
3160
+ return value;
3161
+ }
3162
+ if (hasDefaultValue) {
3163
+ return defaultValue;
3164
+ }
3165
+ throw new ContextNotProvidedError({ name });
3166
+ };
3167
+ const tryUseContext = () => {
3168
+ const value = variable.get();
3169
+ if (value !== void 0) {
3170
+ return value;
3171
+ }
3172
+ if (hasDefaultValue) {
3173
+ return defaultValue;
3174
+ }
3175
+ return void 0;
3176
+ };
3177
+ const Provider = (value, fn) => variable.run(value, fn);
3178
+ return {
3179
+ name,
3180
+ useContext,
3181
+ tryUseContext,
3182
+ Provider,
3183
+ [CONTEXT_MARK]: true
3184
+ };
3185
+ }
3186
+ class ContextNotProvidedError extends Error {
3187
+ /**
3188
+ * 创建 Context 未提供错误。
3189
+ *
3190
+ * @param context - 读取失败的上下文声明(仅取 name 用于信息展示)。
3191
+ */
3192
+ constructor(context) {
3193
+ super(`[schemx] Context "${context.name}" has not been provided.`);
3194
+ this.name = "ContextNotProvidedError";
3195
+ }
3196
+ }
3197
+ function isContext(value) {
3198
+ return Boolean(
3199
+ value && typeof value === "object" && CONTEXT_MARK in value && value[CONTEXT_MARK] === true
3200
+ );
3201
+ }
3202
+ const schemxContextStore = createContext("SchemxContext");
3203
+ function withSchemxContext(context, run) {
3204
+ return schemxContextStore.Provider(
3205
+ {
3206
+ type: "runtime",
3207
+ value: context
3208
+ },
3209
+ run
3210
+ );
3211
+ }
3212
+ function useSchemxContext() {
3213
+ const current = schemxContextStore.tryUseContext();
3214
+ if ((current == null ? void 0 : current.type) !== "runtime") {
3215
+ throw new Error("[schemx] Form runtime context has not been provided.");
3216
+ }
3217
+ return current.value;
3218
+ }
3219
+ function maybeUseSchemxContext() {
3220
+ const current = schemxContextStore.tryUseContext();
3221
+ if ((current == null ? void 0 : current.type) !== "runtime") {
3222
+ return void 0;
3223
+ }
3224
+ return current.value;
3225
+ }
3226
+ function createFieldDescriptor(options) {
3227
+ const { schema, parentKey = "" } = options;
3228
+ const key = schema.key ?? (parentKey ? `field:${parentKey}/${schema.name}` : `field:${schema.name}`);
3229
+ const normalizedSchema = buildNormalizedFieldSchema(schema);
3230
+ return {
3231
+ type: "field",
3232
+ key,
3233
+ name: schema.name,
3234
+ componentType: schema.componentType,
3235
+ staticSchema: normalizedSchema,
3236
+ dynamicProps: createFieldDynamicProps(schema.dependencies),
3237
+ validation: createFieldValidation(normalizedSchema)
3238
+ };
3239
+ }
3240
+ function createGroupDescriptor(options) {
3241
+ const { schema, index, parentKey = "" } = options;
3242
+ const key = createGroupDescriptorKey(schema.key, index, parentKey);
3243
+ const { children: _rawChildren, ...schemaWithoutChildren } = schema;
3244
+ return {
3245
+ type: "group",
3246
+ key,
3247
+ staticSchema: {
3248
+ ...schemaWithoutChildren,
3249
+ key
3250
+ },
3251
+ children: []
3252
+ };
3253
+ }
3254
+ function createDependencyDescriptor(options) {
3255
+ const { schema, parentKey = "" } = options;
3256
+ const trigger = [...schema.to];
3257
+ const triggerKey = trigger.map(serializeNamePath).join(",");
3258
+ const key = schema.key ?? (parentKey ? `dependency:${parentKey}/${triggerKey}` : `dependency:${triggerKey}`);
3259
+ const renderer = (formApi, abortSignal) => {
3260
+ const values = formApi.getValues();
3261
+ return schema.renderer(values, formApi, {
3262
+ abortSignal
3263
+ });
3264
+ };
3265
+ return {
3266
+ type: "dependency",
3267
+ key,
3268
+ triggerFields: trigger,
3269
+ renderer
3270
+ };
3271
+ }
3272
+ function getPlaceholder(schema) {
3273
+ var _a;
3274
+ const existingplaceholder = ((_a = schema.componentProps) == null ? void 0 : _a.placeholder) ?? schema.placeholder;
3275
+ if (existingplaceholder == null) {
3276
+ return ["input", "text", "textarea"].includes(schema.componentType) ? `请输入${schema.label || schema.name}` : `请选择${schema.label || schema.name}`;
3277
+ }
3278
+ return existingplaceholder;
3279
+ }
3280
+ function buildNormalizedFieldSchema(schema) {
3281
+ const { defaultProps, instance } = useSchemxContext();
3282
+ const {
3283
+ componentProps: cp,
3284
+ visible,
3285
+ readonly,
3286
+ disabled,
3287
+ required,
3288
+ rules,
3289
+ validationTrigger,
3290
+ dependencies: _dependencies,
3291
+ ...rest
3292
+ } = schema;
3293
+ const mergedVisible = visible ?? defaultConfig.visible;
3294
+ const mergedReadonly = readonly ?? defaultProps.readonly ?? defaultConfig.readonly;
3295
+ const mergedDisabled = disabled ?? defaultProps.disabled ?? defaultConfig.disabled;
3296
+ const mergedAlign = mergedReadonly ? "right" : (cp == null ? void 0 : cp.align) ?? rest.contentAlign;
3297
+ const mergedValidationTrigger = validationTrigger ?? defaultProps.validationTrigger ?? defaultConfig.validationTrigger;
3298
+ const mergedPlaceholder = getPlaceholder(schema);
3299
+ const rulesArray = (Array.isArray(rules) ? rules : [rules]).filter(Boolean);
3300
+ const mergedRequired = required ?? (rulesArray.length > 0 || defaultConfig.required);
3301
+ const normalizedSchema = {
3302
+ ...rest ?? {},
3303
+ key: rest.key,
3304
+ name: rest.name,
3305
+ label: rest.label,
3306
+ componentType: rest.componentType,
3307
+ visible: mergedVisible,
3308
+ readonly: mergedReadonly,
3309
+ disabled: mergedDisabled,
3310
+ required: mergedRequired,
3311
+ placeholder: mergedPlaceholder,
3312
+ labelIcon: rest.labelIcon || defaultConfig.labelIcon,
3313
+ labelAlign: rest.labelAlign || defaultConfig.labelAlign,
3314
+ labelPosition: rest.labelPosition || defaultConfig.labelPosition,
3315
+ labelWidth: rest.labelWidth || defaultConfig.labelWidth,
3316
+ colon: rest.colon ?? defaultConfig.colon,
3317
+ rules,
3318
+ validationTrigger: normalizeTrigger$1(mergedValidationTrigger)
3319
+ };
3320
+ if (Object.hasOwn(schema, "initialValue")) {
3321
+ normalizedSchema.initialValue = rest.initialValue;
3322
+ }
3323
+ if (mergedReadonly) {
3324
+ normalizedSchema.contentAlign = "right";
3325
+ normalizedSchema.labelPosition = "left";
3326
+ }
3327
+ normalizedSchema.componentProps = {
3328
+ ...cp,
3329
+ align: mergedAlign,
3330
+ readonly: mergedReadonly,
3331
+ disabled: mergedDisabled,
3332
+ placeholder: mergedPlaceholder,
3333
+ formItemProps: normalizedSchema,
3334
+ formInstance: instance
3335
+ };
3336
+ return normalizedSchema;
3337
+ }
3338
+ function createFieldDynamicProps(dependencies) {
3339
+ if (!dependencies) {
3340
+ return null;
3341
+ }
3342
+ return {
3343
+ source: "dependencies",
3344
+ triggerFields: dependencies.triggerFields,
3345
+ dependencies
3346
+ };
3347
+ }
3348
+ function createFieldValidation(schema) {
3349
+ const rules = normalizeValidationRules(schema.rules);
3350
+ if (!rules) {
3351
+ return null;
3352
+ }
3353
+ return {
3354
+ trigger: schema.validationTrigger,
3355
+ rules
3356
+ };
3357
+ }
3358
+ function normalizeValidationRules(rules) {
3359
+ if (rules == null) {
3360
+ return null;
3361
+ }
3362
+ if (Array.isArray(rules)) {
3363
+ return rules.length > 0 ? rules : null;
3364
+ }
3365
+ return rules;
3366
+ }
3367
+ function createGroupDescriptorKey(explicitKey, index, parentKey) {
3368
+ return explicitKey ?? (parentKey ? `group:${parentKey}/${index}` : `group:${index}`);
3369
+ }
3370
+ function serializeNamePath(name) {
3371
+ if (Array.isArray(name)) {
3372
+ return name.join(".");
3373
+ }
3374
+ return String(name);
3375
+ }
3376
+ function normalizeTrigger$1(trigger) {
3377
+ const map = {
3378
+ onBlur: "blur",
3379
+ onChange: "change",
3380
+ onSubmit: "submit",
3381
+ blur: "blur",
3382
+ change: "change",
3383
+ submit: "submit"
3384
+ };
3385
+ const TArray = Array.isArray(trigger) ? trigger : [trigger];
3386
+ return TArray.map((t2) => map[t2] ?? "submit");
3387
+ }
3388
+ function isDependencyDescriptor(descriptor) {
3389
+ return descriptor.type === "dependency";
3390
+ }
3391
+ function createCompileCache() {
3392
+ return {
3393
+ version: 0,
3394
+ entries: /* @__PURE__ */ new WeakMap()
3395
+ };
3396
+ }
3397
+ function createCompile(options = {}) {
3398
+ const compileOptions = {
3399
+ defaultProps: options.defaultProps ?? {},
3400
+ formInstance: options.formInstance ?? {}
3401
+ };
3402
+ const compileCache = createCompileCache();
3403
+ function toDescriptors(schemas, parentKey = "") {
3404
+ if (maybeUseSchemxContext()) {
3405
+ return compileDescriptors(schemas, parentKey);
3406
+ }
3407
+ return withSchemxContext(
3408
+ createFallbackCompileContext(),
3409
+ () => compileDescriptors(schemas, parentKey)
3410
+ );
3411
+ }
3412
+ function compileDescriptors(schemas, parentKey = "") {
3413
+ const descriptors = [];
3414
+ const normalized = normalizeSchemas([...schemas]);
3415
+ for (let i2 = 0; i2 < normalized.length; i2++) {
3416
+ const schema = normalized[i2];
3417
+ let descriptor;
3418
+ const cached = compileCache.entries.get(schema);
3419
+ if (cached && cached.version === compileCache.version) {
3420
+ descriptors.push(cached.descriptor);
3421
+ continue;
3422
+ }
3423
+ if (isGroupSchema(schema)) {
3424
+ descriptor = createGroupDescriptor({
3425
+ schema,
3426
+ index: i2,
3427
+ parentKey
3428
+ });
3429
+ if (schema.children.length > 0) {
3430
+ descriptor.children = toDescriptors(schema.children, descriptor.key);
3431
+ }
3432
+ } else if (isDependencySchema(schema)) {
3433
+ descriptor = createDependencyDescriptor({
3434
+ schema,
3435
+ parentKey
3436
+ });
3437
+ } else {
3438
+ descriptor = createFieldDescriptor({
3439
+ schema,
3440
+ parentKey
3441
+ });
3442
+ }
3443
+ compileCache.entries.set(schema, {
3444
+ version: compileCache.version,
3445
+ descriptor
3446
+ });
3447
+ descriptors.push(descriptor);
3448
+ }
3449
+ return descriptors;
3450
+ }
3451
+ function createFallbackCompileContext() {
3452
+ return {
3453
+ defaultProps: compileOptions.defaultProps,
3454
+ instance: compileOptions.formInstance
3455
+ };
3456
+ }
3457
+ function getCacheVersion() {
3458
+ return compileCache.version;
3459
+ }
3460
+ function invalidate() {
3461
+ compileCache.version++;
3462
+ }
3463
+ function getVersion() {
3464
+ return compileCache.version;
3465
+ }
3466
+ return {
3467
+ cache: compileCache,
3468
+ getCacheVersion,
3469
+ toDescriptors,
3470
+ invalidate,
3471
+ getVersion
3472
+ };
3473
+ }
3474
+ function createSchemas(schemas = []) {
3475
+ const source = createSignal(schemas);
3476
+ const getValue = () => {
3477
+ return source.value;
3478
+ };
3479
+ const peek = () => {
3480
+ return source.peek();
3481
+ };
3482
+ const set2 = (nextSchemas) => {
3483
+ source.value = nextSchemas;
3484
+ };
3485
+ const update = (updater) => {
3486
+ source.value = updater(source.peek());
3487
+ };
3488
+ const subscribe = (listener) => {
3489
+ let isInitialNotify = true;
3490
+ const unsubscribe = source.subscribe((value) => {
3491
+ if (isInitialNotify) {
3492
+ isInitialNotify = false;
3493
+ return;
3494
+ }
3495
+ listener(value);
3496
+ });
3497
+ return () => {
3498
+ unsubscribe();
3499
+ };
3500
+ };
3501
+ return {
3502
+ signal: source,
3503
+ get value() {
3504
+ return getValue();
3505
+ },
3506
+ peek,
3507
+ set: set2,
3508
+ update,
3509
+ subscribe
3510
+ };
3511
+ }
3512
+ function isSchemxSchemas(schemas) {
3513
+ if (!schemas || Array.isArray(schemas)) {
3514
+ return false;
3515
+ }
3516
+ const candidate = schemas;
3517
+ return typeof candidate.peek === "function" && typeof candidate.set === "function" && typeof candidate.update === "function" && typeof candidate.subscribe === "function";
3518
+ }
3519
+ function createAbortableTaskRunner(options) {
3520
+ const ownScope = options.scope.child();
3521
+ let version = 0;
3522
+ let controller = null;
3523
+ const isStale = (currentVersion, currentController) => {
3524
+ return ownScope.disposed || currentController.signal.aborted || currentVersion !== version;
3525
+ };
3526
+ const runCurrentTask = async (currentVersion, currentController) => {
3527
+ var _a, _b, _c, _d;
3528
+ try {
3529
+ const value = await options.run(currentController.signal);
3530
+ if (isStale(currentVersion, currentController)) {
3531
+ return value;
3532
+ }
3533
+ (_a = options.onSuccess) == null ? void 0 : _a.call(options, value);
3534
+ (_b = options.onSettled) == null ? void 0 : _b.call(options);
3535
+ return value;
3536
+ } catch (cause) {
3537
+ const error = normalizeError$1(cause);
3538
+ if (isStale(currentVersion, currentController)) {
3539
+ if (options.throwOnError) {
3540
+ throw error;
3541
+ }
3542
+ return;
3543
+ }
3544
+ (_c = options.onError) == null ? void 0 : _c.call(options, error);
3545
+ (_d = options.onSettled) == null ? void 0 : _d.call(options);
3546
+ if (options.throwOnError) {
3547
+ throw error;
3548
+ }
3549
+ }
3550
+ };
3551
+ const run = async () => {
3552
+ var _a;
3553
+ if (ownScope.disposed) {
3554
+ return;
3555
+ }
3556
+ const currentVersion = ++version;
3557
+ controller == null ? void 0 : controller.abort();
3558
+ controller = new AbortController();
3559
+ (_a = options.onStart) == null ? void 0 : _a.call(options, controller);
3560
+ return await options.scheduler.track(runCurrentTask(currentVersion, controller));
3561
+ };
3562
+ const dispose = () => {
3563
+ version += 1;
3564
+ controller == null ? void 0 : controller.abort();
3565
+ ownScope.dispose();
3566
+ };
3567
+ options.scope.add(dispose);
3568
+ return {
3569
+ run,
3570
+ dispose
3571
+ };
3572
+ }
3573
+ function normalizeError$1(cause) {
3574
+ return cause instanceof Error ? cause : new Error(String(cause));
3575
+ }
3576
+ function createFieldRuntimeState(options) {
3577
+ const { key, descriptor } = options;
3578
+ const schema = descriptor.staticSchema;
3579
+ const staticSchema = createSignal(schema, {
3580
+ name: `field:${String(descriptor.name)}:staticSchema`
3581
+ });
3582
+ const dynamicOverrides = createSignal(
3583
+ {},
3584
+ { name: `field:${String(descriptor.name)}:dynamicOverrides` }
3585
+ );
3586
+ const diagnostics = createSignal(
3587
+ createInitialDiagnostics(),
3588
+ { name: `field:${String(descriptor.name)}:diagnostics` }
3589
+ );
3590
+ const name = createSignal(descriptor.name, {
3591
+ name: `field:${String(descriptor.name)}:name`
3592
+ });
3593
+ const effectiveSchema = createComputed(() => {
3594
+ const base = staticSchema.value;
3595
+ const overrides = dynamicOverrides.value;
3596
+ return {
3597
+ key,
3598
+ name: name.value,
3599
+ componentType: base.componentType,
3600
+ label: base.label || "",
3601
+ visible: overrides.visible ?? base.visible ?? true,
3602
+ disabled: overrides.disabled ?? base.disabled ?? false,
3603
+ readonly: overrides.readonly ?? base.readonly ?? false,
3604
+ required: overrides.required ?? base.required ?? false,
3605
+ placeholder: overrides.placeholder ?? base.placeholder ?? "",
3606
+ componentProps: overrides.componentProps ?? base.componentProps ?? {},
3607
+ rules: overrides.rules ?? base.rules ?? [],
3608
+ validationTrigger: base.validationTrigger
3609
+ };
3610
+ });
3611
+ const viewSchema = createComputed(() => {
3612
+ const effective = effectiveSchema.value;
3613
+ return {
3614
+ ...staticSchema.value,
3615
+ visible: effective.visible,
3616
+ disabled: effective.disabled,
3617
+ readonly: effective.readonly,
3618
+ required: effective.required,
3619
+ label: effective.label,
3620
+ placeholder: effective.placeholder,
3621
+ componentProps: effective.componentProps,
3622
+ rules: effective.rules
3623
+ };
3624
+ });
3625
+ return {
3626
+ name,
3627
+ staticSchema,
3628
+ dynamicOverrides,
3629
+ effectiveSchema,
3630
+ viewSchema,
3631
+ diagnostics
3632
+ };
3633
+ }
3634
+ function setFieldStaticSchema(state, descriptor) {
3635
+ state.staticSchema.value = descriptor.staticSchema;
3636
+ state.name.value = descriptor.name;
3637
+ const prev = state.diagnostics.peek();
3638
+ state.diagnostics.value = {
3639
+ ...prev,
3640
+ lastUpdatedBy: "static-schema",
3641
+ version: prev.version + 1,
3642
+ triggerFields: [],
3643
+ overriddenKeys: [],
3644
+ error: null
3645
+ };
3646
+ }
3647
+ function setFieldDynamicOverrides(state, overrides, meta) {
3648
+ state.dynamicOverrides.value = overrides;
3649
+ const prev = state.diagnostics.peek();
3650
+ state.diagnostics.value = {
3651
+ ...prev,
3652
+ lastUpdatedBy: "dependencies",
3653
+ version: prev.version + 1,
3654
+ triggerFields: meta.triggerFields,
3655
+ overriddenKeys: Object.keys(overrides),
3656
+ error: meta.error ?? null
3657
+ };
3658
+ }
3659
+ function createInitialDiagnostics() {
3660
+ return {
3661
+ lastUpdatedBy: "static-schema",
3662
+ version: 0,
3663
+ triggerFields: [],
3664
+ overriddenKeys: [],
3665
+ error: null
3666
+ };
3667
+ }
3668
+ const FIELD_DEPENDENCIES_PROP_KEYS = [
3669
+ "componentProps",
3670
+ "placeholder",
3671
+ "required",
3672
+ "readonly",
3673
+ "disabled",
3674
+ "visible",
3675
+ "rules"
3676
+ ];
2379
3677
  function createDependenciesEffect(options) {
2380
- const { descriptor, fieldModel, context, scope } = options;
2381
- const base = descriptor.schema;
2382
- const dependencies = descriptor.dependencies;
2383
- if (dependencies == null || dependencies.triggerFields == null || dependencies.triggerFields.length === 0) {
3678
+ const { context, descriptor, runtimeState, scope } = options;
3679
+ const { formApi, scheduler } = context;
3680
+ const dynamicProps = descriptor.dynamicProps;
3681
+ const dependencies = dynamicProps == null ? void 0 : dynamicProps.dependencies;
3682
+ const triggerFields = dynamicProps == null ? void 0 : dynamicProps.triggerFields;
3683
+ if (dependencies == null || triggerFields == null || triggerFields.length === 0) {
2384
3684
  return;
2385
3685
  }
2386
- let version = 0;
3686
+ const taskRunner = createAbortableTaskRunner({
3687
+ scope,
3688
+ scheduler,
3689
+ run: () => resolveDependencies(dependencies, formApi),
3690
+ onSuccess: (resolvedProps) => {
3691
+ setFieldDynamicOverrides(runtimeState, resolvedProps, {
3692
+ triggerFields
3693
+ });
3694
+ },
3695
+ onError: (error) => {
3696
+ console.error("[schemx] dependencies 执行错误:", error);
3697
+ }
3698
+ });
2387
3699
  const dispose = createSignalEffect(() => {
2388
- const currentVersion = ++version;
2389
- void context.formApi.getValues(dependencies.triggerFields);
2390
- void context.scheduler.track(
2391
- resolveDependencies(dependencies, base, context.formApi).then((resolvedProps) => {
2392
- if (scope.disposed || currentVersion !== version) {
2393
- return;
2394
- }
2395
- updateFieldModel(fieldModel, descriptor, resolvedProps);
2396
- })
2397
- );
3700
+ void formApi.getValues([...triggerFields]);
3701
+ void taskRunner.run();
2398
3702
  });
2399
3703
  scope.add(() => {
2400
- version += 1;
2401
3704
  dispose();
2402
3705
  });
2403
3706
  }
2404
- async function resolveDependencies(dependencies, base, formApi) {
3707
+ async function resolveDependencies(dependencies, formApi) {
2405
3708
  const values = formApi.getValues();
2406
3709
  const [resolvedProps] = await Promise.all([
2407
- resolveDependenciesProps(dependencies, base, values, formApi),
3710
+ resolveDependenciesProps(dependencies, values, formApi),
2408
3711
  runDependenciesTrigger(dependencies, values, formApi)
2409
3712
  ]);
2410
3713
  return resolvedProps;
@@ -2419,67 +3722,17 @@ async function runDependenciesTrigger(dependencies, values, formApi) {
2419
3722
  console.error("[schemx] trigger 执行错误:", error);
2420
3723
  }
2421
3724
  }
2422
- async function resolveDependenciesProps(dependencies, base, values, formApi) {
2423
- const [componentProps, placeholder, required, readonly, disabled, visible, rules] = await Promise.all([
2424
- resolveDependenciesProp({
2425
- condition: dependencies.componentProps,
2426
- values,
2427
- formApi,
2428
- defaultValue: base.componentProps
2429
- }),
2430
- resolveDependenciesProp({
2431
- condition: dependencies.placeholder,
2432
- values,
2433
- formApi,
2434
- defaultValue: base.placeholder
2435
- }),
2436
- resolveDependenciesProp({
2437
- condition: dependencies.required,
2438
- values,
2439
- formApi,
2440
- defaultValue: base.required
2441
- }),
2442
- resolveDependenciesProp({
2443
- condition: dependencies.readonly,
2444
- values,
2445
- formApi,
2446
- defaultValue: base.readonly
2447
- }),
2448
- resolveDependenciesProp({
2449
- condition: dependencies.disabled,
2450
- values,
2451
- formApi,
2452
- defaultValue: base.disabled
2453
- }),
2454
- resolveDependenciesProp({
2455
- condition: dependencies.visible,
2456
- values,
2457
- formApi,
2458
- defaultValue: base.visible
2459
- }),
2460
- resolveDependenciesProp({
2461
- condition: dependencies.rules,
2462
- values,
2463
- formApi,
2464
- defaultValue: base.rules
2465
- })
2466
- ]);
2467
- return {
2468
- componentProps,
2469
- placeholder,
2470
- required,
2471
- readonly,
2472
- disabled,
2473
- visible,
2474
- rules
2475
- };
2476
- }
2477
- async function resolveDependenciesProp(options) {
2478
- const { condition, values, formApi, defaultValue } = options;
2479
- if (condition == null) {
2480
- return defaultValue;
2481
- }
2482
- return resolveCondition(formApi, condition, values, defaultValue);
3725
+ async function resolveDependenciesProps(dependencies, values, formApi) {
3726
+ const entries = await Promise.all(
3727
+ FIELD_DEPENDENCIES_PROP_KEYS.filter((key) => dependencies[key] != null).map(
3728
+ async (key) => {
3729
+ const condition = dependencies[key];
3730
+ const value = await resolveCondition(formApi, condition, values, void 0);
3731
+ return [key, value];
3732
+ }
3733
+ )
3734
+ );
3735
+ return Object.fromEntries(entries);
2483
3736
  }
2484
3737
  async function resolveCondition(formApi, condition, formValues, defaultValue) {
2485
3738
  try {
@@ -2490,118 +3743,124 @@ async function resolveCondition(formApi, condition, formValues, defaultValue) {
2490
3743
  return defaultValue;
2491
3744
  }
2492
3745
  }
3746
+ const dependencyNodeResources = /* @__PURE__ */ new WeakMap();
2493
3747
  function createDependencyEffect(options) {
2494
3748
  var _a;
2495
- const { node, descriptor, context } = options;
3749
+ const { context, node, descriptor } = options;
3750
+ const { formApi, scheduler, compile, commitChildren } = context;
2496
3751
  const resourceScope = options.scope ?? node.scope.child();
2497
- (_a = node.dependencySlot) == null ? void 0 : _a.dispose();
2498
- const slot = {
3752
+ let compileCacheVersion = compile.getCacheVersion();
3753
+ const resources = context.nodeResources;
3754
+ dependencyNodeResources.set(node, resources);
3755
+ (_a = resources.dependencyEffects.get(node.id)) == null ? void 0 : _a.dispose();
3756
+ const effectState = {
2499
3757
  loading: createSignal(false),
2500
3758
  error: createSignal(null),
2501
- version: createSignal(0),
2502
- abortController: createSignal(null),
2503
- run: async () => void 0,
2504
- dispose: () => void 0
2505
- };
2506
- node.dependencyResourceScope = resourceScope;
2507
- slot.run = () => {
2508
- var _a2;
2509
- if (resourceScope.disposed) return Promise.resolve();
2510
- const currentDescriptor = node.descriptor;
2511
- const currentVersion = slot.version.value + 1;
2512
- slot.version.value = currentVersion;
2513
- (_a2 = slot.abortController.value) == null ? void 0 : _a2.abort();
2514
- const controller = new AbortController();
2515
- slot.abortController.value = controller;
2516
- slot.loading.value = true;
2517
- slot.error.value = null;
2518
- return context.scheduler.track(
2519
- (async () => {
2520
- try {
2521
- const childSchemas = await Promise.resolve(
2522
- currentDescriptor.renderer(context.formApi, controller.signal)
2523
- );
2524
- if (resourceScope.disposed || controller.signal.aborted || currentVersion !== slot.version.value) {
2525
- return;
2526
- }
2527
- const descriptors = compileToDescriptors(
2528
- childSchemas,
2529
- context.defaultProps
2530
- );
2531
- context.commitChildren(node, descriptors);
2532
- } catch (cause) {
2533
- if (resourceScope.disposed || controller.signal.aborted || currentVersion !== slot.version.value) {
2534
- return;
2535
- }
2536
- slot.error.value = normalizeError$1(cause);
2537
- } finally {
2538
- if (!resourceScope.disposed && !controller.signal.aborted && currentVersion === slot.version.value) {
2539
- slot.loading.value = false;
2540
- }
2541
- }
2542
- })()
2543
- );
3759
+ version: createSignal(0),
3760
+ abortController: createSignal(null),
3761
+ run: async () => void 0,
3762
+ dispose: () => void 0
2544
3763
  };
2545
- slot.dispose = () => {
2546
- var _a2;
2547
- slot.version.value += 1;
2548
- (_a2 = slot.abortController.value) == null ? void 0 : _a2.abort();
3764
+ resources.dependencyResourceScopes.set(node.id, resourceScope);
3765
+ const taskRunner = createAbortableTaskRunner({
3766
+ scope: resourceScope,
3767
+ scheduler,
3768
+ run: async (signal) => {
3769
+ const currentDescriptor = resources.descriptors.get(node.id);
3770
+ if (!currentDescriptor || !isDependencyDescriptor(currentDescriptor)) {
3771
+ return [];
3772
+ }
3773
+ return await Promise.resolve(currentDescriptor.renderer(formApi, signal));
3774
+ },
3775
+ onStart: (controller) => {
3776
+ effectState.version.value += 1;
3777
+ effectState.abortController.value = controller;
3778
+ effectState.loading.value = true;
3779
+ effectState.error.value = null;
3780
+ },
3781
+ onSuccess: (childSchemas) => {
3782
+ const nextCompileCacheVersion = compile.getCacheVersion();
3783
+ if (nextCompileCacheVersion !== compileCacheVersion) {
3784
+ compile.invalidate();
3785
+ compileCacheVersion = nextCompileCacheVersion;
3786
+ }
3787
+ const descriptors = compile.toDescriptors(childSchemas, "");
3788
+ commitChildren(node, descriptors);
3789
+ },
3790
+ onError: (error) => {
3791
+ effectState.error.value = error;
3792
+ },
3793
+ onSettled: () => {
3794
+ effectState.loading.value = false;
3795
+ }
3796
+ });
3797
+ effectState.run = async () => {
3798
+ if (resourceScope.disposed) return;
3799
+ const currentDescriptor = resources.descriptors.get(node.id);
3800
+ if (!currentDescriptor || !isDependencyDescriptor(currentDescriptor)) {
3801
+ return;
3802
+ }
3803
+ await taskRunner.run();
3804
+ };
3805
+ effectState.dispose = () => {
3806
+ effectState.version.value += 1;
3807
+ taskRunner.dispose();
2549
3808
  resourceScope.dispose();
2550
3809
  };
2551
3810
  resourceScope.add(() => {
2552
3811
  var _a2;
2553
- (_a2 = slot.abortController.value) == null ? void 0 : _a2.abort();
2554
- slot.abortController.value = null;
2555
- if (node.dependencySlot === slot) {
2556
- node.dependencySlot = null;
3812
+ (_a2 = effectState.abortController.value) == null ? void 0 : _a2.abort();
3813
+ effectState.abortController.value = null;
3814
+ if (resources.dependencyEffects.get(node.id) === effectState) {
3815
+ resources.dependencyEffects.delete(node.id);
2557
3816
  }
2558
- if (node.dependencyResourceScope === resourceScope) {
2559
- node.dependencyResourceScope = null;
3817
+ if (resources.dependencyResourceScopes.get(node.id) === resourceScope) {
3818
+ resources.dependencyResourceScopes.delete(node.id);
2560
3819
  }
2561
3820
  });
2562
- if (descriptor.trigger.length > 0) {
2563
- setupTriggerSubscription(
2564
- descriptor.trigger,
2565
- context.formApi,
2566
- () => slot.run(),
2567
- resourceScope
2568
- );
2569
- }
2570
- node.dependencySlot = slot;
2571
- void slot.run().catch((runError) => {
2572
- console.error("DependencyEffectSlot initial run error:", runError);
3821
+ setupTriggerSubscription(
3822
+ descriptor.triggerFields,
3823
+ formApi,
3824
+ () => effectState.run(),
3825
+ resourceScope,
3826
+ scheduler,
3827
+ `dependency:${node.id}:trigger`
3828
+ );
3829
+ resources.dependencyEffects.set(node.id, effectState);
3830
+ void effectState.run().catch((runError) => {
3831
+ console.error("DependencyEffectState initial run error:", runError);
2573
3832
  });
2574
- return slot;
3833
+ return effectState;
2575
3834
  }
2576
- function setupTriggerSubscription(triggers, formApi, run, scope) {
3835
+ function setupTriggerSubscription(triggers, formApi, run, scope, scheduler, taskId) {
2577
3836
  let isFirstRun = true;
2578
- let pendingRun = false;
2579
3837
  const disposeEffect = createSignalEffect(() => {
2580
- void formApi.getValues(triggers);
2581
- if (!isFirstRun && !pendingRun) {
2582
- pendingRun = true;
2583
- queueMicrotask(() => {
2584
- pendingRun = false;
2585
- if (scope.disposed) return;
2586
- run().catch((runError) => {
2587
- console.error("DependencyEffectSlot trigger run error:", runError);
2588
- });
3838
+ void formApi.getValues([...triggers]);
3839
+ if (!isFirstRun) {
3840
+ scheduler.schedule({
3841
+ id: taskId,
3842
+ priority: "normal",
3843
+ scope,
3844
+ run,
3845
+ onError: (runError) => {
3846
+ console.error("DependencyEffectState trigger run error:", runError);
3847
+ }
2589
3848
  });
2590
3849
  }
2591
3850
  isFirstRun = false;
2592
3851
  });
2593
3852
  scope.add(disposeEffect);
2594
3853
  }
2595
- function normalizeError$1(cause) {
2596
- return cause instanceof Error ? cause : new Error(String(cause));
2597
- }
2598
3854
  class RuntimeFieldRegistry {
2599
3855
  constructor() {
2600
3856
  __publicField(this, "fields", /* @__PURE__ */ new Map());
2601
3857
  }
2602
3858
  register(entry) {
2603
3859
  const key = entry.name;
2604
- this.fields.set(key, entry);
3860
+ this.fields.set(key, {
3861
+ name: entry.name,
3862
+ node: entry.node
3863
+ });
2605
3864
  }
2606
3865
  unregister(name, node) {
2607
3866
  const key = name;
@@ -2623,30 +3882,30 @@ function createFieldRegistry() {
2623
3882
  return new RuntimeFieldRegistry();
2624
3883
  }
2625
3884
  function createValidationEffect(options) {
2626
- const { name, fieldModel, scope, context } = options;
3885
+ const { context, name, effectiveSchema, scope } = options;
2627
3886
  const taskScheduler = context.scheduler;
2628
3887
  const registered = createSignal(false);
2629
- const validating = createSignal(false);
2630
3888
  let registrationVersion = 0;
2631
3889
  const readValidationProps = () => {
2632
- const snapshot = fieldModel.snapshot.value;
3890
+ const effective = effectiveSchema.value;
2633
3891
  return {
2634
- visible: snapshot.visible,
2635
- readonly: snapshot.readonly,
2636
- disabled: snapshot.disabled,
2637
- label: snapshot.label,
2638
- rules: snapshot.rules
3892
+ visible: effective.visible,
3893
+ readonly: effective.readonly,
3894
+ disabled: effective.disabled,
3895
+ label: effective.label,
3896
+ rules: effective.rules
2639
3897
  };
2640
3898
  };
2641
3899
  const applyRegistration = (snapshot) => {
2642
3900
  const { visible, readonly, disabled, label, rules } = snapshot;
2643
- if (!visible || readonly || disabled || !rules) {
3901
+ if (!visible || readonly || disabled || !hasRules(rules)) {
2644
3902
  context.instance.unregisterRules(name);
2645
3903
  context.instance.setFieldError(name, []);
2646
3904
  registered.value = false;
2647
3905
  return;
2648
3906
  }
2649
- context.instance.registerRules(name, rules, `${label}为必填项`);
3907
+ const normalizedRules = rules ?? [];
3908
+ context.instance.registerRules(name, normalizedRules, `${label}为必填项`);
2650
3909
  registered.value = true;
2651
3910
  };
2652
3911
  const scheduleRegistration = (snapshot) => {
@@ -2673,25 +3932,17 @@ function createValidationEffect(options) {
2673
3932
  scheduleRegistration(readValidationProps());
2674
3933
  });
2675
3934
  scope.add(disposeEffect);
2676
- const validate = async () => {
2677
- validating.value = true;
2678
- try {
2679
- const result = await context.instance.validateField(name);
2680
- return result;
2681
- } finally {
2682
- validating.value = false;
2683
- }
2684
- };
2685
3935
  const dispose = () => {
2686
3936
  scope.dispose();
2687
3937
  };
2688
3938
  return {
2689
3939
  registered,
2690
- validating,
2691
- validate,
2692
3940
  dispose
2693
3941
  };
2694
3942
  }
3943
+ function hasRules(rules) {
3944
+ return Array.isArray(rules) ? rules.length > 0 : Boolean(rules);
3945
+ }
2695
3946
  function createLifecycleBus(initialListener) {
2696
3947
  const listeners = /* @__PURE__ */ new Set();
2697
3948
  if (initialListener) {
@@ -2780,139 +4031,6 @@ function createLifecycleBus(initialListener) {
2780
4031
  };
2781
4032
  }
2782
4033
  const createLifecycle = createLifecycleBus;
2783
- function defaultGetChildren(node) {
2784
- return node.children;
2785
- }
2786
- function findNodeBFS(tree, predicate, options = {}) {
2787
- const getChildren = options.getChildren ?? defaultGetChildren;
2788
- const queue = Array.isArray(tree) ? [...tree] : [tree];
2789
- let index = 0;
2790
- while (index < queue.length) {
2791
- const node = queue[index];
2792
- index++;
2793
- if (predicate(node)) {
2794
- return node;
2795
- }
2796
- const children = getChildren(node);
2797
- if (children == null ? void 0 : children.length) {
2798
- queue.push(...children);
2799
- }
2800
- }
2801
- return void 0;
2802
- }
2803
- function hasDescriptor(node) {
2804
- return node.type !== "root";
2805
- }
2806
- function isRootRuntimeNode(node) {
2807
- return node.type === "root";
2808
- }
2809
- function isFieldRuntimeNode(node) {
2810
- return (node == null ? void 0 : node.type) === "field";
2811
- }
2812
- function isGroupRuntimeNode(node) {
2813
- return (node == null ? void 0 : node.type) === "group";
2814
- }
2815
- function isDependencyRuntimeNode(node) {
2816
- return (node == null ? void 0 : node.type) === "dependency";
2817
- }
2818
- function isContainerRuntimeNode(node) {
2819
- return node.type === "root" || node.type === "group" || node.type === "dependency";
2820
- }
2821
- function getChildRuntimeNodes(node) {
2822
- if (isRootRuntimeNode(node) || isGroupRuntimeNode(node)) {
2823
- return node.childNodes;
2824
- }
2825
- if (isDependencyRuntimeNode(node)) {
2826
- return node.dynamicChildNodes;
2827
- }
2828
- return [];
2829
- }
2830
- function setChildRuntimeNodes(node, children) {
2831
- if (isRootRuntimeNode(node) || isGroupRuntimeNode(node)) {
2832
- node.childNodes = children;
2833
- return;
2834
- }
2835
- if (isDependencyRuntimeNode(node)) {
2836
- node.dynamicChildNodes = children;
2837
- return;
2838
- }
2839
- }
2840
- function findFieldRuntimeNode(root, name) {
2841
- return findNodeBFS(
2842
- root,
2843
- (node) => isFieldRuntimeNode(node) && node.descriptor.name === name,
2844
- {
2845
- getChildren: (node) => getChildRuntimeNodes(node)
2846
- }
2847
- );
2848
- }
2849
- class RuntimeReconciler {
2850
- constructor(runtimeNodeManager) {
2851
- __publicField(this, "runtimeNodeManager");
2852
- this.runtimeNodeManager = runtimeNodeManager;
2853
- }
2854
- /**
2855
- * 将容器 RuntimeNode 的子节点更新为目标 descriptor 列表。
2856
- *
2857
- * @param parentNode - 承载子节点的 RuntimeNode。
2858
- * @param descriptors - 新一轮编译后的子节点描述符。
2859
- * @returns 子节点结构是否发生可观测变化(新增、移除、类型变更或子树变动)。
2860
- *
2861
- * @remarks
2862
- * 同 key 且同 type 的 RuntimeNode 会被复用;不同 type 即使 key 相同也会重建。
2863
- * 新子节点会先提交到 parent,再销毁被移除的旧节点,避免 cleanup 或视图投影
2864
- * 期间仍读取到过期结构。`viewRevision` 由外层 commit boundary 统一推进。
2865
- */
2866
- reconcileChildren(parentNode, descriptors) {
2867
- return this.reconcileChildrenTree(parentNode, descriptors);
2868
- }
2869
- reconcileChildrenTree(parentNode, descriptors) {
2870
- const previousByKey = new Map(
2871
- getChildRuntimeNodes(parentNode).map((node) => [node.key, node])
2872
- );
2873
- const next = [];
2874
- const groups = [];
2875
- let changed = false;
2876
- for (const descriptor of descriptors) {
2877
- const existingNode = previousByKey.get(descriptor.key);
2878
- if (existingNode && existingNode.type === descriptor.type) {
2879
- previousByKey.delete(descriptor.key);
2880
- existingNode.parent = parentNode;
2881
- this.runtimeNodeManager.update(existingNode, descriptor);
2882
- next.push(existingNode);
2883
- if (isGroupDescriptor(descriptor)) {
2884
- groups.push({ node: existingNode, descriptor });
2885
- }
2886
- continue;
2887
- }
2888
- changed = true;
2889
- const node = this.runtimeNodeManager.create(descriptor, parentNode);
2890
- this.runtimeNodeManager.mount(node);
2891
- next.push(node);
2892
- if (isGroupDescriptor(descriptor)) {
2893
- groups.push({ node, descriptor });
2894
- }
2895
- }
2896
- setChildRuntimeNodes(parentNode, next);
2897
- for (const { node, descriptor } of groups) {
2898
- if (isGroupDescriptor(descriptor)) {
2899
- if (this.reconcileChildrenTree(node, descriptor.children)) {
2900
- changed = true;
2901
- }
2902
- }
2903
- }
2904
- if (previousByKey.size > 0) {
2905
- changed = true;
2906
- }
2907
- for (const removed of previousByKey.values()) {
2908
- this.runtimeNodeManager.disposeTree(removed);
2909
- }
2910
- return changed;
2911
- }
2912
- }
2913
- function createReconciler(runtimeNodeManager) {
2914
- return new RuntimeReconciler(runtimeNodeManager);
2915
- }
2916
4034
  function createScope() {
2917
4035
  let disposed = false;
2918
4036
  const cleanupRecords = [];
@@ -3000,367 +4118,811 @@ const runCleanup = (cleanup) => {
3000
4118
  function reportRuntimeCleanupError(error) {
3001
4119
  console.error("[Scope] Cleanup error:", error);
3002
4120
  }
3003
- class DefaultRuntimeNodeManager {
3004
- constructor(context) {
3005
- __publicField(this, "nextId", 1);
3006
- __publicField(this, "context");
3007
- __publicField(this, "instance");
3008
- __publicField(this, "fieldRegistry");
3009
- __publicField(this, "lifecycleBus");
3010
- this.context = context;
3011
- this.fieldRegistry = context.fieldRegistry;
3012
- this.instance = context.instance;
3013
- this.lifecycleBus = context.lifecycleBus;
4121
+ function createRootRuntimeNode(options) {
4122
+ return {
4123
+ id: 0,
4124
+ key: "schemx:root",
4125
+ type: "root",
4126
+ parent: null,
4127
+ scope: options.scope,
4128
+ mounted: createSignal(false),
4129
+ disposed: createSignal(false),
4130
+ childNodes: []
4131
+ };
4132
+ }
4133
+ function getChildRuntimeNodes(node) {
4134
+ switch (node.type) {
4135
+ case "root":
4136
+ case "group":
4137
+ return node.childNodes;
4138
+ case "dependency":
4139
+ return node.childNodes;
4140
+ case "field":
4141
+ return [];
3014
4142
  }
3015
- /**
3016
- * 创建透明根 RuntimeNode。
3017
- *
3018
- * @returns root RuntimeNode,不对应任何表单 descriptor。
3019
- */
3020
- createRoot() {
3021
- return {
3022
- id: 0,
3023
- key: "schemx:root",
3024
- type: "root",
3025
- parent: null,
3026
- scope: createScope(),
3027
- disposed: createSignal(false),
3028
- mounted: createSignal(false),
3029
- childNodes: []
4143
+ }
4144
+ function setChildRuntimeNodes(node, children) {
4145
+ switch (node.type) {
4146
+ case "root":
4147
+ case "group":
4148
+ node.childNodes = children;
4149
+ return;
4150
+ case "dependency":
4151
+ node.childNodes = children;
4152
+ return;
4153
+ case "field":
4154
+ return;
4155
+ }
4156
+ }
4157
+ function createFieldRuntimeNode(options) {
4158
+ var _a;
4159
+ return {
4160
+ id: options.id,
4161
+ key: options.key,
4162
+ type: "field",
4163
+ parent: options.parent ?? null,
4164
+ scope: options.scope ?? ((_a = options.parent) == null ? void 0 : _a.scope.child()) ?? createScope(),
4165
+ mounted: createSignal(false),
4166
+ disposed: createSignal(false)
4167
+ };
4168
+ }
4169
+ function createGroupRuntimeNode(options) {
4170
+ var _a;
4171
+ return {
4172
+ id: options.id,
4173
+ key: options.key,
4174
+ type: "group",
4175
+ parent: options.parent ?? null,
4176
+ scope: options.scope ?? ((_a = options.parent) == null ? void 0 : _a.scope.child()) ?? createScope(),
4177
+ mounted: createSignal(false),
4178
+ disposed: createSignal(false),
4179
+ childNodes: []
4180
+ };
4181
+ }
4182
+ function createDependencyRuntimeNode(options) {
4183
+ var _a;
4184
+ return {
4185
+ id: options.id,
4186
+ key: options.key,
4187
+ type: "dependency",
4188
+ parent: options.parent ?? null,
4189
+ scope: options.scope ?? ((_a = options.parent) == null ? void 0 : _a.scope.child()) ?? createScope(),
4190
+ mounted: createSignal(false),
4191
+ disposed: createSignal(false),
4192
+ childNodes: []
4193
+ };
4194
+ }
4195
+ function createRuntimeResources() {
4196
+ return {
4197
+ nodes: /* @__PURE__ */ new Map(),
4198
+ descriptors: /* @__PURE__ */ new Map(),
4199
+ fieldStates: /* @__PURE__ */ new Map(),
4200
+ viewStates: /* @__PURE__ */ new Map(),
4201
+ childrenStates: /* @__PURE__ */ new Map(),
4202
+ dependencyEffects: /* @__PURE__ */ new Map(),
4203
+ fieldResourceScopes: /* @__PURE__ */ new Map(),
4204
+ fieldDynamicPropScopes: /* @__PURE__ */ new Map(),
4205
+ dependencyResourceScopes: /* @__PURE__ */ new Map()
4206
+ };
4207
+ }
4208
+ function deleteNodeResources(resources, nodeId) {
4209
+ resources.nodes.delete(nodeId);
4210
+ resources.descriptors.delete(nodeId);
4211
+ resources.fieldStates.delete(nodeId);
4212
+ resources.viewStates.delete(nodeId);
4213
+ resources.childrenStates.delete(nodeId);
4214
+ resources.dependencyEffects.delete(nodeId);
4215
+ resources.fieldResourceScopes.delete(nodeId);
4216
+ resources.fieldDynamicPropScopes.delete(nodeId);
4217
+ resources.dependencyResourceScopes.delete(nodeId);
4218
+ }
4219
+ function createRuntimeNodeManager(context) {
4220
+ const resources = context.nodeResources;
4221
+ let nextId = 1;
4222
+ const manager = {
4223
+ resources,
4224
+ nodes: resources.nodes,
4225
+ createRoot,
4226
+ create,
4227
+ createNode,
4228
+ getNode,
4229
+ traverse,
4230
+ insertChild,
4231
+ replaceChildren,
4232
+ removeChild,
4233
+ removeSubtree
4234
+ };
4235
+ return manager;
4236
+ function createRoot() {
4237
+ const node = createRootRuntimeNode({ scope: createScope() });
4238
+ registerNode(resources, node);
4239
+ ensureChildrenState(node);
4240
+ return node;
4241
+ }
4242
+ function create(descriptor, parent) {
4243
+ const node = createNode({
4244
+ type: descriptor.type,
4245
+ key: descriptor.key,
4246
+ scope: parent.scope.child()
4247
+ });
4248
+ node.parent = parent;
4249
+ if (node.type !== "field") {
4250
+ ensureChildrenState(node);
4251
+ }
4252
+ return node;
4253
+ }
4254
+ function createNode(createOptions) {
4255
+ const nodeId = nextId++;
4256
+ const scope = createOptions.scope ?? createScope();
4257
+ const baseOptions = {
4258
+ id: nodeId,
4259
+ key: createOptions.key,
4260
+ scope
3030
4261
  };
4262
+ let node = {};
4263
+ if (createOptions.type === "field") {
4264
+ node = createFieldRuntimeNode(baseOptions);
4265
+ } else if (createOptions.type === "group") {
4266
+ node = createGroupRuntimeNode(baseOptions);
4267
+ } else {
4268
+ node = createDependencyRuntimeNode(baseOptions);
4269
+ }
4270
+ registerNode(resources, node);
4271
+ if (node.type !== "field") {
4272
+ ensureChildrenState(node);
4273
+ }
4274
+ return node;
3031
4275
  }
3032
- /**
3033
- * 根据 descriptor 创建单个未挂载 RuntimeNode。
3034
- *
3035
- * @param descriptor - 编译后的表单节点描述符。
3036
- * @param parent - 新 RuntimeNode 所属的容器 RuntimeNode。
3037
- */
3038
- create(descriptor, parent) {
3039
- if (descriptor.type === "field") {
3040
- return this.createField(descriptor, parent);
4276
+ function getNode(nodeId) {
4277
+ return resources.nodes.get(nodeId);
4278
+ }
4279
+ function traverse(root2) {
4280
+ const result = [];
4281
+ const visit = (node) => {
4282
+ result.push(node);
4283
+ for (const child of getChildRuntimeNodes(node)) {
4284
+ visit(child);
4285
+ }
4286
+ };
4287
+ visit(root2);
4288
+ return result;
4289
+ }
4290
+ function insertChild(parent, child, index = getChildRuntimeNodes(parent).length) {
4291
+ if (child.parent) {
4292
+ detachChild(child.parent, child);
4293
+ }
4294
+ const currentChildren = getChildRuntimeNodes(parent).filter(
4295
+ (current) => current !== child
4296
+ );
4297
+ const nextChildren = [...currentChildren];
4298
+ const normalizedIndex = Math.max(0, Math.min(index, nextChildren.length));
4299
+ nextChildren.splice(normalizedIndex, 0, child);
4300
+ child.parent = parent;
4301
+ setChildren(parent, nextChildren);
4302
+ }
4303
+ function replaceChildren(parent, children) {
4304
+ const currentChildren = getChildRuntimeNodes(parent);
4305
+ const nextChildren = Array.from(new Set(children));
4306
+ const nextSet = new Set(nextChildren);
4307
+ for (const child of currentChildren) {
4308
+ if (!nextSet.has(child)) {
4309
+ child.parent = null;
4310
+ }
4311
+ }
4312
+ for (const child of nextChildren) {
4313
+ if (child.parent && child.parent !== parent) {
4314
+ detachChild(child.parent, child);
4315
+ }
4316
+ child.parent = parent;
4317
+ }
4318
+ setChildren(parent, nextChildren);
4319
+ }
4320
+ function removeChild(parent, child) {
4321
+ detachChild(parent, child);
4322
+ }
4323
+ function removeSubtree(node) {
4324
+ for (const child of getChildRuntimeNodes(node)) {
4325
+ removeSubtree(child);
4326
+ }
4327
+ if (node.type !== "field") {
4328
+ setChildren(node, []);
4329
+ }
4330
+ if (node.parent) {
4331
+ detachChild(node.parent, node);
4332
+ }
4333
+ node.parent = null;
4334
+ node.disposed.value = true;
4335
+ node.scope.dispose();
4336
+ deleteNodeResources(resources, node.id);
4337
+ }
4338
+ function detachChild(parent, child) {
4339
+ const nextChildren = getChildRuntimeNodes(parent).filter(
4340
+ (current) => current !== child
4341
+ );
4342
+ setChildren(parent, nextChildren);
4343
+ if (child.parent === parent) {
4344
+ child.parent = null;
4345
+ }
4346
+ }
4347
+ function ensureChildrenState(node) {
4348
+ let state = resources.childrenStates.get(node.id);
4349
+ if (!state) {
4350
+ state = {
4351
+ children: createSignal(
4352
+ getChildRuntimeNodes(node)
4353
+ )
4354
+ };
4355
+ resources.childrenStates.set(node.id, state);
4356
+ }
4357
+ return state;
4358
+ }
4359
+ function setChildren(node, children) {
4360
+ setChildRuntimeNodes(node, children);
4361
+ ensureChildrenState(node).children.value = children;
4362
+ }
4363
+ }
4364
+ function registerNode(resources, node) {
4365
+ resources.nodes.set(node.id, node);
4366
+ }
4367
+ function createFieldNodeViewState(viewSchema, nodeKey, nodeId, diagnostics) {
4368
+ return {
4369
+ view: createComputed(() => {
4370
+ const schema = viewSchema.value;
4371
+ const meta = diagnostics == null ? void 0 : diagnostics.value;
4372
+ return {
4373
+ ...schema,
4374
+ key: nodeKey ?? "",
4375
+ placeholder: sanitizePlaceholder(schema.placeholder ?? ""),
4376
+ componentProps: sanitizeComponentProps(schema.componentProps ?? {}),
4377
+ debug: buildFieldDebugMeta(nodeId, meta)
4378
+ };
4379
+ })
4380
+ };
4381
+ }
4382
+ function createGroupViewState(groupSchema, childrenView, nodeKey, nodeId) {
4383
+ return {
4384
+ view: createComputed(() => {
4385
+ return {
4386
+ ...groupSchema,
4387
+ key: nodeKey ?? "",
4388
+ children: childrenView.value,
4389
+ debug: buildNodeDebugMeta(nodeId, "group", false, false)
4390
+ };
4391
+ })
4392
+ };
4393
+ }
4394
+ function createDependencyViewState(childrenView) {
4395
+ return {
4396
+ view: createComputed(() => childrenView.value)
4397
+ };
4398
+ }
4399
+ function createChildrenViewState(childrenSignal, resources) {
4400
+ return createComputed(() => {
4401
+ const result = [];
4402
+ for (const child of childrenSignal.value) {
4403
+ const view = readRuntimeNodeView(child, resources);
4404
+ if (view == null) {
4405
+ continue;
4406
+ }
4407
+ if (Array.isArray(view)) {
4408
+ result.push(...view);
4409
+ } else {
4410
+ result.push(view);
4411
+ }
4412
+ }
4413
+ return result;
4414
+ });
4415
+ }
4416
+ function readRuntimeNodeView(node, resources = ((_a) => (_a = maybeUseSchemxContext()) == null ? void 0 : _a.nodeResources)()) {
4417
+ if (node.disposed.value) {
4418
+ return null;
4419
+ }
4420
+ if (!resources) {
4421
+ return null;
4422
+ }
4423
+ const viewState = resources.viewStates.get(node.id);
4424
+ if (node.type === "field") {
4425
+ return hasNodeView(viewState) ? viewState.view.value ?? null : null;
4426
+ }
4427
+ if (node.type === "group") {
4428
+ return hasNodeView(viewState) ? viewState.view.value ?? null : null;
4429
+ }
4430
+ if (node.type === "dependency") {
4431
+ return hasNodeView(viewState) ? viewState.view.value ?? [] : [];
4432
+ }
4433
+ return null;
4434
+ }
4435
+ function hasNodeView(viewState) {
4436
+ return viewState != null && "view" in viewState;
4437
+ }
4438
+ function createRootViewState(childrenSignal, resources) {
4439
+ return {
4440
+ viewSchemas: createChildrenViewState(childrenSignal, resources)
4441
+ };
4442
+ }
4443
+ function readRootViewSchemas(root2) {
4444
+ return root2.viewSchemas.value;
4445
+ }
4446
+ function buildFieldDebugMeta(nodeId, diagnostics) {
4447
+ var _a;
4448
+ return {
4449
+ runtimeNodeId: nodeId ?? 0,
4450
+ runtimeNodeType: "field",
4451
+ hasRuntimeState: true,
4452
+ hasDependencyEffect: false,
4453
+ lastUpdatedBy: diagnostics == null ? void 0 : diagnostics.lastUpdatedBy,
4454
+ overriddenKeys: diagnostics == null ? void 0 : diagnostics.overriddenKeys,
4455
+ error: ((_a = diagnostics == null ? void 0 : diagnostics.error) == null ? void 0 : _a.message) ?? null
4456
+ };
4457
+ }
4458
+ function buildNodeDebugMeta(nodeId, runtimeNodeType, hasRuntimeState, hasDependencyEffect) {
4459
+ return {
4460
+ runtimeNodeId: nodeId ?? 0,
4461
+ runtimeNodeType,
4462
+ hasRuntimeState,
4463
+ hasDependencyEffect
4464
+ };
4465
+ }
4466
+ function sanitizePlaceholder(value) {
4467
+ if (!value) {
4468
+ return "";
4469
+ }
4470
+ return value.length > 1e3 ? value.slice(0, 1e3) : value;
4471
+ }
4472
+ function sanitizeComponentProps(props, depth = 0) {
4473
+ if (depth > 10) {
4474
+ return {};
4475
+ }
4476
+ const result = {};
4477
+ for (const key of Object.keys(props)) {
4478
+ if (!isValidPropKey(key)) {
4479
+ continue;
3041
4480
  }
3042
- if (descriptor.type === "group") {
3043
- return this.createGroup(descriptor, parent);
4481
+ const value = props[key];
4482
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
4483
+ result[key] = sanitizeComponentProps(
4484
+ value,
4485
+ depth + 1
4486
+ );
4487
+ } else {
4488
+ result[key] = value;
3044
4489
  }
3045
- if (descriptor.type === "dependency") {
3046
- return this.createDependency(descriptor, parent);
4490
+ }
4491
+ return result;
4492
+ }
4493
+ function isValidPropKey(key) {
4494
+ if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key)) {
4495
+ return true;
4496
+ }
4497
+ return /^[a-zA-Z0-9_-]+$/.test(key);
4498
+ }
4499
+ function createRootRuntimeViewState(root2, resources) {
4500
+ const childrenState = getChildrenState(root2, resources);
4501
+ const viewState = createRootViewState(
4502
+ childrenState.children,
4503
+ resources
4504
+ );
4505
+ resources.viewStates.set(root2.id, viewState);
4506
+ return viewState;
4507
+ }
4508
+ function createRuntimeViewState(node, descriptor, resources) {
4509
+ if (node.type === "field" && descriptor.type === "field") {
4510
+ return createFieldRuntimeViewState(node, descriptor, resources);
4511
+ }
4512
+ if (node.type === "group" && descriptor.type === "group") {
4513
+ return createGroupRuntimeViewState(node, descriptor, resources);
4514
+ }
4515
+ if (node.type === "dependency" && descriptor.type === "dependency") {
4516
+ return createDependencyRuntimeViewState(node, descriptor, resources);
4517
+ }
4518
+ throw new Error(
4519
+ `[schemx] Cannot create viewState for node "${node.key}" with descriptor "${descriptor.type}".`
4520
+ );
4521
+ }
4522
+ function updateRuntimeViewState(node, descriptor, resources) {
4523
+ return createRuntimeViewState(node, descriptor, resources);
4524
+ }
4525
+ function deleteRuntimeViewState(node, resources) {
4526
+ resources.viewStates.delete(node.id);
4527
+ }
4528
+ function createFieldRuntimeViewState(node, descriptor, resources) {
4529
+ const runtimeState = resources.fieldStates.get(node.id);
4530
+ if (!runtimeState) {
4531
+ throw new Error(`[schemx] fieldState is required for node "${node.key}"`);
4532
+ }
4533
+ const viewState = createFieldNodeViewState(
4534
+ runtimeState.viewSchema,
4535
+ node.key,
4536
+ node.id,
4537
+ runtimeState.diagnostics
4538
+ );
4539
+ resources.viewStates.set(node.id, viewState);
4540
+ return viewState;
4541
+ }
4542
+ function createGroupRuntimeViewState(node, descriptor, resources) {
4543
+ const viewState = createGroupViewState(
4544
+ descriptor.staticSchema,
4545
+ createChildrenViewState(
4546
+ getChildrenState(node, resources).children,
4547
+ resources
4548
+ ),
4549
+ node.key,
4550
+ node.id
4551
+ );
4552
+ resources.viewStates.set(node.id, viewState);
4553
+ return viewState;
4554
+ }
4555
+ function createDependencyRuntimeViewState(node, _descriptor, resources) {
4556
+ const viewState = createDependencyViewState(
4557
+ createChildrenViewState(
4558
+ getChildrenState(node, resources).children,
4559
+ resources
4560
+ )
4561
+ );
4562
+ resources.viewStates.set(node.id, viewState);
4563
+ return viewState;
4564
+ }
4565
+ function getChildrenState(node, resources) {
4566
+ const childrenState = resources.childrenStates.get(node.id);
4567
+ if (!childrenState) {
4568
+ throw new Error(`[schemx] childrenState is required for node "${node.key}"`);
4569
+ }
4570
+ return childrenState;
4571
+ }
4572
+ function createRuntimeLifecycle(context) {
4573
+ const resources = context.nodeResources;
4574
+ const bus = context.lifecycleBus;
4575
+ return {
4576
+ mount,
4577
+ update,
4578
+ unmount,
4579
+ unmountSubtree
4580
+ };
4581
+ function mount(node, descriptor) {
4582
+ resources.descriptors.set(node.id, descriptor);
4583
+ bus.emitBeforeMount(node);
4584
+ mountRuntimeResources(node, descriptor);
4585
+ node.mounted.value = true;
4586
+ bus.emitMount(node);
4587
+ }
4588
+ function update(node, previousDescriptor, nextDescriptor) {
4589
+ if (node.type !== nextDescriptor.type) {
4590
+ throw new Error(
4591
+ `unexpected descriptor type: node ${node.type} cannot update with ${nextDescriptor.type}`
4592
+ );
3047
4593
  }
3048
- throwUnknownDescriptor(descriptor);
4594
+ const previousNode = { ...node };
4595
+ bus.emitBeforeUpdate(node, previousNode);
4596
+ resources.descriptors.set(node.id, nextDescriptor);
4597
+ updateRuntimeResources(node, previousDescriptor, nextDescriptor);
4598
+ bus.emitUpdate(node, previousNode);
4599
+ bus.emitUpdated(node, previousNode);
3049
4600
  }
3050
- /**
3051
- * 挂载单个 RuntimeNode 的运行期资源。
3052
- *
3053
- * @param node - 要挂载的 RuntimeNode。
3054
- *
3055
- * @remarks
3056
- * Group RuntimeNode 只表示结构,不会创建领域资源;Field 和 Dependency 会在这里
3057
- * 创建各自的模型、effect 与资源 scope。
3058
- */
3059
- mount(node) {
3060
- if (!hasDescriptor(node)) {
4601
+ function unmountSubtree(node) {
4602
+ if (node.disposed.value) {
3061
4603
  return;
3062
4604
  }
3063
- this.lifecycleBus.emitBeforeMount(node);
3064
- switch (node.type) {
3065
- case "field":
3066
- this.mountField(node);
3067
- break;
3068
- case "group":
3069
- this.mountGroup(node);
3070
- break;
3071
- case "dependency":
3072
- this.mountDependency(node);
3073
- break;
4605
+ for (const child of getChildRuntimeNodes(node)) {
4606
+ unmountSubtree(child);
3074
4607
  }
3075
- node.mounted.value = true;
3076
- this.lifecycleBus.emitMount(node);
4608
+ unmount(node);
3077
4609
  }
3078
- /**
3079
- * 更新单个 RuntimeNode descriptor 快照和运行期资源。
3080
- *
3081
- * @param node - 要更新的 RuntimeNode。
3082
- * @param next - 更新后的表单 descriptor。
3083
- *
3084
- * @remarks
3085
- * descriptor 快照会先写入 RuntimeNode,再由具体 update 分支决定复用还是重启资源。
3086
- * 结构层面的 children reconcile 不在这里处理。
3087
- */
3088
- update(node, next) {
3089
- if (!hasDescriptor(node)) {
4610
+ function unmount(node) {
4611
+ if (node.type === "root") {
3090
4612
  return;
3091
4613
  }
3092
- switch (node.type) {
3093
- case "field": {
3094
- if (!isFieldDescriptor(next)) {
3095
- throwUnexpectedDescriptor(node, next);
3096
- }
3097
- const previousNode = createPreviousRuntimeNodeSnapshot(node);
3098
- this.lifecycleBus.emitBeforeUpdate(node, previousNode);
3099
- node.descriptor = next;
3100
- this.updateField(node, previousNode);
3101
- this.lifecycleBus.emitUpdate(node, previousNode);
3102
- this.lifecycleBus.emitUpdated(node, previousNode);
3103
- break;
3104
- }
3105
- case "group": {
3106
- if (!isGroupDescriptor(next)) {
3107
- throwUnexpectedDescriptor(node, next);
3108
- }
3109
- const previousNode = createPreviousRuntimeNodeSnapshot(node);
3110
- this.lifecycleBus.emitBeforeUpdate(node, previousNode);
3111
- node.descriptor = next;
3112
- this.updateGroup(node, next);
3113
- this.lifecycleBus.emitUpdate(node, previousNode);
3114
- this.lifecycleBus.emitUpdated(node, previousNode);
3115
- break;
3116
- }
3117
- case "dependency": {
3118
- if (!isDependencyDescriptor(next)) {
3119
- throwUnexpectedDescriptor(node, next);
3120
- }
3121
- const previousNode = createPreviousRuntimeNodeSnapshot(node);
3122
- this.lifecycleBus.emitBeforeUpdate(node, previousNode);
3123
- node.descriptor = next;
3124
- this.updateDependency(node, previousNode);
3125
- this.lifecycleBus.emitUpdate(node, previousNode);
3126
- this.lifecycleBus.emitUpdated(node, previousNode);
3127
- break;
3128
- }
3129
- }
4614
+ bus.emitBeforeUnmount(node);
4615
+ unmountRuntimeResources(node);
4616
+ bus.emitUnmount(node);
3130
4617
  }
3131
- /**
3132
- * 卸载单个 RuntimeNode 的运行期资源。
3133
- *
3134
- * @param node - 要卸载的 RuntimeNode。
3135
- *
3136
- * @remarks
3137
- * 这个方法不递归销毁子节点;需要销毁整棵子树时使用 `disposeTree`。
3138
- */
3139
- unmount(node) {
3140
- if (!hasDescriptor(node)) {
4618
+ function mountRuntimeResources(node, descriptor) {
4619
+ if (node.type === "field" && descriptor.type === "field") {
4620
+ mountFieldResources(node, descriptor);
4621
+ return;
4622
+ }
4623
+ if (node.type === "group" && descriptor.type === "group") {
4624
+ mountGroupResources(node, descriptor);
3141
4625
  return;
3142
4626
  }
3143
- switch (node.type) {
3144
- case "field":
3145
- this.unmountField(node);
3146
- break;
3147
- case "group":
3148
- this.unmountGroup(node);
3149
- break;
3150
- case "dependency":
3151
- this.unmountDependency(node);
3152
- break;
4627
+ if (node.type === "dependency" && descriptor.type === "dependency") {
4628
+ mountDependencyResources(node, descriptor);
3153
4629
  }
3154
- node.mounted.value = false;
3155
4630
  }
3156
- /**
3157
- * 递归销毁 RuntimeNode 子树。
3158
- *
3159
- * @param node - 要销毁的子树根 RuntimeNode。
3160
- *
3161
- * @remarks
3162
- * 销毁顺序是:标记 disposed、递归销毁 runtime 子节点、卸载自身领域资源、
3163
- * 释放 RuntimeNode scope、断开 parent。这样可以确保子资源先于父资源释放。
3164
- */
3165
- disposeTree(node) {
3166
- if (node.disposed.value) {
4631
+ function updateRuntimeResources(node, previousDescriptor, nextDescriptor) {
4632
+ if (node.type === "field" && nextDescriptor.type === "field") {
4633
+ updateFieldResources(
4634
+ node,
4635
+ nextDescriptor,
4636
+ (previousDescriptor == null ? void 0 : previousDescriptor.type) === "field" ? previousDescriptor : void 0
4637
+ );
3167
4638
  return;
3168
4639
  }
3169
- if (node.type !== "root") {
3170
- this.lifecycleBus.emitBeforeUnmount(node);
4640
+ if (node.type === "group" && nextDescriptor.type === "group") {
4641
+ mountGroupResources(node, nextDescriptor);
4642
+ return;
3171
4643
  }
3172
- node.disposed.value = true;
3173
- if (isContainerRuntimeNode(node)) {
3174
- for (const child of getChildRuntimeNodes(node)) {
3175
- this.disposeTree(child);
3176
- }
3177
- setChildRuntimeNodes(node, []);
4644
+ if (node.type === "dependency" && nextDescriptor.type === "dependency") {
4645
+ updateDependencyResources(
4646
+ node,
4647
+ nextDescriptor,
4648
+ (previousDescriptor == null ? void 0 : previousDescriptor.type) === "dependency" ? previousDescriptor : void 0
4649
+ );
3178
4650
  }
3179
- this.unmount(node);
3180
- node.scope.dispose();
3181
- node.parent = null;
3182
- if (node.type !== "root") {
3183
- this.lifecycleBus.emitUnmount(node);
4651
+ }
4652
+ function mountFieldResources(node, descriptor) {
4653
+ const runtimeState = createFieldRuntimeState({
4654
+ nodeId: node.id,
4655
+ key: node.key,
4656
+ descriptor
4657
+ });
4658
+ applyFieldInitialValue(descriptor);
4659
+ resources.fieldStates.set(node.id, runtimeState);
4660
+ createRuntimeViewState(node, descriptor, resources);
4661
+ context.fieldRegistry.register({ name: descriptor.name, node });
4662
+ recreateFieldEffectScopes(node, descriptor, runtimeState);
4663
+ }
4664
+ function updateFieldResources(node, descriptor, previousDescriptor) {
4665
+ const runtimeState = resources.fieldStates.get(node.id);
4666
+ if (!runtimeState) {
4667
+ mountFieldResources(node, descriptor);
4668
+ return;
4669
+ }
4670
+ if (previousDescriptor && previousDescriptor.name !== descriptor.name) {
4671
+ context.fieldRegistry.unregister(previousDescriptor.name, node);
3184
4672
  }
4673
+ setFieldStaticSchema(runtimeState, descriptor);
4674
+ updateRuntimeViewState(node, descriptor, resources);
4675
+ context.fieldRegistry.register({ name: descriptor.name, node });
4676
+ recreateFieldEffectScopes(node, descriptor, runtimeState);
3185
4677
  }
3186
- createField(descriptor, parent) {
3187
- const fieldModel = createFieldModel(descriptor);
3188
- const node = {
3189
- id: this.nextId++,
3190
- key: descriptor.key,
3191
- type: descriptor.type,
3192
- parent,
3193
- scope: parent.scope.child(),
3194
- disposed: createSignal(false),
3195
- mounted: createSignal(false),
4678
+ function recreateFieldEffectScopes(node, descriptor, runtimeState) {
4679
+ var _a, _b;
4680
+ (_a = resources.fieldResourceScopes.get(node.id)) == null ? void 0 : _a.dispose();
4681
+ (_b = resources.fieldDynamicPropScopes.get(node.id)) == null ? void 0 : _b.dispose();
4682
+ const validationScope = node.scope.child();
4683
+ const dynamicPropScope = node.scope.child();
4684
+ resources.fieldResourceScopes.set(node.id, validationScope);
4685
+ resources.fieldDynamicPropScopes.set(node.id, dynamicPropScope);
4686
+ validationScope.add(() => {
4687
+ if (resources.fieldResourceScopes.get(node.id) === validationScope) {
4688
+ resources.fieldResourceScopes.delete(node.id);
4689
+ }
4690
+ });
4691
+ dynamicPropScope.add(() => {
4692
+ if (resources.fieldDynamicPropScopes.get(node.id) === dynamicPropScope) {
4693
+ resources.fieldDynamicPropScopes.delete(node.id);
4694
+ }
4695
+ });
4696
+ createValidationEffect({
4697
+ context,
4698
+ name: descriptor.name,
4699
+ effectiveSchema: runtimeState.effectiveSchema,
4700
+ scope: validationScope
4701
+ });
4702
+ createDependenciesEffect({
4703
+ context,
3196
4704
  descriptor,
3197
- fieldModel,
3198
- fieldResourceScope: null,
3199
- fieldDependenciesScope: null
3200
- };
3201
- return node;
4705
+ runtimeState,
4706
+ scope: dynamicPropScope
4707
+ });
3202
4708
  }
3203
- createGroup(descriptor, parent) {
3204
- const node = {
3205
- id: this.nextId++,
3206
- key: descriptor.key,
3207
- type: descriptor.type,
3208
- parent,
3209
- scope: parent.scope.child(),
3210
- disposed: createSignal(false),
3211
- mounted: createSignal(false),
3212
- descriptor,
3213
- childNodes: []
3214
- };
3215
- return node;
4709
+ function mountGroupResources(node, descriptor) {
4710
+ createRuntimeViewState(node, descriptor, resources);
3216
4711
  }
3217
- createDependency(descriptor, parent) {
3218
- const node = {
3219
- id: this.nextId++,
3220
- key: descriptor.key,
3221
- type: descriptor.type,
3222
- parent,
3223
- scope: parent.scope.child(),
3224
- disposed: createSignal(false),
3225
- mounted: createSignal(false),
4712
+ function mountDependencyResources(node, descriptor) {
4713
+ createRuntimeViewState(node, descriptor, resources);
4714
+ createDependencyEffect({
4715
+ context,
4716
+ node,
3226
4717
  descriptor,
3227
- dependencySlot: null,
3228
- dependencyResourceScope: null,
3229
- dynamicChildNodes: []
3230
- };
3231
- return node;
4718
+ scope: node.scope.child()
4719
+ });
3232
4720
  }
3233
- mountField(node) {
3234
- const resourceScope = node.scope.child();
3235
- const model = node.fieldModel;
3236
- if (!model) {
4721
+ function updateDependencyResources(node, descriptor, previousDescriptor) {
4722
+ var _a;
4723
+ createRuntimeViewState(node, descriptor, resources);
4724
+ if (previousDescriptor && hasSameTriggerFields(previousDescriptor.triggerFields, descriptor.triggerFields) && resources.dependencyEffects.has(node.id)) {
3237
4725
  return;
3238
4726
  }
3239
- this.initializeFieldValue(node);
3240
- node.fieldResourceScope = resourceScope;
3241
- this.fieldRegistry.register({
3242
- name: node.descriptor.name,
4727
+ (_a = resources.dependencyResourceScopes.get(node.id)) == null ? void 0 : _a.dispose();
4728
+ createDependencyEffect({
4729
+ context,
3243
4730
  node,
3244
- model
3245
- });
3246
- resourceScope.add(() => {
3247
- this.fieldRegistry.unregister(node.descriptor.name, node);
3248
- if (node.fieldResourceScope === resourceScope) {
3249
- node.fieldResourceScope = null;
3250
- }
4731
+ descriptor,
4732
+ scope: node.scope.child()
3251
4733
  });
3252
- this.mountFieldValidation(node, model, resourceScope);
3253
- this.mountOrRestartFieldDependencies(node, model);
3254
4734
  }
3255
- initializeFieldValue(node) {
3256
- const { name, schema } = node.descriptor;
3257
- if (!Object.hasOwn(schema, "initialValue") || this.instance.getFieldSnapshot(name) !== void 0) {
4735
+ function unmountRuntimeResources(node) {
4736
+ var _a, _b, _c;
4737
+ const descriptor = resources.descriptors.get(node.id);
4738
+ deleteRuntimeViewState(node, resources);
4739
+ if (node.type === "field" && (descriptor == null ? void 0 : descriptor.type) === "field") {
4740
+ context.fieldRegistry.unregister(descriptor.name, node);
4741
+ (_a = resources.fieldResourceScopes.get(node.id)) == null ? void 0 : _a.dispose();
4742
+ (_b = resources.fieldDynamicPropScopes.get(node.id)) == null ? void 0 : _b.dispose();
4743
+ } else if (node.type === "dependency") {
4744
+ (_c = resources.dependencyResourceScopes.get(node.id)) == null ? void 0 : _c.dispose();
4745
+ }
4746
+ }
4747
+ function applyFieldInitialValue(descriptor) {
4748
+ if (!Object.hasOwn(descriptor.staticSchema, "initialValue")) {
4749
+ return;
4750
+ }
4751
+ if (context.instance.getFieldValue(descriptor.name) !== void 0) {
3258
4752
  return;
3259
4753
  }
3260
- const values = {};
3261
- setByPath(values, name, schema.initialValue);
3262
- this.instance.setInitialValues(values);
3263
- this.instance.setFieldValue(name, schema.initialValue);
4754
+ context.instance.setFieldValue(
4755
+ descriptor.name,
4756
+ descriptor.staticSchema.initialValue
4757
+ );
3264
4758
  }
3265
- mountGroup(_node) {
4759
+ }
4760
+ function hasSameTriggerFields(previous, next) {
4761
+ if (previous.length !== next.length) {
4762
+ return false;
3266
4763
  }
3267
- mountDependency(node) {
3268
- createDependencyEffect({
3269
- node,
3270
- descriptor: node.descriptor,
3271
- context: this.context
4764
+ return previous.every((field, index) => isSameNamePath(field, next[index]));
4765
+ }
4766
+ function isSameNamePath(previous, next) {
4767
+ if (next === void 0) {
4768
+ return false;
4769
+ }
4770
+ if (Array.isArray(previous) || Array.isArray(next)) {
4771
+ return Array.isArray(previous) && Array.isArray(next) && previous.length === next.length && previous.every((part, index) => part === next[index]);
4772
+ }
4773
+ return previous === next;
4774
+ }
4775
+ function commitReconcilePlan(parent, plan, options) {
4776
+ const createdByKey = /* @__PURE__ */ new Map();
4777
+ for (const { descriptor } of plan.creates) {
4778
+ const node = options.nodeManager.createNode({
4779
+ type: descriptor.type,
4780
+ key: descriptor.key,
4781
+ scope: parent.scope.child()
3272
4782
  });
4783
+ createdByKey.set(descriptor.key, node);
3273
4784
  }
3274
- updateField(node, previousNode) {
3275
- const model = node.fieldModel;
3276
- if (model && previousNode && previousNode.descriptor.name === node.descriptor.name) {
3277
- updateFieldModel(model, node.descriptor);
3278
- this.fieldRegistry.register({
3279
- name: node.descriptor.name,
3280
- node,
3281
- model
4785
+ const nextChildren = plan.nextChildrenOrder.map((entry) => {
4786
+ if (entry.node) {
4787
+ return entry.node;
4788
+ }
4789
+ const created = createdByKey.get(entry.descriptor.key);
4790
+ if (!created) {
4791
+ throw new Error(
4792
+ `[schemx] Missing created runtime node for descriptor "${entry.descriptor.key}".`
4793
+ );
4794
+ }
4795
+ return created;
4796
+ });
4797
+ for (const { node, previousDescriptor, nextDescriptor } of plan.updates) {
4798
+ options.lifecycle.update(node, previousDescriptor, nextDescriptor);
4799
+ }
4800
+ for (const { descriptor } of plan.creates) {
4801
+ const node = createdByKey.get(descriptor.key);
4802
+ if (!node) {
4803
+ throw new Error(
4804
+ `[schemx] Missing mounted runtime node for descriptor "${descriptor.key}".`
4805
+ );
4806
+ }
4807
+ options.lifecycle.mount(node, descriptor);
4808
+ }
4809
+ options.nodeManager.replaceChildren(parent, nextChildren);
4810
+ for (const { node } of plan.removes) {
4811
+ options.lifecycle.unmountSubtree(node);
4812
+ options.nodeManager.removeSubtree(node);
4813
+ }
4814
+ return nextChildren;
4815
+ }
4816
+ function createReconcilePlan(currentChildren, nextDescriptors, currentDescriptors) {
4817
+ const currentByKey = indexNodesByKey(currentChildren);
4818
+ const nextByKey = indexDescriptorsByKey(nextDescriptors);
4819
+ const creates = [];
4820
+ const updates = [];
4821
+ const removes = [];
4822
+ const nextChildrenOrder = [];
4823
+ for (const descriptor of nextDescriptors) {
4824
+ const existing = currentByKey.get(descriptor.key);
4825
+ if (!existing || !canReuse(existing, descriptor)) {
4826
+ creates.push({ descriptor });
4827
+ nextChildrenOrder.push({ descriptor });
4828
+ continue;
4829
+ }
4830
+ const previousDescriptor = currentDescriptors.get(existing.id);
4831
+ if (previousDescriptor !== descriptor) {
4832
+ updates.push({
4833
+ node: existing,
4834
+ previousDescriptor,
4835
+ nextDescriptor: descriptor
3282
4836
  });
3283
- this.mountOrRestartFieldDependencies(node, model);
3284
- return;
3285
4837
  }
3286
- this.unmountField(node);
3287
- this.mountField(node);
4838
+ nextChildrenOrder.push({ descriptor, node: existing });
4839
+ }
4840
+ for (const child of currentChildren) {
4841
+ const nextDescriptor = nextByKey.get(child.key);
4842
+ if (!nextDescriptor || !canReuse(child, nextDescriptor)) {
4843
+ removes.push({ node: child });
4844
+ }
3288
4845
  }
3289
- updateGroup(_node, _descriptor) {
4846
+ return {
4847
+ creates,
4848
+ updates,
4849
+ removes,
4850
+ nextChildrenOrder
4851
+ };
4852
+ }
4853
+ function canReuse(node, descriptor) {
4854
+ return node.type === descriptor.type;
4855
+ }
4856
+ function indexNodesByKey(nodes) {
4857
+ const result = /* @__PURE__ */ new Map();
4858
+ for (const node of nodes) {
4859
+ result.set(node.key, node);
4860
+ }
4861
+ return result;
4862
+ }
4863
+ function indexDescriptorsByKey(descriptors) {
4864
+ const result = /* @__PURE__ */ new Map();
4865
+ for (const descriptor of descriptors) {
4866
+ result.set(descriptor.key, descriptor);
3290
4867
  }
3291
- updateDependency(node, previousNode) {
3292
- if (!node.dependencySlot || !previousNode || !isSameNamePathList(node.descriptor.trigger, previousNode == null ? void 0 : previousNode.descriptor.trigger)) {
3293
- this.unmountDependency(node);
3294
- this.mountDependency(node);
4868
+ return result;
4869
+ }
4870
+ function createReconciler(context) {
4871
+ const runtime = normalizeReconcilerContext(context);
4872
+ function reconcileChildren(parent, nextDescriptors) {
4873
+ const currentChildren = getChildRuntimeNodes(parent);
4874
+ const plan = createReconcilePlan(
4875
+ currentChildren,
4876
+ nextDescriptors,
4877
+ runtime.getCurrentDescriptors()
4878
+ );
4879
+ const orderedNodes = commitReconcilePlan(parent, plan, runtime);
4880
+ for (const [index, node] of orderedNodes.entries()) {
4881
+ const descriptor = nextDescriptors[index];
4882
+ if ((descriptor == null ? void 0 : descriptor.type) === "group" && node.type === "group") {
4883
+ reconcileChildren(node, descriptor.children);
4884
+ }
3295
4885
  }
3296
4886
  }
3297
- mountFieldValidation(node, model = node.fieldModel, scope = node.fieldResourceScope) {
3298
- if (!model || !scope) {
3299
- return;
4887
+ function createRoot() {
4888
+ const createRootNode = runtime.nodeManager.createRoot;
4889
+ if (!createRootNode) {
4890
+ throw new Error("[schemx] Reconciler nodeManager cannot create root node.");
3300
4891
  }
3301
- createValidationEffect({
3302
- name: node.descriptor.name,
3303
- fieldModel: model,
3304
- context: this.context,
3305
- scope
3306
- });
4892
+ return createRootNode();
3307
4893
  }
3308
- mountOrRestartFieldDependencies(node, model = node.fieldModel) {
3309
- var _a;
3310
- (_a = node.fieldDependenciesScope) == null ? void 0 : _a.dispose();
3311
- if (!model || !node.descriptor.dependencies) {
3312
- node.fieldDependenciesScope = null;
4894
+ function updateNode(node, nextDescriptor) {
4895
+ const previousDescriptor = runtime.getCurrentDescriptors().get(node.id);
4896
+ if (previousDescriptor === nextDescriptor) {
3313
4897
  return;
3314
4898
  }
3315
- const dependenciesScope = node.scope.child();
3316
- node.fieldDependenciesScope = dependenciesScope;
3317
- dependenciesScope.add(() => {
3318
- if (node.fieldDependenciesScope === dependenciesScope) {
3319
- node.fieldDependenciesScope = null;
3320
- }
3321
- });
3322
- createDependenciesEffect({
3323
- descriptor: node.descriptor,
3324
- fieldModel: model,
3325
- context: this.context,
3326
- scope: dependenciesScope
3327
- });
3328
- }
3329
- unmountField(node) {
3330
- var _a, _b;
3331
- (_a = node.fieldDependenciesScope) == null ? void 0 : _a.dispose();
3332
- node.fieldDependenciesScope = null;
3333
- (_b = node.fieldResourceScope) == null ? void 0 : _b.dispose();
3334
- node.fieldResourceScope = null;
3335
- }
3336
- unmountGroup(_node) {
4899
+ runtime.lifecycle.update(node, previousDescriptor, nextDescriptor);
3337
4900
  }
3338
- unmountDependency(node) {
3339
- var _a;
3340
- (_a = node.dependencyResourceScope) == null ? void 0 : _a.dispose();
3341
- node.dependencyResourceScope = null;
3342
- node.dependencySlot = null;
4901
+ function removeNode(node) {
4902
+ runtime.lifecycle.unmountSubtree(node);
4903
+ runtime.nodeManager.removeSubtree(node);
3343
4904
  }
4905
+ return {
4906
+ createRoot,
4907
+ reconcileChildren,
4908
+ updateNode,
4909
+ removeNode
4910
+ };
3344
4911
  }
3345
- function createRuntimeNodeManager(context) {
3346
- return new DefaultRuntimeNodeManager(context);
3347
- }
3348
- function isSameNamePathList(a2, b2) {
3349
- if (a2.length !== b2.length) {
3350
- return false;
4912
+ function normalizeReconcilerContext(context) {
4913
+ if (isReconcilerContext(context)) {
4914
+ return context;
3351
4915
  }
3352
- return a2.every((name, index) => name === b2[index]);
3353
- }
3354
- function createPreviousRuntimeNodeSnapshot(node) {
3355
- return { ...node };
3356
- }
3357
- function throwUnknownDescriptor(descriptor) {
3358
- throw new Error(`unknown type: ${descriptor.type ?? "unknown"}`);
4916
+ const nodeManager = createRuntimeNodeManager(context);
4917
+ const lifecycle = createRuntimeLifecycle(context);
4918
+ return {
4919
+ nodeManager,
4920
+ lifecycle,
4921
+ getCurrentDescriptors: () => context.nodeResources.descriptors
4922
+ };
3359
4923
  }
3360
- function throwUnexpectedDescriptor(node, descriptor) {
3361
- throw new Error(
3362
- `unexpected descriptor type: node ${node.type} cannot update with ${descriptor.type}`
3363
- );
4924
+ function isReconcilerContext(context) {
4925
+ return "nodeManager" in context && "lifecycle" in context;
3364
4926
  }
3365
4927
  const PRIORITY_ORDER = ["sync", "pre", "normal", "post"];
3366
4928
  function createScheduler() {
@@ -3386,18 +4948,23 @@ function createScheduler() {
3386
4948
  };
3387
4949
  const flushOnce = async () => {
3388
4950
  var _a, _b;
3389
- const batch = takeBatch();
3390
- for (const task of batch) {
3391
- if (disposed || ((_a = task.scope) == null ? void 0 : _a.disposed)) {
3392
- continue;
4951
+ while (!disposed) {
4952
+ const batch = takeBatch();
4953
+ if (batch.length === 0) {
4954
+ return;
3393
4955
  }
3394
- try {
3395
- const result = task.run();
3396
- if (isPromiseLike(result)) {
3397
- await track(result);
4956
+ for (const task of batch) {
4957
+ if (disposed || ((_a = task.scope) == null ? void 0 : _a.disposed)) {
4958
+ continue;
4959
+ }
4960
+ try {
4961
+ const result = task.run();
4962
+ if (isPromiseLike(result)) {
4963
+ await track(result);
4964
+ }
4965
+ } catch (error) {
4966
+ (_b = task.onError) == null ? void 0 : _b.call(task, error);
3398
4967
  }
3399
- } catch (error) {
3400
- (_b = task.onError) == null ? void 0 : _b.call(task, error);
3401
4968
  }
3402
4969
  }
3403
4970
  };
@@ -3485,7 +5052,9 @@ class StoreImpl {
3485
5052
  * @param options - 配置选项
3486
5053
  */
3487
5054
  constructor(options = {}) {
5055
+ /** 每个字段路径对应一个 FieldSignal */
3488
5056
  __publicField(this, "fieldSignals", createFieldSignalMap());
5057
+ /** 初始值 */
3489
5058
  __publicField(this, "initialValues");
3490
5059
  const initialValues = options.initialValues ?? {};
3491
5060
  this.initialValues = cloneDeep(initialValues);
@@ -3920,143 +5489,19 @@ class StoreImpl {
3920
5489
  function createStore(options = {}) {
3921
5490
  return new StoreImpl(options);
3922
5491
  }
3923
- const MAX_DEPTH = 100;
3924
- function buildViewSchemas(root) {
3925
- if (!root) {
3926
- return [];
3927
- }
3928
- return buildRuntimeNodeChildren(getChildRuntimeNodes(root), 1);
3929
- }
3930
- function buildRuntimeNodeChildren(nodes, depth) {
3931
- if (depth > MAX_DEPTH) {
3932
- throw new RangeError(
3933
- `buildViewSchemas: max depth ${MAX_DEPTH} exceeded at depth ${depth}`
3934
- );
3935
- }
3936
- const results = [];
3937
- for (const node of nodes) {
3938
- const schema = buildRuntimeNodeSchema(node, depth);
3939
- if (schema === null) {
3940
- continue;
3941
- }
3942
- if (Array.isArray(schema)) {
3943
- for (const child of schema) {
3944
- results.push(child);
3945
- }
3946
- continue;
3947
- }
3948
- results.push(schema);
3949
- }
3950
- return results;
3951
- }
3952
- function buildRuntimeNodeSchema(node, depth) {
3953
- if (node.disposed.value) {
3954
- return null;
3955
- }
3956
- if (isGroupRuntimeNode(node)) {
3957
- return buildGroupViewSchema(node, depth);
3958
- }
3959
- if (isDependencyRuntimeNode(node)) {
3960
- return buildDependencyRuntimeNode(node, depth);
3961
- }
3962
- if (isFieldRuntimeNode(node)) {
3963
- return buildFieldViewSchema(node);
3964
- }
3965
- return null;
3966
- }
3967
- function buildFieldViewSchema(node) {
3968
- const descriptor = node.descriptor;
3969
- const model = node.fieldModel;
3970
- if (!model) {
3971
- console.warn(
3972
- `[buildViewSchemas] skipping field node "${node.key}": no FieldModel resource`
3973
- );
3974
- return null;
3975
- }
3976
- if ((descriptor == null ? void 0 : descriptor.type) !== "field") {
3977
- return null;
3978
- }
3979
- const schema = descriptor.schema;
3980
- const snapshot = model.snapshot.value;
3981
- return {
3982
- ...schema,
3983
- key: node.key,
3984
- visible: snapshot.visible,
3985
- label: snapshot.label,
3986
- readonly: snapshot.readonly,
3987
- disabled: snapshot.disabled,
3988
- required: snapshot.required,
3989
- placeholder: sanitizePlaceholder(snapshot.placeholder),
3990
- componentProps: sanitizeComponentProps(snapshot.componentProps ?? {}),
3991
- rules: snapshot.rules,
3992
- validationTrigger: schema.validationTrigger,
3993
- debug: buildDebugMeta(node)
3994
- };
3995
- }
3996
- function buildGroupViewSchema(node, depth) {
3997
- const children = buildRuntimeNodeChildren(
3998
- getChildRuntimeNodes(node),
3999
- depth + 1
4000
- );
4001
- const descriptor = node.descriptor;
4002
- return {
4003
- ...descriptor.schema,
4004
- key: node.key,
4005
- children,
4006
- debug: buildDebugMeta(node)
4007
- };
4008
- }
4009
- function buildDependencyRuntimeNode(node, depth) {
4010
- return buildRuntimeNodeChildren(getChildRuntimeNodes(node), depth + 1);
4011
- }
4012
- function sanitizePlaceholder(value) {
4013
- return value.length > 1e3 ? value.slice(0, 1e3) : value;
4014
- }
4015
- function sanitizeComponentProps(props, depth = 0) {
4016
- if (depth > 10) {
4017
- return {};
4018
- }
4019
- const result = {};
4020
- for (const key of Object.keys(props)) {
4021
- if (!isValidPropKey(key)) {
4022
- continue;
4023
- }
4024
- const value = props[key];
4025
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
4026
- result[key] = sanitizeComponentProps(value, depth + 1);
4027
- } else {
4028
- result[key] = value;
4029
- }
4030
- }
4031
- return result;
4032
- }
4033
- function isValidPropKey(key) {
4034
- if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key)) {
4035
- return true;
4036
- }
4037
- if (/^[a-zA-Z0-9_-]+$/.test(key)) {
4038
- return true;
4039
- }
4040
- return false;
4041
- }
4042
- function buildDebugMeta(node) {
4043
- return {
4044
- runtimeNodeId: node.id,
4045
- runtimeNodeType: node.type,
4046
- hasFieldModel: node.type === "field" && node.fieldModel !== void 0,
4047
- hasDependencySlot: node.type === "dependency" && node.dependencySlot !== void 0
4048
- };
4049
- }
4050
- function subscribeViewSchemas(root, revision, onChange) {
5492
+ function subscribeViewSchemas(root2, resources, onChange) {
4051
5493
  let rootDisposed = false;
4052
- const rootScope = root.scope;
5494
+ const rootScope = root2.scope;
4053
5495
  const disposeHandle = rootScope.add(() => {
4054
5496
  rootDisposed = true;
4055
5497
  });
4056
5498
  const disposeEffect = createDebouncedSignalEffect(
4057
5499
  () => {
4058
- void revision.revision.value;
4059
- return rootDisposed ? [] : buildViewSchemas(root);
5500
+ if (rootDisposed) {
5501
+ return [];
5502
+ }
5503
+ const rootViewState = resources.viewStates.get(root2.id);
5504
+ return isRootViewState(rootViewState) ? rootViewState.viewSchemas.value : [];
4060
5505
  },
4061
5506
  (viewSchemas) => {
4062
5507
  try {
@@ -4075,34 +5520,49 @@ function subscribeViewSchemas(root, revision, onChange) {
4075
5520
  };
4076
5521
  return unsubscribe;
4077
5522
  }
4078
- function createViewRevision() {
4079
- const revision = createSignal(0);
4080
- const bump = () => {
4081
- revision.value += 1;
4082
- };
4083
- return {
4084
- revision,
4085
- bump
4086
- };
5523
+ function isRootViewState(viewState) {
5524
+ return viewState != null && "viewSchemas" in viewState;
4087
5525
  }
4088
5526
  class CreateForm {
4089
5527
  constructor(options = {}) {
5528
+ /** 表单内部上下文,集中持有全局配置和运行时服务 */
4090
5529
  __publicField(this, "context");
5530
+ /** 用户传入的表单级回调集合 */
4091
5531
  __publicField(this, "callbacks");
5532
+ /** 表单状态存储,管理字段值、初始值和订阅 */
4092
5533
  __publicField(this, "store");
5534
+ /** 渲染器注册表,解析 schema.componentType 到具体渲染实现 */
4093
5535
  __publicField(this, "rendererRegistry");
5536
+ /** 校验规则注册表,解析字符串规则名称到 StandardSchema 或规则工厂 */
4094
5537
  __publicField(this, "validatorRegistry");
5538
+ /** 字段校验器,维护规则、错误状态和校验执行流程 */
4095
5539
  __publicField(this, "validator");
5540
+ /** Runtime node 的透明根节点,承载所有编译后的表单描述符节点 */
4096
5541
  __publicField(this, "root");
5542
+ /** 运行时异步调度器,用于追踪 dependency renderer 和字段动态依赖 */
4097
5543
  __publicField(this, "scheduler");
4098
- __publicField(this, "viewRevision");
5544
+ /** descriptor 到 RuntimeNode tree 的协调器,负责创建、复用和销毁节点 */
4099
5545
  __publicField(this, "reconciler");
4100
- __publicField(this, "runtimeNodeManager");
5546
+ /** 字段 RuntimeNode 到字段模型的注册表,供表单 API 和视图投影读取 */
4101
5547
  __publicField(this, "fieldRegistry");
5548
+ /** RuntimeNode 之外的 descriptor、state、view 和 effect 资源表 */
5549
+ __publicField(this, "nodeResources");
5550
+ /** 表单级资源作用域,统一管理回调 effect 等非 RuntimeNode 资源 */
4102
5551
  __publicField(this, "scope", createScope());
5552
+ /** root schema 的统一数据源 */
4103
5553
  __publicField(this, "schemas");
5554
+ /** schema 编译,让未变化的 schema 复用 descriptor 引用 */
5555
+ __publicField(this, "compile");
5556
+ /** 标记表单实例是否已销毁,保证 dispose 幂等 */
4104
5557
  __publicField(this, "disposed", false);
5558
+ /** node 生命周期事件总线,连接 reconciler 与字段资源挂载流程 */
4105
5559
  __publicField(this, "lifecycleBus");
5560
+ /**
5561
+ * 表单实例接口
5562
+ *
5563
+ * 定义表单的所有操作方法,是 useForm 返回值的基础接口。
5564
+ * SchemxInstance 类实现此接口,提供完整的表单操作能力。
5565
+ */
4106
5566
  __publicField(this, "getFormInstance", () => {
4107
5567
  return {
4108
5568
  setFieldValue: this.store.setFieldValue.bind(this.store),
@@ -4133,8 +5593,8 @@ class CreateForm {
4133
5593
  batch: this.batch.bind(this),
4134
5594
  setSchemas: this.setSchemas.bind(this),
4135
5595
  updateSchemas: this.updateSchemas.bind(this),
5596
+ updateFieldSchema: this.updateFieldSchema.bind(this),
4136
5597
  updateDefaultProps: this.updateDefaultProps.bind(this),
4137
- getViewRevision: () => this.viewRevision.revision.value,
4138
5598
  getViewSchemas: this.getViewSchemas.bind(this),
4139
5599
  subscribeViewSchemas: this.subscribeViewSchemas.bind(this),
4140
5600
  waitForDependencies: this.waitForIdle.bind(this),
@@ -4147,6 +5607,11 @@ class CreateForm {
4147
5607
  destroy: this.destroy.bind(this)
4148
5608
  };
4149
5609
  });
5610
+ /**
5611
+ * 表单 API,提供与表单交互的方法。
5612
+ *
5613
+ * 传递给动态渲染器,允许程序化操作表单。
5614
+ */
4150
5615
  __publicField(this, "getFormApi", () => {
4151
5616
  return {
4152
5617
  setValue: this.store.setFieldValue.bind(this.store),
@@ -4166,6 +5631,11 @@ class CreateForm {
4166
5631
  validate: this.validate.bind(this)
4167
5632
  };
4168
5633
  });
5634
+ /**
5635
+ * 校验所有已注册字段
5636
+ *
5637
+ * 校验前检查是否有字段处于操作中状态,有则直接返回失败结果。
5638
+ */
4169
5639
  __publicField(this, "validate", withLock(async () => {
4170
5640
  const pendingFields = this.store.getPendingFields();
4171
5641
  if (pendingFields.length > 0) {
@@ -4189,24 +5659,30 @@ class CreateForm {
4189
5659
  const result = await this.validator.validate(this.store.getFieldsValue());
4190
5660
  return result;
4191
5661
  }));
5662
+ /**
5663
+ * 提交表单
5664
+ */
4192
5665
  __publicField(this, "submit", withLock(async () => {
4193
- var _a2, _b2, _c, _d;
5666
+ var _a, _b, _c, _d;
4194
5667
  const depsReady = await this.waitForIdle();
4195
5668
  if (!depsReady) {
4196
5669
  return;
4197
5670
  }
4198
5671
  const result = await this.validate();
4199
5672
  if (result.ok) {
4200
- await ((_b2 = (_a2 = this.callbacks).onFinish) == null ? void 0 : _b2.call(_a2, result.values));
5673
+ await ((_b = (_a = this.callbacks).onFinish) == null ? void 0 : _b.call(_a, result.values));
4201
5674
  } else {
4202
5675
  (_d = (_c = this.callbacks).onFinishFailed) == null ? void 0 : _d.call(_c, result.error);
4203
5676
  }
4204
5677
  }));
5678
+ /**
5679
+ * 唯一子节点提交边界。
5680
+ *
5681
+ * 所有结构输入先编译成 descriptor,再经由这里提交到某个 parent RuntimeNode。
5682
+ * Reconciler 只负责 node 结构;视图层通过 childrenState signal 自动感知结构变化。
5683
+ */
4205
5684
  __publicField(this, "commitChildren", (parentNode, descriptors) => {
4206
- const changed = this.reconciler.reconcileChildren(parentNode, descriptors);
4207
- if (changed) {
4208
- this.viewRevision.bump();
4209
- }
5685
+ this.reconciler.reconcileChildren(parentNode, descriptors);
4210
5686
  });
4211
5687
  var _a, _b;
4212
5688
  const {
@@ -4237,20 +5713,31 @@ class CreateForm {
4237
5713
  });
4238
5714
  this.lifecycleBus = createLifecycleBus();
4239
5715
  this.scheduler = createScheduler();
4240
- this.viewRevision = createViewRevision();
4241
5716
  this.fieldRegistry = createFieldRegistry();
5717
+ this.nodeResources = createRuntimeResources();
5718
+ const defaultProps = pick(restOptions, defaultConfigKey);
5719
+ this.compile = createCompile({
5720
+ defaultProps,
5721
+ formInstance: this.getFormInstance()
5722
+ });
4242
5723
  this.context = {
4243
- defaultProps: pick(restOptions, defaultConfigKey),
5724
+ defaultProps,
4244
5725
  instance: this.getFormInstance(),
4245
5726
  formApi: this.getFormApi(),
5727
+ compile: this.compile,
4246
5728
  scheduler: this.scheduler,
4247
5729
  lifecycleBus: this.lifecycleBus,
4248
5730
  fieldRegistry: this.fieldRegistry,
5731
+ nodeResources: this.nodeResources,
4249
5732
  commitChildren: this.commitChildren
4250
5733
  };
4251
- this.runtimeNodeManager = createRuntimeNodeManager(this.context);
4252
- this.reconciler = createReconciler(this.runtimeNodeManager);
4253
- this.root = this.runtimeNodeManager.createRoot();
5734
+ this.reconciler = createReconciler(this.context);
5735
+ this.root = this.reconciler.createRoot();
5736
+ const rootChildrenState = this.nodeResources.childrenStates.get(this.root.id);
5737
+ if (!rootChildrenState) {
5738
+ throw new Error("[schemx] root childrenState is required");
5739
+ }
5740
+ createRootRuntimeViewState(this.root, this.nodeResources);
4254
5741
  if (options.lifecycleHooks) {
4255
5742
  this.lifecycleBus.on(options.lifecycleHooks);
4256
5743
  }
@@ -4285,9 +5772,11 @@ class CreateForm {
4285
5772
  * 注册字段校验规则
4286
5773
  */
4287
5774
  register(path, rules, defaultMessage) {
5775
+ var _a;
4288
5776
  const resolvedRules = [];
4289
- const node = findFieldRuntimeNode(this.root, path);
4290
- const schema = node == null ? void 0 : node.descriptor.schema;
5777
+ const node = (_a = this.fieldRegistry.get(path)) == null ? void 0 : _a.node;
5778
+ const descriptor = node ? this.nodeResources.descriptors.get(node.id) : void 0;
5779
+ const schema = (descriptor == null ? void 0 : descriptor.type) === "field" ? descriptor.staticSchema : void 0;
4291
5780
  this.validator.unregister(path);
4292
5781
  const schemaWithRules = {
4293
5782
  ...schema,
@@ -4355,6 +5844,41 @@ class CreateForm {
4355
5844
  }
4356
5845
  this.schemas.update(updater);
4357
5846
  }
5847
+ /**
5848
+ * 更新单个字段的静态 schema 呈现配置。
5849
+ */
5850
+ updateFieldSchema(name, patch) {
5851
+ var _a;
5852
+ if (this.disposed) {
5853
+ return;
5854
+ }
5855
+ const entry = this.fieldRegistry.get(name);
5856
+ if (!entry) {
5857
+ return;
5858
+ }
5859
+ const node = entry.node;
5860
+ const current = this.nodeResources.descriptors.get(node.id);
5861
+ if ((current == null ? void 0 : current.type) !== "field") {
5862
+ return;
5863
+ }
5864
+ const nextRawSchema = {
5865
+ ...current.staticSchema,
5866
+ ...patch,
5867
+ componentProps: patch.componentProps ? {
5868
+ ...current.staticSchema.componentProps,
5869
+ ...patch.componentProps
5870
+ } : current.staticSchema.componentProps,
5871
+ key: current.key,
5872
+ name: current.name,
5873
+ componentType: current.staticSchema.componentType,
5874
+ dependencies: (_a = current.dynamicProps) == null ? void 0 : _a.dependencies
5875
+ };
5876
+ const [next] = this.compile.toDescriptors([nextRawSchema]);
5877
+ if (next.type !== "field") {
5878
+ return;
5879
+ }
5880
+ this.reconciler.updateNode(node, next);
5881
+ }
4358
5882
  /**
4359
5883
  * 更新表单默认配置。
4360
5884
  *
@@ -4366,6 +5890,7 @@ class CreateForm {
4366
5890
  return;
4367
5891
  }
4368
5892
  Object.assign(this.context.defaultProps, pick(partial, defaultConfigKey));
5893
+ this.compile.invalidate();
4369
5894
  this.applySchemas(this.schemas.peek());
4370
5895
  }
4371
5896
  /**
@@ -4375,12 +5900,8 @@ class CreateForm {
4375
5900
  if (this.disposed) {
4376
5901
  return;
4377
5902
  }
4378
- const previousRevision = this.viewRevision.revision.value;
4379
- const descriptors = compileToDescriptors([...schemas], this.context.defaultProps);
5903
+ const descriptors = this.compile.toDescriptors(schemas);
4380
5904
  this.commitChildren(this.root, descriptors);
4381
- if (this.viewRevision.revision.value === previousRevision) {
4382
- this.viewRevision.bump();
4383
- }
4384
5905
  }
4385
5906
  /**
4386
5907
  * 销毁表单实例
@@ -4393,7 +5914,7 @@ class CreateForm {
4393
5914
  }
4394
5915
  this.disposed = true;
4395
5916
  this.scope.dispose();
4396
- this.runtimeNodeManager.disposeTree(this.root);
5917
+ this.reconciler.removeNode(this.root);
4397
5918
  this.scheduler.dispose();
4398
5919
  this.store.destroy();
4399
5920
  }
@@ -4401,13 +5922,17 @@ class CreateForm {
4401
5922
  * 获取当前 ViewSchemas。
4402
5923
  */
4403
5924
  getViewSchemas() {
4404
- return buildViewSchemas(this.root);
5925
+ const rootViewState = this.nodeResources.viewStates.get(this.root.id);
5926
+ if (!rootViewState || !("viewSchemas" in rootViewState)) {
5927
+ return [];
5928
+ }
5929
+ return readRootViewSchemas(rootViewState);
4405
5930
  }
4406
5931
  /**
4407
5932
  * 订阅 ViewSchemas 变化。
4408
5933
  */
4409
5934
  subscribeViewSchemas(callback) {
4410
- return subscribeViewSchemas(this.root, this.viewRevision, callback);
5935
+ return subscribeViewSchemas(this.root, this.nodeResources, callback);
4411
5936
  }
4412
5937
  /**
4413
5938
  * 等待内部异步任务完成。
@@ -4600,7 +6125,7 @@ function createWatch(form, nameOrNamesOrCallback, callbackOrOptions, maybeOption
4600
6125
  const rendererRegistry = createRendererRegistry("input");
4601
6126
  const validatorRegistry = createValidatorsRegistry();
4602
6127
  const SCHEMX_INSTANCE_KEY = Symbol("SCHEMX_INSTANCE");
4603
- function useForm(options) {
6128
+ function useForm(options = {}) {
4604
6129
  const { ...formOptions } = options;
4605
6130
  const mergedOptions = {
4606
6131
  ...formOptions,
@@ -4614,13 +6139,14 @@ function useForm(options) {
4614
6139
  });
4615
6140
  return instance.value;
4616
6141
  }
4617
- function useFormInstance() {
6142
+ function useFormContext() {
4618
6143
  const instance = inject(SCHEMX_INSTANCE_KEY);
4619
6144
  if (!instance) {
4620
- throw new Error("useFormInstance must be used within a Form");
6145
+ throw new Error("useFormContext must be used within a Form");
4621
6146
  }
4622
6147
  return instance;
4623
6148
  }
6149
+ const FIELD_CONTEXT_KEY = Symbol("schemx:field");
4624
6150
  const fieldHookCache = /* @__PURE__ */ new WeakMap();
4625
6151
  function createFieldHook(form, name) {
4626
6152
  const field = createField(form, name);
@@ -4649,7 +6175,7 @@ function createFieldHook(form, name) {
4649
6175
  return { result, dispose };
4650
6176
  }
4651
6177
  const useField = (name) => {
4652
- const form = useFormInstance();
6178
+ const form = useFormContext();
4653
6179
  const key = name;
4654
6180
  let formCache = fieldHookCache.get(form);
4655
6181
  if (!formCache) {
@@ -4678,8 +6204,18 @@ const useField = (name) => {
4678
6204
  });
4679
6205
  return activeEntry.result;
4680
6206
  };
6207
+ function createFieldContext(field) {
6208
+ provide(FIELD_CONTEXT_KEY, field);
6209
+ }
6210
+ function useFieldContext() {
6211
+ const field = inject(FIELD_CONTEXT_KEY);
6212
+ if (!field) {
6213
+ throw new Error("[schemx] useFieldContext() must be used inside a FormItem tree");
6214
+ }
6215
+ return field;
6216
+ }
4681
6217
  function useWatch(nameOrNamesOrCallback, callbackOrOptions, maybeOptions) {
4682
- const form = useFormInstance();
6218
+ const form = useFormContext();
4683
6219
  const dispose = createWatch(
4684
6220
  form,
4685
6221
  nameOrNamesOrCallback,
@@ -4709,7 +6245,7 @@ function normalizeError(err) {
4709
6245
  }
4710
6246
  const useDictionary = (options, fieldName) => {
4711
6247
  var _a;
4712
- const instance = useFormInstance();
6248
+ const instance = useFormContext();
4713
6249
  const list = ref([]);
4714
6250
  const loading = ref(false);
4715
6251
  const error = ref(void 0);
@@ -4791,13 +6327,13 @@ const useDictionary = (options, fieldName) => {
4791
6327
  return { list, loading, error, loadDict, refresh, mutate };
4792
6328
  };
4793
6329
  const FORM_CONTEXT_KEY = Symbol("FormContext");
4794
- const createContext = (props) => {
6330
+ const createConfigContext = (props) => {
4795
6331
  provide(FORM_CONTEXT_KEY, props);
4796
6332
  };
4797
- function useContext() {
6333
+ function useConfigContext() {
4798
6334
  const context = inject(FORM_CONTEXT_KEY);
4799
6335
  if (!context) {
4800
- throw new Error("useContext must be used within a Form");
6336
+ throw new Error("useConfigContext must be used within a Form");
4801
6337
  }
4802
6338
  return context;
4803
6339
  }
@@ -4825,17 +6361,6 @@ function useViewSchemas(form) {
4825
6361
  onScopeDispose(unsubscribe);
4826
6362
  return viewSchemas;
4827
6363
  }
4828
- const FIELD_CONTEXT_KEY = Symbol("schemx:field");
4829
- function provideFieldContext(field) {
4830
- provide(FIELD_CONTEXT_KEY, field);
4831
- }
4832
- function useFieldContext() {
4833
- const field = inject(FIELD_CONTEXT_KEY);
4834
- if (!field) {
4835
- throw new Error("[schemx] useFieldContext() must be used inside a FormItem tree");
4836
- }
4837
- return field;
4838
- }
4839
6364
  function isValidTrigger(v2) {
4840
6365
  if (v2 === void 0) return false;
4841
6366
  if (Array.isArray(v2) && v2.length === 0) return false;
@@ -4960,17 +6485,17 @@ const FormItem = /* @__PURE__ */ defineComponent((props, {
4960
6485
  }, slots);
4961
6486
  };
4962
6487
  }
4963
- const form = useFormInstance();
4964
- const formContext = useContext();
6488
+ const form = useFormContext();
6489
+ const formContext = useConfigContext();
4965
6490
  const schema = () => schemaRef.value;
4966
6491
  const field = useField(schema().name);
4967
- provideFieldContext(field);
6492
+ createFieldContext(field);
4968
6493
  const trigger = computed(() => mergeTrigger(schema().validationTrigger, formContext.validationTrigger, "onChange"));
4969
6494
  const canVerified = computed(() => {
4970
6495
  const isOperate = schema().visible && !schema().readonly && !schema().disabled;
4971
6496
  const rules = schema().rules;
4972
- const hasRules = Array.isArray(rules) ? (rules == null ? void 0 : rules.length) > 0 : !!schema().rules;
4973
- return isOperate && hasRules;
6497
+ const hasRules2 = Array.isArray(rules) ? (rules == null ? void 0 : rules.length) > 0 : !!schema().rules;
6498
+ return isOperate && hasRules2;
4974
6499
  });
4975
6500
  const handleChange = (v2) => {
4976
6501
  var _a, _b;
@@ -4985,27 +6510,9 @@ const FormItem = /* @__PURE__ */ defineComponent((props, {
4985
6510
  field.validate();
4986
6511
  }
4987
6512
  };
4988
- const formItemProps = computed(() => {
4989
- return {
4990
- ...omit(schema(), ["componentProps"]),
4991
- name: schema().name,
4992
- componentType: schema().componentType,
4993
- class: classnames("schemx-item", schema().class),
4994
- required: schema().required,
4995
- readonly: schema().readonly,
4996
- disabled: schema().disabled,
4997
- visible: schema().visible,
4998
- placeholder: schema().placeholder,
4999
- validationTrigger: trigger.value
5000
- };
5001
- });
5002
6513
  const componentProps = useStableRef(() => ({
5003
6514
  ...schema().componentProps,
5004
- formItemProps: formItemProps.value,
5005
6515
  value: field.getValue(),
5006
- readonly: schema().readonly,
5007
- disabled: schema().disabled,
5008
- placeholder: schema().placeholder,
5009
6516
  onChange: handleChange,
5010
6517
  onBlur: handleBlur,
5011
6518
  "onUpdate:value": (v2) => field.setValue(v2)
@@ -5021,7 +6528,7 @@ const FormItem = /* @__PURE__ */ defineComponent((props, {
5021
6528
  const renderLabel = () => {
5022
6529
  const labelSlot = resolveSlot(slots, `${schema().name}Label`);
5023
6530
  if (labelSlot) {
5024
- return labelSlot(formItemProps.value);
6531
+ return labelSlot(schema());
5025
6532
  }
5026
6533
  const labelAlign = schema().labelAlign || formContext.labelAlign;
5027
6534
  const labelWidth = schema().labelWidth || formContext.labelWidth;
@@ -5046,7 +6553,7 @@ const FormItem = /* @__PURE__ */ defineComponent((props, {
5046
6553
  const contentSlot = resolveSlot(slots, `${schema().name}Content`);
5047
6554
  if (contentSlot) {
5048
6555
  return contentSlot({
5049
- ...formItemProps.value,
6556
+ ...schema(),
5050
6557
  columnElement
5051
6558
  });
5052
6559
  }
@@ -5058,7 +6565,7 @@ const FormItem = /* @__PURE__ */ defineComponent((props, {
5058
6565
  const errorSlot = resolveSlot(slots, `${schema().name}Error`);
5059
6566
  if (errorSlot) {
5060
6567
  return errorSlot({
5061
- ...formItemProps.value,
6568
+ ...schema(),
5062
6569
  errors: field.error.value
5063
6570
  });
5064
6571
  }
@@ -5075,7 +6582,7 @@ const FormItem = /* @__PURE__ */ defineComponent((props, {
5075
6582
  }
5076
6583
  const itemSlot = resolveSlot(slots, normalizeNameKey(schema().name));
5077
6584
  if (itemSlot) {
5078
- return itemSlot(formItemProps.value);
6585
+ return itemSlot(schema());
5079
6586
  }
5080
6587
  const labelPosition = schema().labelPosition || formContext.labelPosition;
5081
6588
  return createVNode("div", {
@@ -5179,7 +6686,7 @@ const _sfc_main = /* @__PURE__ */ defineComponent({
5179
6686
  setup(__props, { expose: __expose, emit: __emit }) {
5180
6687
  const props = __props;
5181
6688
  const emit = __emit;
5182
- createContext(
6689
+ createConfigContext(
5183
6690
  omit(props, [
5184
6691
  "form",
5185
6692
  "modelValue",
@@ -5306,14 +6813,15 @@ function WithRemoteOptions(WrappedComponent) {
5306
6813
  });
5307
6814
  }
5308
6815
  export {
6816
+ ContextNotProvidedError,
5309
6817
  FormGroup,
5310
6818
  FormItem,
5311
6819
  WithRemoteOptions,
5312
6820
  collectObjectPathsByLeaf,
6821
+ createContext,
5313
6822
  createEffect,
5314
6823
  createField,
5315
6824
  createForm,
5316
- createForm as createFormInstance,
5317
6825
  createLifecycle,
5318
6826
  createLifecycleBus,
5319
6827
  createRendererRegistry,
@@ -5328,6 +6836,7 @@ export {
5328
6836
  getByPath,
5329
6837
  isBaseResolvedSchema,
5330
6838
  isBaseSchema,
6839
+ isContext,
5331
6840
  isDependencySchema,
5332
6841
  isGroupResolvedSchema,
5333
6842
  isGroupSchema,
@@ -5335,12 +6844,13 @@ export {
5335
6844
  rendererRegistry,
5336
6845
  SchemxFormExport as schemxForm,
5337
6846
  setByPath,
5338
- useContext,
6847
+ useConfigContext,
5339
6848
  useDictionary,
5340
6849
  useEffect,
5341
6850
  useField,
5342
6851
  useFieldContext,
5343
6852
  useForm,
6853
+ useFormContext,
5344
6854
  useWatch,
5345
6855
  useWatchAll,
5346
6856
  useWatchField,