@atscript/ui 0.1.163 → 0.1.164

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 (156) hide show
  1. package/dist/client-factory.cjs +27 -0
  2. package/dist/client-factory.d.cts +53 -0
  3. package/dist/client-factory.d.mts +53 -0
  4. package/dist/client-factory.mjs +25 -0
  5. package/dist/form/apply.cjs +38 -0
  6. package/dist/form/apply.d.cts +36 -0
  7. package/dist/form/apply.d.mts +36 -0
  8. package/dist/form/apply.mjs +38 -0
  9. package/dist/form/clone.cjs +30 -0
  10. package/dist/form/clone.d.cts +23 -0
  11. package/dist/form/clone.d.mts +23 -0
  12. package/dist/form/clone.mjs +30 -0
  13. package/dist/form/create-form-def.cjs +440 -0
  14. package/dist/form/create-form-def.d.cts +67 -0
  15. package/dist/form/create-form-def.d.mts +67 -0
  16. package/dist/form/create-form-def.mjs +438 -0
  17. package/dist/form/decimal-format.cjs +324 -0
  18. package/dist/form/decimal-format.d.cts +86 -0
  19. package/dist/form/decimal-format.d.mts +86 -0
  20. package/dist/form/decimal-format.mjs +315 -0
  21. package/dist/form/diff.cjs +458 -0
  22. package/dist/form/diff.d.cts +80 -0
  23. package/dist/form/diff.d.mts +80 -0
  24. package/dist/form/diff.mjs +457 -0
  25. package/dist/form/dirty.cjs +65 -0
  26. package/dist/form/dirty.d.cts +47 -0
  27. package/dist/form/dirty.d.mts +47 -0
  28. package/dist/form/dirty.mjs +64 -0
  29. package/dist/form/error-utils.cjs +97 -0
  30. package/dist/form/error-utils.d.cts +58 -0
  31. package/dist/form/error-utils.d.mts +58 -0
  32. package/dist/form/error-utils.mjs +92 -0
  33. package/dist/form/form-actions.cjs +30 -0
  34. package/dist/form/form-actions.d.cts +17 -0
  35. package/dist/form/form-actions.d.mts +17 -0
  36. package/dist/form/form-actions.mjs +30 -0
  37. package/dist/form/grid.cjs +69 -0
  38. package/dist/form/grid.d.cts +49 -0
  39. package/dist/form/grid.d.mts +49 -0
  40. package/dist/form/grid.mjs +64 -0
  41. package/dist/form/labels.cjs +10 -0
  42. package/dist/form/labels.d.cts +7 -0
  43. package/dist/form/labels.d.mts +7 -0
  44. package/dist/form/labels.mjs +10 -0
  45. package/dist/form/measurement.cjs +20 -0
  46. package/dist/form/measurement.d.cts +29 -0
  47. package/dist/form/measurement.d.mts +29 -0
  48. package/dist/form/measurement.mjs +20 -0
  49. package/dist/form/path-utils.cjs +182 -0
  50. package/dist/form/path-utils.d.cts +47 -0
  51. package/dist/form/path-utils.d.mts +47 -0
  52. package/dist/form/path-utils.mjs +175 -0
  53. package/dist/form/rebase.cjs +89 -0
  54. package/dist/form/rebase.d.cts +61 -0
  55. package/dist/form/rebase.d.mts +61 -0
  56. package/dist/form/rebase.mjs +89 -0
  57. package/dist/form/skipped-nav.cjs +100 -0
  58. package/dist/form/skipped-nav.d.cts +13 -0
  59. package/dist/form/skipped-nav.d.mts +13 -0
  60. package/dist/form/skipped-nav.mjs +98 -0
  61. package/dist/form/types.cjs +40 -0
  62. package/dist/form/types.d.cts +133 -0
  63. package/dist/form/types.d.mts +133 -0
  64. package/dist/form/types.mjs +36 -0
  65. package/dist/form/union-detect.cjs +46 -0
  66. package/dist/form/union-detect.d.cts +22 -0
  67. package/dist/form/union-detect.d.mts +22 -0
  68. package/dist/form/union-detect.mjs +46 -0
  69. package/dist/form/validate.cjs +150 -0
  70. package/dist/form/validate.d.cts +50 -0
  71. package/dist/form/validate.d.mts +50 -0
  72. package/dist/form/validate.mjs +147 -0
  73. package/dist/index.cjs +217 -3360
  74. package/dist/index.d.cts +38 -1693
  75. package/dist/index.d.mts +38 -1693
  76. package/dist/index.mjs +35 -3179
  77. package/dist/nav/model-routes.cjs +59 -0
  78. package/dist/nav/model-routes.d.cts +33 -0
  79. package/dist/nav/model-routes.d.mts +33 -0
  80. package/dist/nav/model-routes.mjs +59 -0
  81. package/dist/plugin/annotations.cjs +577 -0
  82. package/dist/plugin/annotations.mjs +577 -0
  83. package/dist/plugin/primitives.cjs +30 -0
  84. package/dist/plugin/primitives.mjs +30 -0
  85. package/dist/plugin/value-help-validation.cjs +419 -0
  86. package/dist/plugin/value-help-validation.mjs +413 -0
  87. package/dist/plugin.cjs +4 -1001
  88. package/dist/plugin.mjs +2 -999
  89. package/dist/shared/annotation-keys.cjs +189 -0
  90. package/dist/shared/annotation-keys.d.cts +82 -0
  91. package/dist/shared/annotation-keys.d.mts +82 -0
  92. package/dist/shared/annotation-keys.mjs +97 -0
  93. package/dist/shared/field-resolver.cjs +123 -0
  94. package/dist/shared/field-resolver.d.cts +77 -0
  95. package/dist/shared/field-resolver.d.mts +77 -0
  96. package/dist/shared/field-resolver.mjs +110 -0
  97. package/dist/shared/meta-cache.cjs +244 -0
  98. package/dist/shared/meta-cache.d.cts +110 -0
  99. package/dist/shared/meta-cache.d.mts +110 -0
  100. package/dist/shared/meta-cache.mjs +237 -0
  101. package/dist/shared/str.cjs +19 -0
  102. package/dist/shared/str.d.cts +7 -0
  103. package/dist/shared/str.d.mts +7 -0
  104. package/dist/shared/str.mjs +17 -0
  105. package/dist/table/column-resolver.cjs +17 -0
  106. package/dist/table/column-resolver.d.cts +11 -0
  107. package/dist/table/column-resolver.d.mts +11 -0
  108. package/dist/table/column-resolver.mjs +15 -0
  109. package/dist/table/create-table-def.cjs +233 -0
  110. package/dist/table/create-table-def.d.cts +15 -0
  111. package/dist/table/create-table-def.d.mts +15 -0
  112. package/dist/table/create-table-def.mjs +233 -0
  113. package/dist/table/navigate-href.cjs +45 -0
  114. package/dist/table/navigate-href.d.cts +31 -0
  115. package/dist/table/navigate-href.d.mts +31 -0
  116. package/dist/table/navigate-href.mjs +45 -0
  117. package/dist/table/types.d.cts +287 -0
  118. package/dist/table/types.d.mts +287 -0
  119. package/dist/table/value-kind.cjs +20 -0
  120. package/dist/table/value-kind.d.cts +15 -0
  121. package/dist/table/value-kind.d.mts +15 -0
  122. package/dist/table/value-kind.mjs +19 -0
  123. package/dist/value-help/dict-paths.cjs +17 -0
  124. package/dist/value-help/dict-paths.d.cts +11 -0
  125. package/dist/value-help/dict-paths.d.mts +11 -0
  126. package/dist/value-help/dict-paths.mjs +17 -0
  127. package/dist/value-help/distinct-client.cjs +51 -0
  128. package/dist/value-help/distinct-client.d.cts +40 -0
  129. package/dist/value-help/distinct-client.d.mts +40 -0
  130. package/dist/value-help/distinct-client.mjs +50 -0
  131. package/dist/value-help/extract-literals.cjs +76 -0
  132. package/dist/value-help/extract-literals.d.cts +32 -0
  133. package/dist/value-help/extract-literals.d.mts +32 -0
  134. package/dist/value-help/extract-literals.mjs +74 -0
  135. package/dist/value-help/extract-ref.cjs +100 -0
  136. package/dist/value-help/extract-ref.d.cts +37 -0
  137. package/dist/value-help/extract-ref.d.mts +37 -0
  138. package/dist/value-help/extract-ref.mjs +100 -0
  139. package/dist/value-help/filter-tree.cjs +45 -0
  140. package/dist/value-help/filter-tree.mjs +45 -0
  141. package/dist/value-help/index.d.mts +8 -0
  142. package/dist/value-help/resolve-options.cjs +64 -0
  143. package/dist/value-help/resolve-options.d.cts +35 -0
  144. package/dist/value-help/resolve-options.d.mts +35 -0
  145. package/dist/value-help/resolve-options.mjs +60 -0
  146. package/dist/value-help/resolve.cjs +62 -0
  147. package/dist/value-help/resolve.d.cts +31 -0
  148. package/dist/value-help/resolve.d.mts +31 -0
  149. package/dist/value-help/resolve.mjs +61 -0
  150. package/dist/value-help/types.d.cts +36 -0
  151. package/dist/value-help/types.d.mts +36 -0
  152. package/dist/value-help/value-help-client.cjs +136 -0
  153. package/dist/value-help/value-help-client.d.cts +67 -0
  154. package/dist/value-help/value-help-client.d.mts +67 -0
  155. package/dist/value-help/value-help-client.mjs +134 -0
  156. package/package.json +10 -10
package/dist/index.cjs CHANGED
@@ -1,3361 +1,218 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- let _atscript_typescript_utils = require("@atscript/typescript/utils");
3
- let _atscript_db_validator = require("@atscript/db/validator");
4
- let _atscript_db_client = require("@atscript/db-client");
5
- //#region src/shared/annotation-keys.ts
6
- const UI_TYPE = "ui.type";
7
- const UI_FORM_PLACEHOLDER = "ui.form.placeholder";
8
- const UI_FORM_HINT = "ui.form.hint";
9
- const UI_FORM_CLASSES = "ui.form.classes";
10
- const UI_FORM_STYLES = "ui.form.styles";
11
- const UI_FORM_AUTOCOMPLETE = "ui.form.autocomplete";
12
- const UI_FORM_DISABLED = "ui.form.disabled";
13
- const UI_FORM_OPTIONS = "ui.form.options";
14
- const UI_FORM_ORDER = "ui.form.order";
15
- const UI_FORM_TYPE = "ui.form.type";
16
- const UI_FORM_COMPONENT = "ui.form.component";
17
- const UI_FORM_HIDDEN = "ui.form.hidden";
18
- const UI_FORM_PUSH_DOWN = "ui.form.pushDown";
19
- const UI_FORM_ATTR = "ui.form.attr";
20
- const UI_FORM_GRID_COL_SPAN = "ui.form.grid.colSpan";
21
- const UI_FORM_GRID_ROW_SPAN = "ui.form.grid.rowSpan";
22
- const UI_FORM_SUBMIT_TEXT = "ui.form.submit.text";
23
- const UI_FORM_LABEL_SINGULAR = "ui.form.label.singular";
24
- const UI_FORM_ACTION = "ui.form.action";
25
- const UI_FORM_PREFIX = "ui.form.prefix";
26
- const UI_FORM_PREFIX_REF = "ui.form.prefix.ref";
27
- const UI_FORM_PREFIX_ICON = "ui.form.prefix.icon";
28
- const UI_FORM_SUFFIX = "ui.form.suffix";
29
- const UI_FORM_SUFFIX_REF = "ui.form.suffix.ref";
30
- const UI_FORM_SUFFIX_ICON = "ui.form.suffix.icon";
31
- const UI_TABLE_WIDTH = "ui.table.width";
32
- const UI_TABLE_COMPONENT = "ui.table.component";
33
- const UI_TABLE_SELECT_WITH = "ui.table.selectWith";
34
- const UI_TABLE_EXCLUDE = "ui.table.exclude";
35
- const UI_TABLE_ATTR = "ui.table.attr";
36
- const UI_TABLE_CLASSES = "ui.table.classes";
37
- const UI_TABLE_STYLES = "ui.table.styles";
38
- const UI_TABLE_TYPE = "ui.table.type";
39
- const UI_TABLE_ORDER = "ui.table.order";
40
- const UI_DICT_LABEL = "ui.dict.label";
41
- const UI_DICT_DESCR = "ui.dict.descr";
42
- const UI_DICT_ATTR = "ui.dict.attr";
43
- const UI_DICT_FILTERABLE = "ui.dict.filterable";
44
- const UI_DICT_SORTABLE = "ui.dict.sortable";
45
- const UI_DICT_SEARCHABLE = "ui.dict.searchable";
46
- const UI_VALUE_HELP = "ui.valueHelp";
47
- const UI_NAV_GROUP = "ui.nav.group";
48
- const UI_NAV_ORDER = "ui.nav.order";
49
- const UI_NAV_HIDDEN = "ui.nav.hidden";
50
- const DB_REL_FK = "db.rel.FK";
51
- const DB_TABLE = "db.table";
52
- const DB_VIEW = "db.view";
53
- const DB_HTTP_PATH = "db.http.path";
54
- const DB_AMOUNT_CURRENCY = "db.amount.currency";
55
- const DB_AMOUNT_CURRENCY_REF = "db.amount.currency.ref";
56
- const DB_UNIT = "db.unit";
57
- const DB_UNIT_REF = "db.unit.ref";
58
- const DB_COLUMN_PRECISION = "db.column.precision";
59
- const WF_ACTION_WITH_DATA = "wf.action.withData";
60
- const META_LABEL = "meta.label";
61
- const META_ID = "meta.id";
62
- const META_DESCRIPTION = "meta.description";
63
- const META_READONLY = "meta.readonly";
64
- const META_REQUIRED = "meta.required";
65
- const META_DEFAULT = "meta.default";
66
- const META_SENSITIVE = "meta.sensitive";
67
- const EXPECT_MAX_LENGTH = "expect.maxLength";
68
- const UI_FORM_FN_PREFIX = "ui.form.fn.";
69
- const UI_FORM_FN_LABEL = "ui.form.fn.label";
70
- const UI_FORM_FN_PLACEHOLDER = "ui.form.fn.placeholder";
71
- const UI_FORM_FN_DESCRIPTION = "ui.form.fn.description";
72
- const UI_FORM_FN_HINT = "ui.form.fn.hint";
73
- const UI_FORM_FN_HIDDEN = "ui.form.fn.hidden";
74
- const UI_FORM_FN_DISABLED = "ui.form.fn.disabled";
75
- const UI_FORM_FN_READONLY = "ui.form.fn.readonly";
76
- const UI_FORM_FN_OPTIONS = "ui.form.fn.options";
77
- const UI_FORM_FN_ATTR = "ui.form.fn.attr";
78
- const UI_FORM_FN_VALUE = "ui.form.fn.value";
79
- const UI_FORM_FN_CLASSES = "ui.form.fn.classes";
80
- const UI_FORM_FN_STYLES = "ui.form.fn.styles";
81
- const UI_FORM_FN_TITLE = "ui.form.fn.title";
82
- const UI_FORM_FN_SUBMIT_TEXT = "ui.form.fn.submit.text";
83
- const UI_FORM_FN_SUBMIT_DISABLED = "ui.form.fn.submit.disabled";
84
- const UI_TABLE_FN_PREFIX = "ui.table.fn.";
85
- const UI_TABLE_FN_ATTR = "ui.table.fn.attr";
86
- const UI_TABLE_FN_CLASSES = "ui.table.fn.classes";
87
- const UI_TABLE_FN_STYLES = "ui.table.fn.styles";
88
- const UI_FORM_VALIDATE = "ui.form.validate";
89
- //#endregion
90
- //#region src/form/types.ts
91
- /** Type guard: checks if a field def is an array field. */
92
- function isArrayField(field) {
93
- return field.type === "array";
94
- }
95
- /** Type guard: checks if a field def is an object field. */
96
- function isObjectField(field) {
97
- return field.type === "object";
98
- }
99
- /** Type guard: checks if a field def is a union field. */
100
- function isUnionField(field) {
101
- return field.type === "union";
102
- }
103
- /** Type guard: checks if a field def is a tuple field. */
104
- function isTupleField(field) {
105
- return field.type === "tuple";
106
- }
107
- //#endregion
108
- //#region src/shared/field-resolver.ts
109
- /** Static resolver — ignores fn keys, reads only static metadata. */
110
- var StaticFieldResolver = class {
111
- resolveFieldProp(prop, _fnKey, staticKey, _scope, opts) {
112
- return resolveStatic(prop.metadata, staticKey, opts);
113
- }
114
- resolveFormProp(type, _fnKey, staticKey, _scope, opts) {
115
- return resolveStatic(type.metadata, staticKey, opts);
116
- }
117
- hasComputedAnnotations(_prop) {
118
- return false;
119
- }
120
- };
121
- /** Resolves a static metadata value. Exported for reuse by dynamic resolvers. */
122
- function resolveStatic(metadata, staticKey, opts) {
123
- if (staticKey === void 0) return void 0;
124
- const staticVal = metadata.get(staticKey);
125
- if (staticVal !== void 0) {
126
- if (opts?.staticAsBoolean) return true;
127
- if (opts?.transform) return opts.transform(staticVal);
128
- return staticVal;
129
- }
130
- }
131
- /** Default static resolver instance. */
132
- const defaultResolver = new StaticFieldResolver();
133
- let activeResolver = defaultResolver;
134
- /** Replace the active resolver (called by ui-fns to install dynamic resolution). */
135
- function setResolver(resolver) {
136
- activeResolver = resolver;
137
- }
138
- /** Get the current active resolver. */
139
- function getResolver() {
140
- return activeResolver;
141
- }
142
- /** Resolve a field-level metadata property via the active resolver. */
143
- function resolveFieldProp(prop, fnKey, staticKey, scope, opts) {
144
- return activeResolver.resolveFieldProp(prop, fnKey, staticKey, scope, opts);
145
- }
146
- /** Resolve a form-level metadata property via the active resolver. */
147
- function resolveFormProp(type, fnKey, staticKey, scope, opts) {
148
- return activeResolver.resolveFormProp(type, fnKey, staticKey, scope, opts);
149
- }
150
- /** Check if a prop has dynamic annotations via the active resolver. */
151
- function hasComputedAnnotations(prop) {
152
- return activeResolver.hasComputedAnnotations(prop);
153
- }
154
- /**
155
- * SSOT for field hidden resolution — resolves `@ui.form.fn.hidden`
156
- * (dynamic, via the active resolver) with static `@ui.form.hidden`
157
- * presence as the fallback. Absent both → `false` (visible).
158
- */
159
- function isFieldHidden(prop, scope) {
160
- return resolveFieldProp(prop, "ui.form.fn.hidden", "ui.form.hidden", scope, { staticAsBoolean: true }) ?? false;
161
- }
162
- function getFieldMeta(prop, key) {
163
- return prop.metadata.get(key);
164
- }
165
- /** Checks whether a metadata key is present on an ATScript prop. */
166
- function hasFieldMeta(prop, key) {
167
- return prop.metadata.has(key);
168
- }
169
- /** Ensures a value is an array — returns as-is if already one, wraps in `[x]` otherwise. */
170
- function asArray(x) {
171
- return Array.isArray(x) ? x : [x];
172
- }
173
- /**
174
- * Parses static `ui.attr` metadata into a key-value record.
175
- * Exported so ui-fns can reuse this without duplicating the parsing logic.
176
- */
177
- function parseStaticAttrs(staticAttrs) {
178
- if (!staticAttrs) return void 0;
179
- const result = {};
180
- let hasAttrs = false;
181
- for (const item of asArray(staticAttrs)) if (typeof item === "object" && item !== null && "name" in item && "value" in item) {
182
- const { name, value } = item;
183
- result[name] = value;
184
- hasAttrs = true;
185
- }
186
- return hasAttrs ? result : void 0;
187
- }
188
- /**
189
- * Resolves `<staticKey>` + `<fnKey>` attr metadata on demand.
190
- * Defaults read `ui.form.attr` + `ui.form.fn.attr`; pass `{ staticKey, fnKey }` to read
191
- * the table-side pair (`ui.table.attr` + `ui.table.fn.attr`) or any other surface.
192
- */
193
- function resolveAttrs(prop, scope, keys = {}) {
194
- const staticKey = keys.staticKey ?? "ui.form.attr";
195
- const fnKey = keys.fnKey ?? "ui.form.fn.attr";
196
- const staticAttrs = getFieldMeta(prop, staticKey);
197
- const fnAttrs = getFieldMeta(prop, fnKey);
198
- if (!staticAttrs && !fnAttrs) return void 0;
199
- const result = {};
200
- let hasAttrs = false;
201
- const parsed = parseStaticAttrs(staticAttrs);
202
- if (parsed) {
203
- Object.assign(result, parsed);
204
- hasAttrs = true;
205
- }
206
- if (fnAttrs) {
207
- const resolved = resolveFieldProp(prop, fnKey, void 0, scope);
208
- if (resolved) {
209
- Object.assign(result, resolved);
210
- hasAttrs = true;
211
- }
212
- }
213
- return hasAttrs ? result : void 0;
214
- }
215
- //#endregion
216
- //#region src/value-help/extract-literals.ts
217
- /**
218
- * Extracts options from a union of literal types (e.g. 'a' | 'b' | 'c').
219
- * Returns undefined if the type is not a pure union of literals.
220
- *
221
- * Handles nested unions created by flattenAnnotatedType, which recurses
222
- * into union items and produces synthetic unions containing both individual
223
- * literals and the original union type as nested items.
224
- */
225
- function extractLiteralOptions(prop, outer) {
226
- if (prop.type.kind !== "union") return void 0;
227
- const result = collectLiterals(prop.type.items, /* @__PURE__ */ new Set());
228
- if (!result || result.length === 0) return void 0;
229
- const labels = [prop, outer].flatMap((node) => node?.metadata.get("ui.literalLabel") ?? []);
230
- if (labels.length) {
231
- const byValue = new Map(labels.map((l) => [l.value, l.label]));
232
- for (const option of result) option.label = byValue.get(option.key) ?? option.label;
233
- }
234
- return result;
235
- }
236
- /**
237
- * The literal options of a field: a literal union's, or those of an array of one
238
- * (`tags: Tag[]`), where the array prop's own `@ui.literalLabel` labels win over the
239
- * element type's. `undefined` when the field is neither. Since 0.1.148.
240
- */
241
- function extractFieldLiteralOptions(prop) {
242
- if (prop.type.kind === "array") return extractLiteralOptions(prop.type.of, prop);
243
- return extractLiteralOptions(prop);
244
- }
245
- /** Returns true when the annotated type is a union composed entirely of literal values. */
246
- function isPureLiteralUnion(prop) {
247
- if (prop.type.kind !== "union") return false;
248
- return checkAllLiterals(prop.type.items);
249
- }
250
- /** Walks union items returning true only if every leaf is a literal value. */
251
- function checkAllLiterals(items) {
252
- for (const item of items) {
253
- if (item.type.kind === "" && item.type.value !== void 0) continue;
254
- if (item.type.kind === "union") {
255
- if (!checkAllLiterals(item.type.items)) return false;
256
- continue;
257
- }
258
- return false;
259
- }
260
- return items.length > 0;
261
- }
262
- /**
263
- * Recursively collects literal values from union items.
264
- * Returns null if any non-literal, non-union item is found (invalid union).
265
- * Returns empty array when all items are valid but already seen (deduped).
266
- */
267
- function collectLiterals(items, seen) {
268
- const result = [];
269
- for (const item of items) if (item.type.kind === "" && item.type.value !== void 0) {
270
- const raw = item.type.value;
271
- const val = String(raw);
272
- if (!seen.has(val)) {
273
- seen.add(val);
274
- result.push({
275
- key: val,
276
- label: val,
277
- value: raw
278
- });
279
- }
280
- } else if (item.type.kind === "union") {
281
- const nested = collectLiterals(item.type.items, seen);
282
- if (nested === null) return null;
283
- result.push(...nested);
284
- } else return null;
285
- return result;
286
- }
287
- //#endregion
288
- //#region src/value-help/filter-tree.ts
289
- function isFieldRef(value) {
290
- return value !== null && typeof value === "object" && "field" in value;
291
- }
292
- /**
293
- * A deliberate copy of `translateQueryTree` from `@atscript/db`: that module is a
294
- * server-side runtime, and importing it would pull `@atscript/db` into the browser
295
- * bundle. `filter-tree.spec.ts` guards the two against drift.
296
- */
297
- function translate(node) {
298
- if (Array.isArray(node.$and)) return { $and: node.$and.map(translate) };
299
- if (Array.isArray(node.$or)) return { $or: node.$or.map(translate) };
300
- if (node.$not && typeof node.$not === "object") return { $not: translate(node.$not) };
301
- const left = node.left.field;
302
- const op = node.op;
303
- const right = node.right;
304
- if (isFieldRef(right)) return { [left]: { [op]: { $field: right.field } } };
305
- if (op === "$exists") return { [left]: { $exists: right !== false } };
306
- return { [left]: { [op]: right } };
307
- }
308
- /**
309
- * Fields the tree pins to one value (`=` comparison against a literal) at its top-level
310
- * `and` chain. The runtime twin of `pinnedFields` in `plugin/value-help-validation.ts`
311
- * (which reads the source predicate) — keep the two rules in step.
312
- */
313
- function pinnedOf(node, out) {
314
- if (Array.isArray(node.$and)) for (const n of node.$and) pinnedOf(n, out);
315
- else if (node.left && node.op === "$eq" && !isFieldRef(node.right)) out.push(node.left.field);
316
- }
317
- /**
318
- * Translates the static `filter` of a `@ui.valueHelp` binding into a Uniquery
319
- * `FilterExpr` (mirrors `translateQueryTree` of `@atscript/db`, with refs
320
- * resolved to the plain field path), plus the target fields it pins with `=` —
321
- * constant inside the picker, so their columns are hidden. Since 0.1.148.
322
- */
323
- function valueHelpFilter(tree) {
324
- const pinned = [];
325
- pinnedOf(tree, pinned);
326
- return {
327
- filter: translate(tree),
328
- pinned: [...new Set(pinned)]
329
- };
330
- }
331
- //#endregion
332
- //#region src/value-help/extract-ref.ts
333
- /**
334
- * Hard cap on how many `.ref` hops the chain walk follows. Real chains are one
335
- * or two hops (view field → table field → dictionary); the cap is a backstop,
336
- * not a modelling limit — and it is also what terminates a cyclic chain.
337
- */
338
- const MAX_REF_CHAIN_DEPTH = 8;
339
- /**
340
- * `@db.http.path` of a binding target. Two producers, two shapes — `/meta`
341
- * deserialization does not normalize annotation values, so both are read here:
342
- *
343
- * - compiled `.as` (the atscript runtime): the annotated type itself (a class
344
- * with a `metadata` Map) or a getter `() => Type` for a cross-file ref;
345
- * - `/meta` (the serialized type): a shallow target `{ id, metadata }` whose
346
- * `metadata` is a plain record.
347
- *
348
- * Also accepts `{ type: () => Type }`.
349
- */
350
- function bindingTargetPath(target) {
351
- if (target === null || typeof target !== "object" && typeof target !== "function") return;
352
- const t = target;
353
- if (typeof target === "function" && t.metadata === void 0) return bindingTargetPath(target());
354
- if (t.metadata instanceof Map) return t.metadata.get(DB_HTTP_PATH);
355
- if (t.metadata && typeof t.metadata === "object") return t.metadata[DB_HTTP_PATH];
356
- return t.type === void 0 ? void 0 : bindingTargetPath(t.type);
357
- }
358
- /**
359
- * The `@ui.valueHelp` binding of a node, when its target is served by a
360
- * controller (`@db.http.path`). Without a path the binding is ignored and the
361
- * caller falls back to the FK walk.
362
- */
363
- function bindingInfo(node) {
364
- const binding = node.metadata.get(UI_VALUE_HELP);
365
- if (!binding?.field) return void 0;
366
- const url = bindingTargetPath(binding.target);
367
- if (!url) return void 0;
368
- const info = {
369
- url,
370
- targetField: binding.field
371
- };
372
- if (binding.filter) {
373
- const { filter, pinned } = valueHelpFilter(binding.filter);
374
- info.filter = filter;
375
- if (pinned.length > 0) info.pinned = pinned;
376
- }
377
- return info;
378
- }
379
- /**
380
- * Synchronous probe. Returns `{ url, targetField }` for the first link of the
381
- * reference chain starting at `prop` that carries a `@ui.valueHelp` binding
382
- * (since 0.1.148 — an explicit binding beats `@db.rel.FK`, and also supplies
383
- * the static `filter` / `pinned` fields), or that satisfies all three conditions:
384
- *
385
- * 1. the link carries `@db.rel.FK`,
386
- * 2. the link has a `.ref`,
387
- * 3. the ref's target metadata carries `@db.http.path`.
388
- *
389
- * Since 0.1.134 the probe follows **reference chains**: when a link does not
390
- * qualify, it hops onto the referenced field (`ref.type()` → that object's
391
- * `props[ref.field]`) and re-tests. A view field declared as
392
- * `errorCode: Issue.errorCode`, where `Issue.errorCode: ErrorCode.code` is the
393
- * link carrying `@db.rel.FK`, therefore keeps its value help instead of losing
394
- * the dictionary.
395
- *
396
- * This mirrors what the server already does on the `/meta` path: since
397
- * `@atscript/db` 0.1.128 the serialized meta collapses such chains onto the
398
- * terminal field (`ref` → terminal, `db.rel.FK: true`), so a form def built
399
- * from `/meta` and one built from the compiled `.as` type land on the same
400
- * dictionary.
401
- *
402
- * The walk is bounded ({@link MAX_REF_CHAIN_DEPTH}), which is also what makes a
403
- * cyclic chain terminate (it runs out of hops and gives up instead of looping).
404
- * It stops as soon as a link has no `.ref`, or the referenced
405
- * field cannot be found — e.g. behind a shallow `{ id, metadata }` ref target
406
- * from `/meta`, which carries no props (and needs none: the server already
407
- * resolved the chain).
408
- */
409
- function extractValueHelp(prop) {
410
- let node = prop;
411
- for (let depth = 0; node && depth < MAX_REF_CHAIN_DEPTH; depth++) {
412
- const bound = bindingInfo(node);
413
- if (bound) return bound;
414
- const ref = node.ref;
415
- if (!ref) return void 0;
416
- const target = ref.type();
417
- if (!target) return void 0;
418
- if (node.metadata.has("db.rel.FK")) {
419
- const url = target.metadata.get(DB_HTTP_PATH);
420
- if (url) return {
421
- url,
422
- targetField: ref.field
423
- };
424
- }
425
- node = (target.type.kind === "object" ? target.type : void 0)?.props.get(ref.field);
426
- }
427
- }
428
- //#endregion
429
- //#region src/form/create-form-def.ts
430
- /** Known atscript primitive extension tags that map directly to field types. */
431
- const UI_TAGS = new Set([
432
- "action",
433
- "paragraph",
434
- "select",
435
- "radio",
436
- "checkbox"
437
- ]);
438
- const EDIT = { mode: "edit" };
439
- /**
440
- * Converts an ATScript annotated type into a FormDef.
441
- *
442
- * - **Object types** (`kind === 'object'`): produces an object root with nested fields.
443
- * - **Non-object types** (primitive, array, union, etc.): produces a single leaf root field
444
- * with `path: ''`.
445
- *
446
- * A `@db.column.derived` field is marked `derived` straight from its metadata;
447
- * a computed view column, from `opts.metaFields`; an update-stamped field
448
- * (see `CreateFormDefOptions.mode`), when `opts.mode` is `"edit"`.
449
- */
450
- function createFormDef(type, opts) {
451
- const edit = opts?.mode === "edit";
452
- if (type.type.kind !== "object") {
453
- const rootField = createFieldDef("", type, edit);
454
- const fields = [rootField];
455
- return {
456
- type,
457
- rootField,
458
- fields,
459
- mainFields: fields,
460
- pushDownFields: [],
461
- flatMap: /* @__PURE__ */ new Map()
462
- };
463
- }
464
- const objectType = type;
465
- const flatMap = (0, _atscript_typescript_utils.flattenAnnotatedType)(objectType, { excludePhantomTypes: false });
466
- const fields = [];
467
- const structuredPrefixes = /* @__PURE__ */ new Set();
468
- for (const [path, prop] of flatMap.entries()) {
469
- if (path === "") continue;
470
- if (path === opts?.versionColumn) continue;
471
- if (isChildOfStructured(path, structuredPrefixes)) continue;
472
- const originalProp = resolveOriginalProp(objectType, path) ?? prop;
473
- const kind = originalProp.type.kind;
474
- if (kind === "object" && !isStructuredObject(originalProp)) continue;
475
- if (kind === "array") {
476
- if (originalProp.type.of.type.kind === "array" && !getFieldMeta(originalProp, "ui.form.component")) continue;
477
- }
478
- if (kind === "array" || kind === "object" || kind === "union" || kind === "tuple") structuredPrefixes.add(path + ".");
479
- const field = createFieldDef(path, originalProp, edit);
480
- if (opts?.metaFields?.[path]?.computed) field.derived = true;
481
- fields.push(field);
482
- }
483
- const orderMap = new Map(fields.map((f) => [f, getFieldMeta(f.prop, "ui.form.order") ?? Infinity]));
484
- fields.sort((a, b) => orderMap.get(a) - orderMap.get(b));
485
- const rootField = {
486
- path: "",
487
- prop: type,
488
- type: "object",
489
- phantom: false,
490
- name: "",
491
- allStatic: false,
492
- pushDown: false
493
- };
494
- let mainFields = fields;
495
- const pushDownFields = [];
496
- if (fields.some((f) => f.pushDown)) {
497
- mainFields = [];
498
- for (const f of fields) (f.pushDown ? pushDownFields : mainFields).push(f);
499
- }
500
- const def = {
501
- type,
502
- rootField,
503
- fields,
504
- mainFields,
505
- pushDownFields,
506
- flatMap
507
- };
508
- rootField.objectDef = def;
509
- return def;
510
- }
511
- /**
512
- * Creates a FormFieldDef from any ATScript annotated type. `edit`: the form
513
- * edits a stored row (`CreateFormDefOptions.mode`).
514
- */
515
- function createFieldDef(path, prop, edit = false) {
516
- const kind = prop.type.kind;
517
- const name = path.slice(path.lastIndexOf(".") + 1);
518
- const allStatic = !hasComputedAnnotations(prop);
519
- const uiType = getFieldMeta(prop, "ui.form.type") ?? getFieldMeta(prop, "ui.type");
520
- const pushDown = getFieldMeta(prop, UI_FORM_PUSH_DOWN) !== void 0;
521
- const valueHelpInfo = extractValueHelp(prop);
522
- const derived = getFieldMeta(prop, "db.column.derived") !== void 0 || edit && path !== "" && isUpdateStamped(prop);
523
- const base = {
524
- path,
525
- prop,
526
- phantom: false,
527
- name,
528
- allStatic,
529
- pushDown,
530
- valueHelpInfo,
531
- ...derived && { derived: true }
532
- };
533
- const customType = uiType;
534
- if (kind === "array") {
535
- const arrayType = prop.type;
536
- const isMultiselect = customType === "multiselect" || getFieldMeta(prop, "ui.form.options") !== void 0 || getFieldMeta(prop, "ui.form.fn.options") !== void 0 || isPureLiteralUnion(arrayType.of);
537
- return {
538
- ...base,
539
- type: "array",
540
- customType: isMultiselect ? "multiselect" : customType,
541
- itemType: arrayType.of,
542
- itemField: createFieldDef("", arrayType.of, edit)
543
- };
544
- }
545
- if (kind === "object") return {
546
- ...base,
547
- type: "object",
548
- customType,
549
- objectDef: createFormDef(prop, edit ? EDIT : void 0)
550
- };
551
- if (kind === "union") {
552
- if (isPureLiteralUnion(prop)) return {
553
- ...base,
554
- type: uiType ?? "select"
555
- };
556
- const unionVariants = createUnionVariants(prop, edit && soleValueMember(prop) !== void 0);
557
- if (unionVariants.length > 1) return {
558
- ...base,
559
- type: "union",
560
- customType,
561
- unionVariants
562
- };
563
- const v = unionVariants[0];
564
- if (v?.itemField) return {
565
- ...v.itemField,
566
- path,
567
- name,
568
- allStatic,
569
- pushDown,
570
- ...derived && { derived: true }
571
- };
572
- if (v?.def) return {
573
- ...base,
574
- type: "object",
575
- customType,
576
- objectDef: v.def
577
- };
578
- }
579
- if (kind === "tuple") {
580
- const tupleType = prop.type;
581
- return {
582
- ...base,
583
- type: "tuple",
584
- customType,
585
- itemFields: tupleType.items.map((item, i) => {
586
- const field = createFieldDef(String(i), item);
587
- field.name = "";
588
- return field;
589
- })
590
- };
591
- }
592
- if (valueHelpInfo) return {
593
- ...base,
594
- type: uiType ?? "ref"
595
- };
596
- const tags = kind === "" ? prop.type.tags : void 0;
597
- let uiTag;
598
- let isTimestamp = false;
599
- if (tags) for (const t of tags) {
600
- if (uiTag === void 0 && UI_TAGS.has(t)) uiTag = t;
601
- if (t === "timestamp") isTimestamp = true;
602
- }
603
- const dt = kind === "" ? prop.type.designType : void 0;
604
- let numericType;
605
- if (kind === "") {
606
- const hasCurrency = getFieldMeta(prop, "db.amount.currency") !== void 0 || getFieldMeta(prop, "db.amount.currency.ref") !== void 0;
607
- const isDecimalDesign = dt === "decimal";
608
- if (hasCurrency) numericType = "decimal";
609
- else if (isDecimalDesign) numericType = "decimal";
610
- else if (dt === "number") {
611
- const hasUnit = getFieldMeta(prop, "db.unit") !== void 0 || getFieldMeta(prop, "db.unit.ref") !== void 0;
612
- const hasPrefix = getFieldMeta(prop, "ui.form.prefix") !== void 0 || getFieldMeta(prop, "ui.form.prefix.ref") !== void 0 || getFieldMeta(prop, "ui.form.prefix.icon") !== void 0;
613
- const hasSuffix = getFieldMeta(prop, "ui.form.suffix") !== void 0 || getFieldMeta(prop, "ui.form.suffix.ref") !== void 0 || getFieldMeta(prop, "ui.form.suffix.icon") !== void 0;
614
- if (hasUnit || hasPrefix || hasSuffix) numericType = "number";
615
- }
616
- }
617
- const tagType = isTimestamp ? "datetime" : void 0;
618
- return {
619
- ...base,
620
- type: uiType ?? uiTag ?? numericType ?? tagType ?? (dt === "number" ? "number" : dt === "boolean" ? "checkbox" : "text"),
621
- phantom: kind === "" && dt === "phantom"
622
- };
623
- }
624
- /** Non-`ui.form.*` keys that still address the object itself. */
625
- const OBJECT_IDENTITY_KEYS = new Set([
626
- META_LABEL,
627
- META_DESCRIPTION,
628
- UI_TYPE
629
- ]);
630
- const UI_FORM_NS = "ui.form.";
631
- /** `ui.form.*` keys that place a field rather than give it an identity. */
632
- const UI_FORM_PLACEMENT_NS = "ui.form.grid.";
633
- /**
634
- * Whether an object prop renders as a field of its own rather than being
635
- * flattened into its parent.
636
- *
637
- * Any `@ui.form.*` annotation (plus `@meta.label` / `@meta.description` /
638
- * `@ui.type`) means the author addressed the object itself, so it needs a
639
- * field to carry that instruction to a renderer — a collapsible section, or
640
- * whatever `@ui.form.component` / `@ui.form.type` names. An object with none
641
- * of them is a pure namespace: it is dropped and its children render inline
642
- * in the parent grid, which keeps DB-flattened structs (`addr.street` stored
643
- * as `addr__street`) from growing chrome nobody asked for. `@db.*`,
644
- * `@expect.*` and the rest of `@meta.*` stay out for exactly that reason —
645
- * they are what such a struct carries.
646
- *
647
- * Placement keys (`@ui.form.order`, `@ui.form.grid.*`) are excluded: they
648
- * position a field among its siblings, and a namespace has no position of its
649
- * own — its children carry their own.
650
- *
651
- * A prefix rule rather than a list because the list was wrong the moment it
652
- * was written. Matching on `@meta.label` and `@ui.form.component` alone left
653
- * every other key to be read off a prop that never became a field: a
654
- * `@meta.description` went missing, a `@ui.form.type` component silently
655
- * never mounted, `@ui.form.pushDown` never pushed down, and — the one that
656
- * mattered — `@ui.form.hidden` on a struct left every child on screen.
657
- */
658
- function isStructuredObject(prop) {
659
- for (const key of prop.metadata.keys()) {
660
- if (OBJECT_IDENTITY_KEYS.has(key)) return true;
661
- if (!key.startsWith(UI_FORM_NS)) continue;
662
- if (key === "ui.form.order" || key.startsWith(UI_FORM_PLACEMENT_NS)) continue;
663
- return true;
664
- }
665
- return false;
666
- }
667
- /** Resolves the original annotated type from the type hierarchy by path. */
668
- function resolveOriginalProp(type, path) {
669
- const parts = path.split(".");
670
- let current = type.type;
671
- for (let i = 0; i < parts.length - 1; i++) {
672
- const prop = current.props.get(parts[i]);
673
- if (!prop || prop.type.kind !== "object") return void 0;
674
- current = prop.type;
675
- }
676
- return current.props.get(parts[parts.length - 1]);
677
- }
678
- /** Check if a path is a child of any structured prefix (prefixes are pre-suffixed with "."). */
679
- function isChildOfStructured(path, prefixes) {
680
- for (const prefix of prefixes) if (path.startsWith(prefix)) return true;
681
- return false;
682
- }
683
- /**
684
- * Builds union variant definitions from a union annotated type.
685
- * Iterates top-level items directly — one variant per item.
686
- */
687
- function buildUnionVariants(typeDef) {
688
- return createUnionVariants(typeDef, false);
689
- }
690
- function createUnionVariants(typeDef, edit) {
691
- const items = typeDef.type.items ?? [typeDef];
692
- const variants = [];
693
- for (const item of items) {
694
- const v = createVariant(item, edit);
695
- if (items.length > 1) v.label = `${String(variants.length + 1)}. ${v.label}`;
696
- variants.push(v);
697
- }
698
- return variants;
699
- }
700
- /** Creates a single union variant from an annotated type item. */
701
- function createVariant(def, edit) {
702
- const kind = def.type.kind;
703
- if (kind === "object") {
704
- const label = getFieldMeta(def, "meta.label") ?? "Object";
705
- const hasComponent = getFieldMeta(def, UI_FORM_COMPONENT) !== void 0;
706
- return {
707
- label,
708
- type: def,
709
- def: createFormDef(def, edit ? EDIT : void 0),
710
- itemField: hasComponent ? createFieldDef("", def, edit) : void 0
711
- };
712
- }
713
- if (kind === "") {
714
- const dt = def.type.designType;
715
- return {
716
- label: capitalize(dt === "phantom" ? "item" : dt),
717
- type: def,
718
- itemField: createFieldDef("", def, edit),
719
- designType: dt
720
- };
721
- }
722
- return {
723
- label: capitalize(kind),
724
- type: def,
725
- itemField: createFieldDef("", def, edit)
726
- };
727
- }
728
- /**
729
- * An update-stamped field (see `CreateFormDefOptions.mode`). Read off the prop,
730
- * or — as `@atscript/db` does — off the one value member of `T | null`, unless
731
- * the prop references another field.
732
- */
733
- function isUpdateStamped(prop) {
734
- if ((0, _atscript_db_validator.isServerStampedOnUpdate)(prop.metadata)) return true;
735
- const member = prop.ref?.field ? void 0 : soleValueMember(prop);
736
- return member !== void 0 && (0, _atscript_db_validator.isServerStampedOnUpdate)(member.metadata);
737
- }
738
- /** The one non-`null` / `undefined` member of a (nested) union, if there is exactly one. */
739
- function soleValueMember(prop) {
740
- if (prop.type.kind !== "union") return void 0;
741
- const members = /* @__PURE__ */ new Set();
742
- const visit = (t) => {
743
- if (t.type.kind === "union") for (const item of t.type.items) visit(item);
744
- else if (t.type.kind !== "" || t.type.designType !== "null" && t.type.designType !== "undefined") members.add(t);
745
- };
746
- visit(prop);
747
- return members.size === 1 ? members.values().next().value : void 0;
748
- }
749
- function capitalize(s) {
750
- return s.charAt(0).toUpperCase() + s.slice(1);
751
- }
752
- //#endregion
753
- //#region src/form/form-actions.ts
754
- /**
755
- * Declared actions of a form — the union of `@ui.form.action` ids and
756
- * `@wf.action.withData` ids across all fields. `withData` distinguishes a
757
- * data-carrying workflow action (sends the current form payload) from a plain
758
- * stateless action. Single source of truth for "what actions can a host fire".
759
- */
760
- function getDeclaredFormActions(def) {
761
- const out = [];
762
- for (const field of def.fields) {
763
- const withData = getFieldMeta(field.prop, WF_ACTION_WITH_DATA);
764
- if (withData) {
765
- out.push({
766
- id: withData,
767
- withData: true
768
- });
769
- continue;
770
- }
771
- const plain = getFieldMeta(field.prop, UI_FORM_ACTION);
772
- if (plain?.id) out.push({
773
- id: plain.id,
774
- withData: false
775
- });
776
- }
777
- return out;
778
- }
779
- //#endregion
780
- //#region src/value-help/dict-paths.ts
781
- /**
782
- * Paths that make up the "dict view" of a value-help target:
783
- * PKs + label + descr + attr fields. Used by filter dialogs to clamp
784
- * visible columns to the dictionary subset.
785
- */
786
- function valueHelpDictPaths(resolved) {
787
- const paths = [
788
- ...resolved.primaryKeys,
789
- resolved.labelField,
790
- ...resolved.attrFields
791
- ];
792
- if (resolved.descrField) paths.push(resolved.descrField);
793
- return new Set(paths);
794
- }
795
- //#endregion
796
- //#region src/value-help/resolve-options.ts
797
- /** Extracts the key from an option entry. */
798
- function optKey(opt) {
799
- return typeof opt === "string" ? opt : opt.key;
800
- }
801
- /** Extracts the display label from an option entry. */
802
- function optLabel(opt) {
803
- return typeof opt === "string" ? opt : opt.label;
804
- }
805
- const labelMaps = /* @__PURE__ */ new WeakMap();
806
- /**
807
- * The display label of a literal-union column's option (`@ui.literalLabel`) for
808
- * `value` — `undefined` when the column has no options or none matches. Map-backed
809
- * per options array, so rendering a table does not scan the options per cell.
810
- * The one lookup behind the table cell, the filter chips, export and a custom cell.
811
- * Since 0.1.148.
812
- */
813
- function optionLabel(column, value) {
814
- const options = column.options;
815
- if (!options?.length) return void 0;
816
- if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") return;
817
- let labels = labelMaps.get(options);
818
- if (!labels) {
819
- labels = new Map(options.map((o) => [o.key, o.label]));
820
- labelMaps.set(options, labels);
821
- }
822
- return labels.get(String(value));
823
- }
824
- /**
825
- * Converts raw option annotation value to a normalized array.
826
- */
827
- function parseStaticOptions(raw) {
828
- return asArray(raw).map((item) => {
829
- if (typeof item === "object" && item !== null && "label" in item) {
830
- const { label, value } = item;
831
- return value !== void 0 ? {
832
- key: value,
833
- label
834
- } : label;
835
- }
836
- return String(item);
837
- });
838
- }
839
- /**
840
- * Resolves options from metadata with a fallback chain:
841
- * 1. `@ui.form.fn.options` (dynamic, compiled by ui-fns)
842
- * 2. `@ui.form.options` (static annotation)
843
- * 3. Literal union type extraction (auto-derived from type)
844
- * 4. Future: dictionary / value-help lookup
845
- */
846
- function resolveOptions(prop, scope) {
847
- const resolved = resolveFieldProp(prop, UI_FORM_FN_OPTIONS, UI_FORM_OPTIONS, scope, { transform: parseStaticOptions });
848
- if (resolved !== void 0) return resolved;
849
- return extractFieldLiteralOptions(prop);
850
- }
851
- //#endregion
852
- //#region src/shared/str.ts
853
- /** Converts a dot-path to a human-readable label (e.g. 'firstName' → 'First Name'). */
854
- function humanizePath(path) {
855
- return path.slice(path.lastIndexOf(".") + 1).replace(/([a-z])([A-Z])/g, "$1 $2").replace(/^./, (s) => s.toUpperCase());
856
- }
857
- /** Escape special regex characters in user input for safe embedding in a `$regex` filter. */
858
- function escapeRegex(input) {
859
- return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
860
- }
861
- /** Safely convert an unknown value to a string without triggering no-base-to-string lint errors. */
862
- function str(value) {
863
- if (typeof value === "string") return value;
864
- if (typeof value === "number" || typeof value === "bigint" || typeof value === "boolean") return `${value}`;
865
- return JSON.stringify(value) ?? "";
866
- }
867
- //#endregion
868
- //#region src/value-help/value-help-client.ts
869
- let cacheTtl = 5e3;
870
- let searches = /* @__PURE__ */ new WeakMap();
871
- /**
872
- * How long (ms) a settled value-help search is reused for an identical
873
- * search on the same client. Default 5000. `0` shares only searches still in
874
- * flight; a negative value turns sharing off. Server-side rendering never
875
- * shares (one process serves many viewers).
876
- */
877
- function setValueHelpCacheTtl(ms) {
878
- cacheTtl = ms;
879
- }
880
- /**
881
- * Drop shared value-help search results — for one `client`, or for every
882
- * client when omitted. Call after writing to a dictionary outside the
883
- * built-in table actions to make pickers refetch at once.
884
- */
885
- function invalidateValueHelpCache(client) {
886
- if (client) searches.get(client)?.clear();
887
- else searches = /* @__PURE__ */ new WeakMap();
888
- }
889
- function now() {
890
- return typeof performance === "undefined" ? Date.now() : performance.now();
891
- }
892
- /** Cache key of a plain-JSON request; `undefined` when it holds anything else (never shared). */
893
- function requestKey(request) {
894
- let plain = true;
895
- try {
896
- const key = JSON.stringify(request, (_k, v) => {
897
- if (typeof v === "function" || typeof v === "symbol") plain = false;
898
- else if (v !== null && typeof v === "object" && !Array.isArray(v)) {
899
- const proto = Object.getPrototypeOf(v);
900
- if (proto !== Object.prototype && proto !== null) plain = false;
901
- }
902
- return v;
903
- });
904
- return plain ? key : void 0;
905
- } catch {
906
- return;
907
- }
908
- }
909
- function sharedQuery(client, request) {
910
- const run = () => client.query(request);
911
- if (cacheTtl < 0 || typeof window === "undefined") return run();
912
- const key = requestKey(request);
913
- if (key === void 0) return run();
914
- let byKey = searches.get(client);
915
- if (!byKey) searches.set(client, byKey = /* @__PURE__ */ new Map());
916
- const hit = byKey.get(key);
917
- if (hit && (hit.settledAt === void 0 || now() - hit.settledAt < cacheTtl)) return hit.promise;
918
- const entry = { promise: run().then((items) => {
919
- entry.settledAt = now();
920
- return items;
921
- }, (err) => {
922
- if (byKey.get(key) === entry) byKey.delete(key);
923
- throw err;
924
- }) };
925
- byKey.set(key, entry);
926
- return entry.promise;
927
- }
928
- /**
929
- * Value-help query client. Wraps a `Client` from `@atscript/db-client`
930
- * with FK-specific search logic (regex fallback for non-searchable tables,
931
- * $select scoping).
932
- *
933
- * Consumers resolve the target's metadata once via `resolveValueHelp(url)`
934
- * and pass the resulting `ResolvedValueHelp` to `search()`. Label resolution
935
- * for cells is deliberately unsupported — cells always display raw ids.
936
- *
937
- * Identical searches on the same `Client` are shared (see
938
- * {@link setValueHelpCacheTtl}).
939
- */
940
- var ValueHelpClient = class {
941
- _client;
942
- constructor(client) {
943
- this._client = client;
944
- }
945
- /**
946
- * Search the target with value-help semantics.
947
- *
948
- * - If target is searchable → sends `$search` (server full-text)
949
- * - If not searchable → sends `$or` regex across select fields + exact PK match
950
- */
951
- async search(resolved, opts) {
952
- const mode = opts?.mode ?? "form";
953
- const limit = opts?.limit ?? 20;
954
- const valueField = opts?.valueField;
955
- const selectFields = opts?.select ?? computeSelectFields(resolved, mode, valueField);
956
- const text = opts?.text;
957
- const scope = opts?.filter;
958
- const controls = {
959
- $select: selectFields,
960
- $limit: limit
961
- };
962
- let filter = scope;
963
- if (text) if (resolved.searchable) controls.$search = text;
964
- else {
965
- const search = buildOrFilter(text, selectFields, valueField ?? resolved.primaryKeys[0] ?? resolved.labelField);
966
- filter = scope ? { $and: [scope, search] } : search;
967
- }
968
- const items = await sharedQuery(this._client, {
969
- ...filter && { filter },
970
- controls
971
- });
972
- return { items: Array.isArray(items) ? items.slice() : items };
973
- }
974
- };
975
- /**
976
- * Compute the $select fields for a value-help query — always including the
977
- * `valueField` the picker commits (a unique non-PK field is otherwise never fetched).
978
- */
979
- function computeSelectFields(resolved, mode, valueField) {
980
- const fields = [...resolved.primaryKeys, resolved.labelField];
981
- if (valueField) fields.push(valueField);
982
- if (resolved.descrField) fields.push(resolved.descrField);
983
- if (mode === "filter") fields.push(...resolved.attrFields);
984
- return [...new Set(fields)];
985
- }
986
- /**
987
- * Build a Uniquery `$or` filter for value-help search across multiple fields.
988
- * Uses regex startsWith (case-insensitive) on text fields + exact match on PK.
989
- */
990
- function buildOrFilter(text, fields, pkField) {
991
- const escaped = escapeRegex(text);
992
- const conditions = [];
993
- for (const field of fields) if (field !== pkField) conditions.push({ [field]: { $regex: `/^${escaped}/i` } });
994
- const asNum = Number(text);
995
- if (!Number.isNaN(asNum)) conditions.push({ [pkField]: asNum });
996
- else conditions.push({ [pkField]: text });
997
- return { $or: conditions };
998
- }
999
- //#endregion
1000
- //#region src/value-help/distinct-client.ts
1001
- /**
1002
- * `true` for a 4xx answer — the server declined this picker (gate, ARBAC, unknown field).
1003
- * @internal Shared with `@atscript/vue-table`.
1004
- */
1005
- function isPickerDeclined(err) {
1006
- const status = err?.status;
1007
- return typeof status === "number" && status >= 400 && status < 500;
1008
- }
1009
- /**
1010
- * Distinct values of one column of the table behind `client`, via
1011
- * `/query?$groupBy=<field>`. All server gates (hidden field, ARBAC `$groupBy`
1012
- * control, row scope, write-only, encrypted) apply as for any grouped read; a
1013
- * 4xx rejects with a `ClientError` — see {@link isPickerDeclined}.
1014
- * `hasMore` tells whether another page follows.
1015
- *
1016
- * @internal Backs the distinct-values picker of `@atscript/vue-table`.
1017
- */
1018
- async function fetchDistinctValues(client, field, opts = {}) {
1019
- const limit = opts.limit ?? 50;
1020
- const text = opts.text?.trim();
1021
- const conditions = [];
1022
- if (opts.filter) conditions.push(opts.filter);
1023
- if (text) if (opts.numeric) {
1024
- const n = Number(text);
1025
- if (!Number.isFinite(n)) return {
1026
- items: [],
1027
- hasMore: false
1028
- };
1029
- conditions.push({ [field]: n });
1030
- } else conditions.push({ [field]: { $regex: `/^${escapeRegex(text)}/i` } });
1031
- const filter = conditions.length > 1 ? { $and: conditions } : conditions[0];
1032
- const rows = await client.aggregate({
1033
- ...filter && { filter },
1034
- controls: {
1035
- $groupBy: [field],
1036
- $select: [field],
1037
- ...opts.sortable && { $sort: { [field]: 1 } },
1038
- $limit: limit + 1,
1039
- $skip: opts.skip ?? 0
1040
- }
1041
- });
1042
- return {
1043
- items: rows.slice(0, limit).map((r) => r[field]).filter((v) => v !== null && v !== void 0),
1044
- hasMore: rows.length > limit
1045
- };
1046
- }
1047
- //#endregion
1048
- //#region src/client-factory.ts
1049
- const builtin = (url, options) => new _atscript_db_client.Client(url, options);
1050
- let _default = builtin;
1051
- /**
1052
- * Override the app-wide default factory. Call once at startup (e.g. in
1053
- * `entry-client.ts`) to wire shared fetch, credentials, error handling, etc.
1054
- * Every table, value-help picker, and other client consumer will pick it up.
1055
- */
1056
- function setDefaultClientFactory(factory) {
1057
- _default = factory;
1058
- }
1059
- /** Current app-wide default factory. Falls back to `new Client(url, options)`. */
1060
- function getDefaultClientFactory() {
1061
- return _default;
1062
- }
1063
- /** Reset the default factory to the built-in one (primarily for tests). */
1064
- function resetDefaultClientFactory() {
1065
- _default = builtin;
1066
- }
1067
- //#endregion
1068
- //#region src/form/measurement.ts
1069
- /**
1070
- * Read measurement annotations off a single field prop. Returns `undefined`
1071
- * for any annotation that's absent — callers can spread the result into a
1072
- * larger record.
1073
- */
1074
- function extractMeasurement(prop) {
1075
- const precisionMeta = getFieldMeta(prop, DB_COLUMN_PRECISION);
1076
- return {
1077
- currencyCode: getFieldMeta(prop, DB_AMOUNT_CURRENCY),
1078
- currencyRefField: getFieldMeta(prop, DB_AMOUNT_CURRENCY_REF),
1079
- unitCode: getFieldMeta(prop, DB_UNIT),
1080
- unitRefField: getFieldMeta(prop, DB_UNIT_REF),
1081
- precisionScale: precisionMeta?.scale
1082
- };
1083
- }
1084
- //#endregion
1085
- //#region src/table/create-table-def.ts
1086
- /**
1087
- * Builds a TableDef from a moost-db MetaResponse.
1088
- *
1089
- * 1. Deserializes `meta.type` into a live TAtscriptAnnotatedType
1090
- * 2. Flattens to discover all field paths
1091
- * 3. Builds ColumnDef per field using annotations + meta.fields capabilities
1092
- * 4. Sorts by @ui.table.order
1093
- */
1094
- function createTableDef(meta, preDeserializedType) {
1095
- const type = preDeserializedType ?? (0, _atscript_typescript_utils.deserializeAnnotatedType)(meta.type);
1096
- const flatMap = type.type.kind === "object" ? (0, _atscript_typescript_utils.flattenAnnotatedType)(type, { excludePhantomTypes: true }) : /* @__PURE__ */ new Map();
1097
- const columns = [];
1098
- for (const [path, prop] of flatMap.entries()) {
1099
- if (path === "") continue;
1100
- if (path === meta.versionColumn) continue;
1101
- const fieldMeta = meta.fields[path];
1102
- if (!isReadable(fieldMeta)) continue;
1103
- if (getFieldMeta(prop, "ui.table.exclude") !== void 0) continue;
1104
- const options = extractFieldLiteralOptions(prop);
1105
- const valueHelpInfo = extractValueHelp(prop);
1106
- let distinct;
1107
- if (!valueHelpInfo && !options && fieldMeta.groupable && fieldMeta.filterable) {
1108
- const url = type.metadata.get(DB_HTTP_PATH);
1109
- if (url && getFieldMeta(prop, "ui.valueHelp.distinct") !== void 0) distinct = {
1110
- url,
1111
- field: path
1112
- };
1113
- }
1114
- columns.push(buildColumn(path, prop, fieldMeta, {
1115
- options,
1116
- valueHelpInfo,
1117
- distinct
1118
- }));
1119
- }
1120
- if (meta.decorations) {
1121
- const decoType = (0, _atscript_typescript_utils.deserializeAnnotatedType)(meta.decorations);
1122
- if (decoType.type.kind === "object") for (const [path, prop] of decoType.type.props) {
1123
- const fieldMeta = meta.fields[path];
1124
- if (!fieldMeta?.decoration || flatMap.has(path)) continue;
1125
- if (getFieldMeta(prop, "ui.table.exclude") !== void 0) continue;
1126
- flatMap.set(path, prop);
1127
- columns.push(buildColumn(path, prop, fieldMeta, { options: extractFieldLiteralOptions(prop) }));
1128
- }
1129
- }
1130
- columns.sort((a, b) => a.order - b.order);
1131
- const actions = groupActions(meta.actions ?? []);
1132
- const crud = meta.crud ?? {};
1133
- const preferredId = meta.preferredId ?? meta.primaryKeys;
1134
- return {
1135
- type,
1136
- columns,
1137
- flatMap,
1138
- fetchableFields: new Set(Object.keys(meta.fields).filter((p) => isReadable(meta.fields[p]))),
1139
- primaryKeys: meta.primaryKeys,
1140
- preferredId,
1141
- identifierFields: identifierFieldsOf(preferredId, meta.actions ?? []),
1142
- versionColumn: meta.versionColumn,
1143
- crud,
1144
- canRemove: "remove" in crud,
1145
- actions,
1146
- searchable: meta.searchable,
1147
- vectorSearchable: meta.vectorSearchable,
1148
- searchIndexes: meta.searchIndexes,
1149
- relations: meta.relations
1150
- };
1151
- }
1152
- /**
1153
- * One column. A server-declared display-only column (`fieldMeta.decoration`)
1154
- * is never sortable, filterable or groupable and always nullable (a decoration
1155
- * can be absent); an ordinary one takes its capabilities from `/meta`.
1156
- */
1157
- function buildColumn(path, prop, fieldMeta, resolved) {
1158
- const { options, valueHelpInfo, distinct } = resolved;
1159
- const maxLengthMeta = getFieldMeta(prop, EXPECT_MAX_LENGTH);
1160
- const tableType = getFieldMeta(prop, UI_TABLE_TYPE);
1161
- const sharedType = getFieldMeta(prop, UI_TYPE);
1162
- const tableComponent = getFieldMeta(prop, UI_TABLE_COMPONENT);
1163
- const decoration = fieldMeta.decoration === true;
1164
- const filterOps = decoration ? void 0 : fieldMeta.filterOps;
1165
- return {
1166
- path,
1167
- label: getFieldMeta(prop, "meta.label") ?? humanizePath(path),
1168
- type: tableType ?? sharedType ?? (valueHelpInfo ? "ref" : inferDisplayType(prop, options)),
1169
- valueKind: inferValueKind(prop),
1170
- component: tableComponent,
1171
- selectWith: getFieldMeta(prop, UI_TABLE_SELECT_WITH),
1172
- sortable: !decoration && (fieldMeta.sortable ?? false),
1173
- filterable: !decoration && (fieldMeta.filterable ?? false),
1174
- ...filterOps && { filterOps: [...filterOps] },
1175
- nullable: decoration || prop.optional === true,
1176
- width: getFieldMeta(prop, UI_TABLE_WIDTH),
1177
- maxLen: maxLengthMeta?.length,
1178
- order: getFieldMeta(prop, "ui.table.order") ?? Infinity,
1179
- options,
1180
- valueHelpInfo,
1181
- ...distinct && { distinct },
1182
- ...extractMeasurement(prop)
1183
- };
1184
- }
1185
- /**
1186
- * `preferredId` ∪ every delegated action's `idMap` paths, in that order —
1187
- * the same array when no action carries an `idMap`.
1188
- */
1189
- function identifierFieldsOf(preferredId, actions) {
1190
- let out;
1191
- for (const a of actions) {
1192
- if (!a.idMap) continue;
1193
- for (const path of Object.values(a.idMap)) {
1194
- if (preferredId.includes(path) || out?.includes(path)) continue;
1195
- (out ??= [...preferredId]).push(path);
1196
- }
1197
- }
1198
- return out ?? preferredId;
1199
- }
1200
- /** A field the caller may read: listed in `meta.fields` and not write-only. */
1201
- function isReadable(field) {
1202
- return field !== void 0 && field.writeOnly !== true;
1203
- }
1204
- /** Sort by (order ?? 0). `toSorted` is stable per spec, so ties preserve declaration order. */
1205
- function byOrder(xs) {
1206
- return xs.toSorted((x, y) => (x.order ?? 0) - (y.order ?? 0));
1207
- }
1208
- /**
1209
- * Partition actions by `level`, sort each group by `(order ?? 0)` then
1210
- * declaration order, and pick the first `default: true` entry per level.
1211
- * The synthesised `__remove` UI action lives outside this set and is never
1212
- * a candidate for `default.row`.
1213
- */
1214
- function groupActions(actions) {
1215
- const table = [];
1216
- const row = [];
1217
- const rows = [];
1218
- for (const a of actions) if (a.level === "table") table.push(a);
1219
- else if (a.level === "row") row.push(a);
1220
- else if (a.level === "rows") rows.push(a);
1221
- const tableSorted = byOrder(table);
1222
- const rowSorted = byOrder(row);
1223
- const rowsSorted = byOrder(rows);
1224
- return {
1225
- table: tableSorted,
1226
- row: rowSorted,
1227
- rows: rowsSorted,
1228
- default: {
1229
- table: tableSorted.find((a) => a.default === true),
1230
- row: rowSorted.find((a) => a.default === true),
1231
- rows: rowsSorted.find((a) => a.default === true)
1232
- }
1233
- };
1234
- }
1235
- /** Infers a display type string from the annotated type's kind and designType. */
1236
- function inferDisplayType(prop, literalOpts) {
1237
- const kind = prop.type.kind;
1238
- if (kind === "array") return "array";
1239
- if (kind === "object") return "object";
1240
- if (kind === "union") return literalOpts !== void 0 ? "enum" : "union";
1241
- if (kind === "") {
1242
- const final = prop.type;
1243
- const dt = final.designType;
1244
- if (dt === "number") return final.tags?.has("timestamp") ? "datetime" : "number";
1245
- if (dt === "decimal") return "number";
1246
- if (dt === "boolean") return "boolean";
1247
- return "text";
1248
- }
1249
- return "text";
1250
- }
1251
- /**
1252
- * Number metadata that makes the server treat a plain `number` column as an
1253
- * integer (mirrors the db layer's `valueTypeOf`), beside the `int` / `expect.int` tags.
1254
- */
1255
- const INTEGER_NUMBER_META = [
1256
- "expect.int",
1257
- "db.default.increment",
1258
- "db.default.now",
1259
- "db.agg.count",
1260
- "db.agg.countDistinct"
1261
- ];
1262
- /** The kind of one scalar leaf, or `undefined` for a non-scalar / unknown design type. */
1263
- function scalarValueKind(prop) {
1264
- const final = prop.type;
1265
- const tags = final.tags;
1266
- switch (final.designType) {
1267
- case "string": return tags?.has("isoDate") ? "isoDate" : tags?.has("date") ? "date" : "string";
1268
- case "number":
1269
- if (tags?.has("timestamp")) return "timestamp";
1270
- if (tags?.has("int") || INTEGER_NUMBER_META.some((k) => prop.metadata.has(k))) return "integer";
1271
- return "number";
1272
- case "decimal": return "decimal";
1273
- case "boolean": return "boolean";
1274
- default: return;
1275
- }
1276
- }
1277
- /** Kinds of every non-null leaf of a (possibly nested) union; `null` when one is not a scalar. */
1278
- function collectUnionKinds(items, out) {
1279
- for (const item of items) {
1280
- if (item.type.kind === "union") {
1281
- collectUnionKinds(item.type.items, out);
1282
- continue;
1283
- }
1284
- if (item.type.kind === "") {
1285
- const dt = item.type.designType;
1286
- if (dt === "null" || dt === "undefined") continue;
1287
- out.add(scalarValueKind(item));
1288
- continue;
1289
- }
1290
- out.add(void 0);
1291
- }
1292
- }
1293
- /**
1294
- * Scalar storage kind of the column's value — what the server's filter guard
1295
- * checks. A scalar maps to its kind; a union that agrees on one kind across
1296
- * its non-null members (`'a' | 'b'`, `1 | 2`, `number.timestamp | null`)
1297
- * takes it; arrays, objects, JSON and mixed unions have none (`undefined`),
1298
- * which means no value coercion.
1299
- */
1300
- function inferValueKind(prop) {
1301
- const kind = prop.type.kind;
1302
- if (kind === "") return scalarValueKind(prop);
1303
- if (kind !== "union") return void 0;
1304
- const kinds = /* @__PURE__ */ new Set();
1305
- collectUnionKinds(prop.type.items, kinds);
1306
- if (kinds.size !== 1) return void 0;
1307
- return [...kinds][0];
1308
- }
1309
- //#endregion
1310
- //#region src/shared/meta-cache.ts
1311
- /**
1312
- * Enough for every URL a page touches — a table, the dictionaries its
1313
- * filters and forms pick from — plus the recent navigation history, so going
1314
- * back is instant; small enough to cap a long session at a few MB of parsed
1315
- * `/meta`. Twice the `@atscript/db-client` `MetaStore` body limit, since
1316
- * parametric URLs share bodies.
1317
- */
1318
- const DEFAULT_MAX_ENTRIES = 100;
1319
- let maxEntries = DEFAULT_MAX_ENTRIES;
1320
- /** Per-URL entries, least recently used first. Browser only. */
1321
- const cache = /* @__PURE__ */ new Map();
1322
- const slots = /* @__PURE__ */ new WeakMap();
1323
- /** Derived shapes per `ETag`, counted by the cached entries that use them. Browser only. */
1324
- const derivedByEtag = /* @__PURE__ */ new Map();
1325
- /** Custom `/meta` stores of cached clients, counted by the entries that use them. */
1326
- const customStores = /* @__PURE__ */ new Map();
1327
- /** `undefined` until the first `setMetaCacheIdentity` call; `null` = anonymous. */
1328
- let identity;
1329
- const resetListeners = /* @__PURE__ */ new Set();
1330
- /**
1331
- * Get or create the cache entry for `url`. First caller's `factory` (and
1332
- * `options.metaKey`) seeds the `Client`; subsequent callers reuse it. On
1333
- * `meta` rejection, the entry is evicted so the next call retries. A hit
1334
- * marks the URL most recently used; hold an entry you keep using with
1335
- * {@link retainMetaEntry}. Without a browser `window` nothing is cached and
1336
- * the client is asked for `metaStore: false`.
1337
- */
1338
- function getMetaEntry(url, factory, options) {
1339
- const browser = typeof window !== "undefined";
1340
- const existing = browser ? cache.get(url) : void 0;
1341
- if (existing) {
1342
- touch(url, existing);
1343
- return existing;
1344
- }
1345
- const f = factory ?? getDefaultClientFactory();
1346
- let client;
1347
- if (!browser) client = f(url, { metaStore: false });
1348
- else if (options?.metaKey) client = f(url, { metaKey: options.metaKey });
1349
- else client = f(url);
1350
- const meta = client.meta().catch((err) => {
1351
- if (cache.get(url) === entry) evict(url, entry);
1352
- throw err;
1353
- });
1354
- const derived = meta.then((m) => derive(entry, client, m));
1355
- const type = derived.then((d) => d.type);
1356
- type.catch(() => {});
1357
- const entry = {
1358
- client,
1359
- meta,
1360
- type
1361
- };
1362
- const slot = {
1363
- url,
1364
- derived,
1365
- holds: 0
1366
- };
1367
- slots.set(entry, slot);
1368
- if (browser) {
1369
- slot.store = customStoreOf(client);
1370
- if (slot.store) customStores.set(slot.store, (customStores.get(slot.store) ?? 0) + 1);
1371
- cache.set(url, entry);
1372
- trim(entry);
1373
- }
1374
- return entry;
1375
- }
1376
- /**
1377
- * Keep `entry` in the cache while it is in use: a held entry is never
1378
- * evicted by the size limit ({@link setMetaCacheMaxEntries}), so later
1379
- * `getMetaEntry` / `resolveValueHelp` calls for its URL keep returning it.
1380
- * Call the returned function (idempotent) once done — `useTable` and the
1381
- * form value-help do this for their component's lifetime. A reset still
1382
- * drops held entries. Since 0.1.154.
1383
- */
1384
- function retainMetaEntry(entry) {
1385
- const slot = slots.get(entry);
1386
- if (!slot) return () => {};
1387
- slot.holds++;
1388
- let released = false;
1389
- return () => {
1390
- if (released) return;
1391
- released = true;
1392
- slot.holds--;
1393
- if (slot.holds === 0 && cache.get(slot.url) === entry) {
1394
- touch(slot.url, entry);
1395
- trim();
1396
- }
1397
- };
1398
- }
1399
- /**
1400
- * How many URLs the meta cache keeps (default `100`). Least recently used
1401
- * entries beyond it are dropped — entries held with {@link retainMetaEntry}
1402
- * (every mounted table and form value-help) never are, and may exceed it.
1403
- * At least `1`; `Infinity` turns the limit off; no argument restores the
1404
- * default. Since 0.1.154.
1405
- */
1406
- function setMetaCacheMaxEntries(max) {
1407
- maxEntries = max === void 0 ? DEFAULT_MAX_ENTRIES : max >= 1 ? max : 1;
1408
- trim();
1409
- }
1410
- function touch(url, entry) {
1411
- cache.delete(url);
1412
- cache.set(url, entry);
1413
- }
1414
- /**
1415
- * Drop least recently used entries nothing holds until the cache fits.
1416
- * `spare` — the entry just handed out, about to be retained by its caller.
1417
- */
1418
- function trim(spare) {
1419
- if (cache.size <= maxEntries) return;
1420
- for (const [url, entry] of cache) {
1421
- if (entry !== spare && slots.get(entry).holds === 0) evict(url, entry);
1422
- if (cache.size <= maxEntries) return;
1423
- }
1424
- }
1425
- /**
1426
- * Remove `entry` and release what only it kept: its shared `Derived` and
1427
- * custom store. A reset no longer reaches its client, so the client's memoized
1428
- * `/meta` goes now — a factory that reuses clients per URL would otherwise
1429
- * hand it to the next viewer.
1430
- */
1431
- function evict(url, entry) {
1432
- cache.delete(url);
1433
- entry.client.invalidateMeta?.();
1434
- const slot = slots.get(entry);
1435
- if (slot.etag !== void 0 && --derivedByEtag.get(slot.etag).refs === 0) derivedByEtag.delete(slot.etag);
1436
- if (slot.store) {
1437
- const refs = customStores.get(slot.store);
1438
- if (refs > 1) customStores.set(slot.store, refs - 1);
1439
- else {
1440
- slot.store.clear();
1441
- customStores.delete(slot.store);
1442
- }
1443
- }
1444
- }
1445
- /**
1446
- * The `TableDef` for a cache entry, built once per entry — and once per
1447
- * `/meta` `ETag` across entries. Since 0.1.153.
1448
- */
1449
- function getMetaTableDef(entry) {
1450
- if (!entry.tableDef) {
1451
- const derived = slots.get(entry)?.derived;
1452
- entry.tableDef = derived ? Promise.all([entry.meta, derived]).then(([meta, d]) => d.tableDef ??= createTableDef(meta, d.type)) : Promise.all([entry.meta, entry.type]).then(([meta, type]) => createTableDef(meta, type));
1453
- }
1454
- return entry.tableDef;
1455
- }
1456
- /**
1457
- * Shares the `Derived` of one `ETag` among the cached entries that loaded it;
1458
- * an entry no longer cached (evicted, reset, server render) keeps its own.
1459
- */
1460
- function derive(entry, client, meta) {
1461
- const slot = slots.get(entry);
1462
- const etag = cache.get(slot.url) === entry ? client.metaEtag?.() : void 0;
1463
- if (etag === void 0) return { type: (0, _atscript_typescript_utils.deserializeAnnotatedType)(meta.type) };
1464
- let shared = derivedByEtag.get(etag);
1465
- if (shared) shared.refs++;
1466
- else {
1467
- shared = {
1468
- derived: { type: (0, _atscript_typescript_utils.deserializeAnnotatedType)(meta.type) },
1469
- refs: 1
1470
- };
1471
- derivedByEtag.set(etag, shared);
1472
- }
1473
- slot.etag = etag;
1474
- return shared.derived;
1475
- }
1476
- /**
1477
- * The custom `/meta` store a factory gave `client`, so a reset (and the
1478
- * eviction of its last cached client) can clear it. The shared
1479
- * `defaultMetaStore` is skipped: a reset clears it through
1480
- * `clearMetaStore()`, and an eviction must not drop the ETags of every
1481
- * other URL. A store-less client (`metaStore: false`) is skipped too.
1482
- */
1483
- function customStoreOf(client) {
1484
- const store = client.metaStore;
1485
- return store && store !== _atscript_db_client.defaultMetaStore ? store : void 0;
1486
- }
1487
- /**
1488
- * Drop every cached `/meta` — including the copy each cached `Client`
1489
- * memoizes and the `@atscript/db-client` meta stores used to revalidate it
1490
- * (the shared default one and any custom one a factory supplied) — the
1491
- * value-help searches shared under them, and everything registered through
1492
- * {@link onMetaCacheReset} (e.g. the table-presets cache). Entries already
1493
- * handed out keep working; the next `getMetaEntry` refetches.
1494
- */
1495
- function resetMetaCache() {
1496
- const entries = [...cache.values()];
1497
- cache.clear();
1498
- derivedByEtag.clear();
1499
- for (const entry of entries) entry.client.invalidateMeta?.();
1500
- (0, _atscript_db_client.clearMetaStore)();
1501
- for (const store of customStores.keys()) store.clear();
1502
- customStores.clear();
1503
- invalidateValueHelpCache();
1504
- for (const listener of resetListeners) listener();
1505
- }
1506
- /**
1507
- * Bind the meta cache to the current viewer. Call it whenever the signed-in
1508
- * user or their role may have changed — after login, after logout and on
1509
- * every reload of the current user. A key that differs from the previous
1510
- * one resets the cache (`resetMetaCache`); the same key keeps it. `null` /
1511
- * `undefined` = anonymous.
1512
- *
1513
- * Binding an identity also turns on caches that are only safe when the app
1514
- * reports sign-in changes, such as the table-presets cache.
1515
- */
1516
- function setMetaCacheIdentity(key) {
1517
- const next = key ?? null;
1518
- if (next === identity) return;
1519
- identity = next;
1520
- resetMetaCache();
1521
- }
1522
- /**
1523
- * The identity last passed to {@link setMetaCacheIdentity}: `undefined` when
1524
- * the app never bound one, `null` for anonymous. Since 0.1.153.
1525
- */
1526
- function getMetaCacheIdentity() {
1527
- return identity;
1528
- }
1529
- /**
1530
- * Run `listener` on every {@link resetMetaCache} (and so on every identity
1531
- * change). For caches that belong to the signed-in viewer. Returns an
1532
- * unsubscribe function. Since 0.1.153.
1533
- */
1534
- function onMetaCacheReset(listener) {
1535
- resetListeners.add(listener);
1536
- return () => {
1537
- resetListeners.delete(listener);
1538
- };
1539
- }
1540
- //#endregion
1541
- //#region src/value-help/resolve.ts
1542
- /**
1543
- * Lazily fetch and extract value-help metadata for the given URL.
1544
- *
1545
- * - Issues exactly one `GET {url}/meta` per URL across the session (shared via meta-cache).
1546
- * - Concurrent callers with the same URL share the in-flight promise.
1547
- * - If the underlying fetch rejects, the cache entry is evicted so a later
1548
- * retry performs a fresh fetch.
1549
- */
1550
- function resolveValueHelp(url) {
1551
- const entry = getMetaEntry(url);
1552
- if (entry.resolved) return entry.resolved;
1553
- entry.resolved = Promise.all([entry.meta, entry.type]).then(([meta, type]) => buildResolved(url, meta, type));
1554
- return entry.resolved;
1555
- }
1556
- /** Thin alias over `resetMetaCache` — retained so existing test code keeps working. */
1557
- function resetValueHelpCache() {
1558
- resetMetaCache();
1559
- }
1560
- function buildResolved(url, meta, targetType) {
1561
- const objectType = targetType.type.kind === "object" ? targetType.type : void 0;
1562
- const versionColumn = meta.versionColumn;
1563
- const primaryKeys = [];
1564
- let labelField;
1565
- let descrField;
1566
- const attrFields = [];
1567
- let firstStringField;
1568
- if (objectType) for (const [name, fieldProp] of objectType.props) {
1569
- if (name === versionColumn) continue;
1570
- const isPK = fieldProp.metadata.has(META_ID);
1571
- if (isPK) primaryKeys.push(name);
1572
- if (fieldProp.metadata.has("ui.dict.label")) labelField = name;
1573
- if (fieldProp.metadata.has("ui.dict.descr")) descrField = name;
1574
- if (fieldProp.metadata.has("ui.dict.attr")) attrFields.push(name);
1575
- if (!firstStringField && !isPK && fieldProp.type.kind === "" && fieldProp.type.designType === "string") firstStringField = name;
1576
- }
1577
- if (!labelField) labelField = firstStringField;
1578
- if (!labelField) labelField = primaryKeys[0] ?? "id";
1579
- const filterableFields = [];
1580
- const sortableFields = [];
1581
- if (meta.fields) for (const [name, fm] of Object.entries(meta.fields)) {
1582
- if (name === versionColumn) continue;
1583
- if (fm?.filterable) filterableFields.push(name);
1584
- if (fm?.sortable) sortableFields.push(name);
1585
- }
1586
- return {
1587
- url,
1588
- primaryKeys,
1589
- labelField,
1590
- descrField,
1591
- attrFields,
1592
- filterableFields,
1593
- sortableFields,
1594
- searchable: !!meta.searchable,
1595
- targetType
1596
- };
1597
- }
1598
- //#endregion
1599
- //#region src/form/path-utils.ts
1600
- /**
1601
- * Joins a dot-separated path prefix with a segment. Empty-safe on both
1602
- * sides: an empty segment returns the prefix as-is, an empty prefix
1603
- * returns the segment as-is (no leading/trailing dots).
1604
- */
1605
- function joinPath(prefix, segment) {
1606
- if (!segment) return prefix;
1607
- return prefix ? `${prefix}.${segment}` : segment;
1608
- }
1609
- /**
1610
- * Gets a nested value by dot-separated path.
1611
- * Always dereferences `obj.value` first (form data is wrapped in `{ value: domainData }`).
1612
- * When `path` is empty, returns the root domain data (`obj.value`).
1613
- */
1614
- function getByPath(obj, path) {
1615
- const root = obj.value;
1616
- if (!path) return root;
1617
- const keys = path.split(".");
1618
- let current = root;
1619
- for (const key of keys) {
1620
- if (current === null || current === void 0 || typeof current !== "object") return void 0;
1621
- current = current[key];
1622
- }
1623
- return current;
1624
- }
1625
- /**
1626
- * Sets a nested value by dot-separated path.
1627
- * Always dereferences `obj.value` first (form data is wrapped in `{ value: domainData }`).
1628
- * When `path` is empty, sets the root domain data (`obj.value = value`).
1629
- * Creates intermediate objects if they do not exist.
1630
- */
1631
- function setByPath(obj, path, value) {
1632
- if (!path) {
1633
- obj.value = value;
1634
- return;
1635
- }
1636
- const keys = path.split(".");
1637
- const last = keys.pop();
1638
- if (last === void 0) return;
1639
- let current = obj.value;
1640
- for (const key of keys) {
1641
- if (current[key] === null || current[key] === void 0 || typeof current[key] !== "object") current[key] = {};
1642
- current = current[key];
1643
- }
1644
- current[last] = value;
1645
- }
1646
- /**
1647
- * Deletes the own key at a dot-separated path (form-data wrapper aware — derefs
1648
- * `obj.value` first). Walks to the parent WITHOUT vivifying intermediate nodes:
1649
- * if any ancestor is missing, the call is a no-op (nothing to delete).
1650
- *
1651
- * Unlike `setByPath(obj, path, undefined)`, this leaves NO own key behind — the
1652
- * leaf reads as absent (`'k' in parent === false`), which keeps `deepEqual`
1653
- * structural comparisons in sync (a present `undefined` own-key and an absent
1654
- * key are NOT structurally equal under the own-key walk). Used by
1655
- * {@link applyFormChanges} to apply a clear-to-`undefined` change as a delete.
1656
- *
1657
- * Empty path clears the root domain value (`obj.value = undefined`).
1658
- */
1659
- function deleteByPath(obj, path) {
1660
- if (!path) {
1661
- obj.value = void 0;
1662
- return;
1663
- }
1664
- const keys = path.split(".");
1665
- const last = keys.pop();
1666
- if (last === void 0) return;
1667
- let current = obj.value;
1668
- for (const key of keys) {
1669
- if (current === null || current === void 0 || typeof current !== "object") return;
1670
- current = current[key];
1671
- }
1672
- if (current === null || current === void 0 || typeof current !== "object") return;
1673
- delete current[last];
1674
- }
1675
- function parseStaticDefault(raw, prop) {
1676
- if (typeof raw !== "string") return raw;
1677
- if (prop.type.kind === "" && prop.type.designType === "string") return raw;
1678
- try {
1679
- return JSON.parse(raw);
1680
- } catch {
1681
- return;
1682
- }
1683
- }
1684
- /** Cached default resolver — reused when no resolver is provided. */
1685
- const defaultValueResolver = createFormValueResolver();
1686
- function createFormValueResolver(data = {}, context = {}) {
1687
- return (prop, _path) => {
1688
- return resolveFieldProp(prop, UI_FORM_FN_VALUE, META_DEFAULT, {
1689
- v: void 0,
1690
- data,
1691
- context,
1692
- entry: void 0
1693
- }, { transform: (raw) => parseStaticDefault(raw, prop) });
1694
- };
1695
- }
1696
- /**
1697
- * Type-appropriate "defined-but-empty" fallback for primitive design types
1698
- * whose structural default in atscript's `finalDefault` table is
1699
- * `undefined`. Without this, `createFormData` on an optional `decimal`
1700
- * field (or any other primitive missed by atscript's table) returns
1701
- * `undefined` — but `createFormData` is called from "explicit add"
1702
- * contexts (optional-toggle, array-add, tuple-pad, union-pick) where the
1703
- * caller's intent is "give me a value the renderer can edit", not "no
1704
- * value yet". Returning `undefined` leaves the empty-state placeholder
1705
- * stuck in AsFieldShell.
1706
- *
1707
- * `decimal → "0"` mirrors the `number → 0` default — the atscript runtime
1708
- * validator (≥ 0.1.54) rejects `""` for decimal fields, so committing the
1709
- * canonical zero is the only init that survives a submit-without-edit.
1710
- * `useAsDecimal` pads the display to the field's effective scale, so the
1711
- * user sees `0.00` / `0.000` per the `@db.column.precision` annotation.
1712
- */
1713
- function primitiveInitFallback(prop) {
1714
- if (prop.type.kind !== "") return void 0;
1715
- switch (prop.type.designType) {
1716
- case "decimal": return "0";
1717
- default: return;
1718
- }
1719
- }
1720
- function createFormData(type, resolver) {
1721
- let value = (0, _atscript_typescript_utils.createDataFromAnnotatedType)(type, { mode: resolver ?? defaultValueResolver });
1722
- if (value === void 0) value = primitiveInitFallback(type);
1723
- return { value };
1724
- }
1725
- const variantValidatorCache = /* @__PURE__ */ new WeakMap();
1726
- function getVariantValidator(variant) {
1727
- let v = variantValidatorCache.get(variant.type);
1728
- if (!v) {
1729
- v = variant.type.validator();
1730
- variantValidatorCache.set(variant.type, v);
1731
- }
1732
- return v;
1733
- }
1734
- const variantsDiscriminatorCache = /* @__PURE__ */ new WeakMap();
1735
- function getVariantsDiscriminator(variants) {
1736
- let cached = variantsDiscriminatorCache.get(variants);
1737
- if (cached === void 0) {
1738
- cached = (0, _atscript_typescript_utils.detectDiscriminator)(variants.map((v) => v.type));
1739
- variantsDiscriminatorCache.set(variants, cached);
1740
- }
1741
- return cached;
1742
- }
1743
- function detectUnionVariant(value, variants) {
1744
- if (variants.length <= 1) return 0;
1745
- const disc = getVariantsDiscriminator(variants);
1746
- if (disc && value !== null && typeof value === "object") {
1747
- const tag = value[disc.propertyName];
1748
- const key = String(tag);
1749
- if (Object.prototype.hasOwnProperty.call(disc.indexMapping, key)) {
1750
- const idx = disc.indexMapping[key];
1751
- if (idx !== void 0) return idx;
1752
- }
1753
- }
1754
- for (let i = 0; i < variants.length; i++) try {
1755
- if (getVariantValidator(variants[i]).validate(value, true)) return i;
1756
- } catch {}
1757
- return 0;
1758
- }
1759
- //#endregion
1760
- //#region src/form/clone.ts
1761
- /**
1762
- * Structural deep clone of plain JSON-ish data (objects / arrays / primitives /
1763
- * `Date`). Walks OWN-ENUMERABLE keys only (matches the own-key discipline in
1764
- * `diff.ts` — never copies an accidental prototype) and copies leaves by value.
1765
- *
1766
- * `structuredClone` is deliberately NOT used: it throws on functions and on Vue
1767
- * reactive proxies. The optional `unwrap` hook lets a framework caller
1768
- * de-proxy each value first (vue-form passes `toRaw`); the core omits it.
1769
- *
1770
- * The SINGLE deep-clone primitive for the form engine — used by
1771
- * `applyFormChanges`, `buildFormRebase`, and vue-form's baseline snapshot. Do
1772
- * not reimplement structural cloning elsewhere.
1773
- */
1774
- function deepClone(value, unwrap) {
1775
- const v = unwrap ? unwrap(value) : value;
1776
- if (v === null || typeof v !== "object") return v;
1777
- if (v instanceof Date) return new Date(v.getTime());
1778
- if (Array.isArray(v)) {
1779
- const out = [];
1780
- for (let i = 0; i < v.length; i++) out.push(deepClone(v[i], unwrap));
1781
- return out;
1782
- }
1783
- const src = v;
1784
- const out = {};
1785
- for (const k of Object.keys(src)) out[k] = deepClone(src[k], unwrap);
1786
- return out;
1787
- }
1788
- //#endregion
1789
- //#region src/form/error-utils.ts
1790
- /**
1791
- * Framework-agnostic helpers for working with form-error maps keyed by
1792
- * dotted path. Used by AsForm to drive error badges and auto-open
1793
- * collapsed sections; safe to share with React (or any other) bindings.
1794
- *
1795
- * Convention:
1796
- * - Keys are dotted paths (`a.b.c`); empty string and `__form` denote
1797
- * the form-level error.
1798
- * - Values may be `string | undefined`; falsy entries are dropped on
1799
- * merge.
1800
- */
1801
- /** Error-map key of the form-level error. */
1802
- const FORM_ERROR_KEY = "__form";
1803
- /**
1804
- * Turn a validator's error list into an error map keyed by path. A
1805
- * root-level error (empty path) becomes the form-level error
1806
- * ({@link FORM_ERROR_KEY}). The first error per path wins: a failing
1807
- * container rule is reported before the container's own shape / length
1808
- * checks at the same path.
1809
- */
1810
- function validatorErrorsToMap(errors) {
1811
- const out = {};
1812
- for (const err of errors) out[err.path || "__form"] ??= err.message;
1813
- return out;
1814
- }
1815
- /**
1816
- * Merge any number of partial error maps into a single dense
1817
- * `Record<path, message>`. Falsy values are skipped — later sources do
1818
- * NOT overwrite earlier ones with an empty value.
1819
- */
1820
- function mergeErrorMaps(...maps) {
1821
- const merged = {};
1822
- for (const m of maps) {
1823
- if (!m) continue;
1824
- for (const k of Object.keys(m)) {
1825
- const v = m[k];
1826
- if (v) merged[k] = v;
1827
- }
1828
- }
1829
- return merged;
1830
- }
1831
- /**
1832
- * Return `errors` without the entries whose key is in `paths`.
1833
- *
1834
- * Identity-preserving: when no key matches, the ORIGINAL `errors` object
1835
- * is returned unchanged — callers compare `result !== errors` to detect
1836
- * that something was pruned and skip spurious reactive writes.
1837
- */
1838
- function omitPaths(errors, paths) {
1839
- let pruned = null;
1840
- for (const key in errors) if (paths.has(key)) {
1841
- pruned ??= { ...errors };
1842
- delete pruned[key];
1843
- }
1844
- return pruned ?? errors;
1845
- }
1846
- /**
1847
- * Yield every ancestor prefix of a dotted path, longest-first
1848
- * (`a.b.c` → `a.b.c`, `a.b`, `a`). Returns the path itself first so
1849
- * callers can include it in the iteration without a special case.
1850
- *
1851
- * Empty paths and the form-level key (`__form`) yield nothing.
1852
- */
1853
- function* iteratePathAncestors(path) {
1854
- if (!path || path === "__form") return;
1855
- let pos = path.length;
1856
- while (pos > 0) {
1857
- yield path.slice(0, pos);
1858
- const dot = path.lastIndexOf(".", pos - 1);
1859
- if (dot < 0) return;
1860
- pos = dot;
1861
- }
1862
- }
1863
- /**
1864
- * Build an indexed `Map<absolutePath, descendantErrorCount>` so each
1865
- * struct in the tree can render an error-count badge in O(1).
1866
- *
1867
- * For every error path, the count is incremented on the path itself
1868
- * AND every dotted-path ancestor — so a struct at `a.b` reports the
1869
- * total of all errors at `a.b` or below.
1870
- */
1871
- function buildDescendantErrorCounts(errors) {
1872
- const map = /* @__PURE__ */ new Map();
1873
- for (const errPath of Object.keys(errors)) {
1874
- if (!errors[errPath]) continue;
1875
- for (const prefix of iteratePathAncestors(errPath)) map.set(prefix, (map.get(prefix) ?? 0) + 1);
1876
- }
1877
- return map;
1878
- }
1879
- //#endregion
1880
- //#region src/form/validate.ts
1881
- const dbPlugin = (0, _atscript_db_validator.createDbValidatorPlugin)();
1882
- const INSERT_CONTEXT = { mode: "insert" };
1883
- /**
1884
- * Always-on plugin for fields the server fills in, so a create form is not
1885
- * blocked on them:
1886
- * - `@db.column.derived` — read-only and server-computed: never validated
1887
- * (not even a loaded value, which the user could not fix).
1888
- * - an absent `@db.default*` / `@db.column.version` / `@db.onUpdate.inc` value
1889
- * — delegated to `@atscript/db`'s own insert-mode rule, so the key list has
1890
- * one owner.
1891
- * `db.rel.FK` is kept out: a form fills the FK itself (no nested nav
1892
- * object), so an empty required FK must still fail.
1893
- *
1894
- * The db plugin reads its mode from the validation context, which here
1895
- * carries the form's `{ data, context }` — it gets a view of `ctx` with the
1896
- * insert context instead.
1897
- */
1898
- const serverManagedPlugin = (ctx, def, value) => {
1899
- if (def.metadata.has("db.column.derived")) return true;
1900
- if (value !== void 0 || def.metadata.has("db.rel.FK")) return void 0;
1901
- return dbPlugin(Object.create(ctx, { context: { value: INSERT_CONTEXT } }), def, value);
1902
- };
1903
- /**
1904
- * The props of the fields `createFormDef` marked `derived`, at any depth — a
1905
- * computed view column (`metaFields`) or an edit form's update-stamped field
1906
- * (see `CreateFormDefOptions.mode`) carries no annotation the plugin above
1907
- * could read. The validator matches by prop, so a prop that is also used where
1908
- * it is not derived (an interface's stamp below a union of several types, too)
1909
- * stays validated.
1910
- */
1911
- function collectDerivedProps(def) {
1912
- const derived = /* @__PURE__ */ new Set();
1913
- const kept = /* @__PURE__ */ new Set();
1914
- const walk = (fields) => {
1915
- for (const field of fields) {
1916
- if (field.derived) {
1917
- derived.add(field.prop);
1918
- continue;
1919
- }
1920
- kept.add(field.prop);
1921
- if (isObjectField(field)) walk(field.objectDef.fields);
1922
- else if (isArrayField(field)) walk([field.itemField]);
1923
- else if (isTupleField(field)) walk(field.itemFields);
1924
- else if (isUnionField(field)) for (const v of field.unionVariants) {
1925
- if (v.def) walk(v.def.fields);
1926
- if (v.itemField) walk([v.itemField]);
1927
- }
1928
- }
1929
- };
1930
- walk(def.fields);
1931
- for (const prop of kept) derived.delete(prop);
1932
- return derived;
1933
- }
1934
- let defaultValidatorPlugins = [];
1935
- /** Replace the default validator plugins applied to every form/field validator. */
1936
- function setDefaultValidatorPlugins(plugins) {
1937
- defaultValidatorPlugins = plugins;
1938
- }
1939
- /** Get the currently registered default validator plugins. */
1940
- function getDefaultValidatorPlugins() {
1941
- return defaultValidatorPlugins;
1942
- }
1943
- /**
1944
- * Returns a reusable validator function for a whole FormDef.
1945
- *
1946
- * Validator is created once and reused on every call.
1947
- * ATScript's @expect.* validation runs automatically; server-managed db
1948
- * fields (every `derived` field, absent `@db.default*` / version) pass.
1949
- * For custom `ui.fn.*` validators, install ui-fns and pass its plugin via `opts.plugins`.
1950
- *
1951
- * Errors are keyed by dotted path. A root-level error (a failing
1952
- * `@ui.form.validate` on the form's interface) is keyed `__form`.
1953
- */
1954
- function getFormValidator(def, opts) {
1955
- const derived = collectDerivedProps(def);
1956
- const derivedPlugin = (_ctx, prop) => derived.has(prop) ? true : void 0;
1957
- const validator = new _atscript_typescript_utils.Validator(def.type, {
1958
- unknownProps: "ignore",
1959
- ...opts,
1960
- plugins: [
1961
- ...derived.size > 0 ? [derivedPlugin] : [],
1962
- serverManagedPlugin,
1963
- ...defaultValidatorPlugins,
1964
- ...opts?.plugins ?? []
1965
- ]
1966
- });
1967
- return (callOpts) => {
1968
- if (validator.validate(callOpts.data, true, {
1969
- data: callOpts.data,
1970
- context: callOpts.context ?? {}
1971
- })) return {};
1972
- return validatorErrorsToMap(validator.errors);
1973
- };
1974
- }
1975
- /**
1976
- * Root-only plugin: passes every descendant without visiting it. Only
1977
- * `object` / `array` / `tuple` roots use it — their root-path errors (shape,
1978
- * length, a container-level `@ui.form.validate`) are all decided before the
1979
- * walk descends, so skipping the children cannot change the root error. A
1980
- * union or intersection root evaluates its branches AT the root path, where
1981
- * a branch's verdict depends on its children — those keep the full walk.
1982
- */
1983
- const skipDescendantsPlugin = (ctx) => ctx.path === "" ? void 0 : true;
1984
- /**
1985
- * Whether a type kind is a container that carries its own children:
1986
- * `object`, `array` or `tuple`. Union / intersection kinds are not
1987
- * containers — they evaluate their branches at their own path.
1988
- */
1989
- function isContainerKind(kind) {
1990
- return kind === "object" || kind === "array" || kind === "tuple";
1991
- }
1992
- /**
1993
- * Creates a cached validator function for a single ATScript prop.
1994
- *
1995
- * The `Validator` instance is created lazily on first call and reused.
1996
- * Returns `true` when valid, or the first error message string when invalid.
1997
- * With `rootOnly`, an object / array / tuple prop is validated at its root
1998
- * only (descendants are not walked — their errors would be discarded anyway).
1999
- */
2000
- function createFieldValidator(prop, opts) {
2001
- let cached;
2002
- return (value, externalCtx) => {
2003
- cached ??= new _atscript_typescript_utils.Validator(prop, { plugins: opts?.rootOnly && isContainerKind(prop.type.kind) ? [
2004
- skipDescendantsPlugin,
2005
- serverManagedPlugin,
2006
- ...defaultValidatorPlugins
2007
- ] : [serverManagedPlugin, ...defaultValidatorPlugins] });
2008
- if (!cached.validate(value, true, externalCtx)) {
2009
- if (opts?.rootOnly) {
2010
- const rootError = cached.errors?.find((e) => e.path === "");
2011
- if (rootError) return rootError.message;
2012
- return true;
2013
- }
2014
- return cached.errors?.[0]?.message || "Invalid value";
2015
- }
2016
- return true;
2017
- };
2018
- }
2019
- //#endregion
2020
- //#region src/form/diff.ts
2021
- /**
2022
- * Diffs a form's `current` data against its `baseline` snapshot, producing both
2023
- * a changed-fields list and an `@atscript/db` patch object.
2024
- *
2025
- * Both `baseline` and `current` are the WRAPPED form-data container
2026
- * (`{ value: domainData }`) so this reuses {@link getByPath}.
2027
- *
2028
- * Revert-aware: a value edited back to its baseline produces no change and no
2029
- * patch entry.
2030
- *
2031
- * Snapshot contract: the result is NOT a deep copy. `$insert` items, `$replace`
2032
- * arrays, scalar leaf values, and `changes[].before/after` all hold live
2033
- * references into `baseline` / `current`. Callers that keep editing the form
2034
- * after building the patch must snapshot first (e.g. build the patch at submit
2035
- * time on a frozen clone). This is the common Vue v-model flow.
2036
- */
2037
- function buildFormDiff(def, baseline, current, opts) {
2038
- const changes = [];
2039
- const patch = {};
2040
- const versionColumn = findVersionColumn(def);
2041
- diffFields(def.fields, "", baseline, current, changes, patch, versionColumn, def.flatMap);
2042
- if ((opts?.cas ?? true) && versionColumn && Object.keys(patch).length > 0) {
2043
- const baselineVersion = getByPath(baseline, versionColumn);
2044
- if (typeof baselineVersion === "number" && Number.isInteger(baselineVersion)) patch.$cas = { [versionColumn]: baselineVersion };
2045
- }
2046
- return {
2047
- isDirty: changes.length > 0,
2048
- changes,
2049
- patch
2050
- };
2051
- }
2052
- /**
2053
- * Diffs a list of sibling fields. `prefix` is the dot-path of the parent
2054
- * context relative to the form root (used only for the change list `path`);
2055
- * patch entries are written into the local `patch` object so callers can place
2056
- * the whole sub-object as a nested partial.
2057
- *
2058
- * `versionColumn` is the top-level `@db.column.version` field name (or
2059
- * undefined). When set, the matching top-level field is skipped entirely — it
2060
- * is server-managed and may only be round-tripped via `$cas`.
2061
- *
2062
- * `inlineFlatMap` is the form's `flatMap`, supplied only at the top-level walk.
2063
- * It lets {@link diffScalarField} read `@db.patch.strategy` off the object
2064
- * ancestors of an INLINED leaf (a dotted-path leaf with no `FormObjectFieldDef`
2065
- * node — `createFormDef` dissolves unlabelled objects into dot-paths). At a
2066
- * default (replace) ancestor the whole sub-object must be emitted. It is
2067
- * intentionally NOT propagated into `diffObjectField` recursion, where the
2068
- * strategy decision is already made per structured object.
2069
- */
2070
- function diffFields(fields, prefix, baseline, current, changes, patch, versionColumn, inlineFlatMap) {
2071
- for (const field of fields) {
2072
- if (field.path === "" && fields.length === 1) {
2073
- diffLeafRoot(field, baseline, current, changes, patch);
2074
- continue;
2075
- }
2076
- if (field.phantom || field.derived || versionColumn !== void 0 && !prefix && field.path === versionColumn) continue;
2077
- const fullPath = prefix ? `${prefix}.${field.path}` : field.path;
2078
- if (isArrayField(field)) {
2079
- diffArrayField(field, fullPath, baseline, current, changes, patch);
2080
- continue;
2081
- }
2082
- if (isObjectField(field)) {
2083
- diffObjectField(field, fullPath, baseline, current, changes, patch);
2084
- continue;
2085
- }
2086
- diffScalarField(field, fullPath, baseline, current, changes, patch, inlineFlatMap);
2087
- }
2088
- }
2089
- /** Single-leaf root form (non-object root). Whole value is the patch. */
2090
- function diffLeafRoot(field, baseline, current, changes, patch) {
2091
- const before = getByPath(baseline, "");
2092
- const after = getByPath(current, "");
2093
- if (deepEqual(before, after)) return;
2094
- if (isArrayField(field)) {
2095
- const arrayPatch = diffArray(field, before, after);
2096
- if (arrayPatch === void 0) return;
2097
- changes.push({
2098
- path: "",
2099
- kind: "array",
2100
- before,
2101
- after
2102
- });
2103
- patch.value = arrayPatch;
2104
- } else {
2105
- changes.push({
2106
- path: "",
2107
- kind: "set",
2108
- before,
2109
- after
2110
- });
2111
- patch.value = after === void 0 ? null : after;
2112
- }
2113
- }
2114
- /** Scalar / union / tuple / ref field — whole-value compare; clear → null. */
2115
- function diffScalarField(field, fullPath, baseline, current, changes, patch, inlineFlatMap) {
2116
- const before = getByPath(baseline, fullPath);
2117
- const after = getByPath(current, fullPath);
2118
- if (deepEqual(before, after)) return;
2119
- changes.push({
2120
- path: fullPath,
2121
- kind: "set",
2122
- before,
2123
- after
2124
- });
2125
- if (inlineFlatMap && field.path.includes(".")) {
2126
- const cutoff = inlinedReplaceCutoff(field.path, inlineFlatMap);
2127
- if (cutoff !== void 0) {
2128
- const prefixLen = fullPath.length - field.path.length;
2129
- const sub = getByPath(current, prefixLen > 0 ? fullPath.slice(0, prefixLen) + cutoff : cutoff);
2130
- setPatchLeaf(patch, cutoff, sub === void 0 ? null : sub);
2131
- return;
2132
- }
2133
- }
2134
- setPatchLeaf(patch, field.path, after === void 0 ? null : after);
2135
- }
2136
- /**
2137
- * For a dotted INLINED leaf path, returns the path of the shallowest object
2138
- * ancestor whose `@db.patch.strategy` is the default (`replace`), or undefined
2139
- * when every ancestor is `merge` (then the leaf partial is correct). At a
2140
- * replace ancestor the whole sub-object must be present in the patch.
2141
- *
2142
- * Walks ancestor segments (`a`, `a.b`, … but not the leaf itself); the first
2143
- * one that is an object AND not merge is the cutoff. merge does NOT propagate,
2144
- * so a default-replace level below a merge level still cuts off there.
2145
- */
2146
- function inlinedReplaceCutoff(leafPath, flatMap) {
2147
- const segs = leafPath.split(".");
2148
- let acc = "";
2149
- for (let i = 0; i < segs.length - 1; i++) {
2150
- acc = acc ? `${acc}.${segs[i]}` : segs[i];
2151
- const prop = flatMap.get(acc);
2152
- if (!prop || prop.type.kind !== "object") continue;
2153
- if (getFieldMeta(prop, "db.patch.strategy") !== "merge") return acc;
2154
- }
2155
- }
2156
- /**
2157
- * Inlined-or-structured object field — recurse, emit a nested partial OR the
2158
- * whole sub-object depending on the field's `@db.patch.strategy`.
2159
- *
2160
- * atscript-db's DEFAULT nested-object patch strategy is `replace` (strict —
2161
- * every required child must be present, else 400; omitted optionals are
2162
- * null-filled). A changed-leaves-only partial is a valid patch ONLY when the
2163
- * object field carries `@db.patch.strategy 'merge'`. For the default (replace)
2164
- * case we therefore emit the WHOLE current sub-object so the validator passes
2165
- * and no optional leaf is silently nulled. `merge` does NOT propagate, so a
2166
- * descendant object without its own `merge` again emits its full sub-object
2167
- * (handled by recursion — `diffFields` re-enters this function per child).
2168
- *
2169
- * Wholesale-clear: if the sub-object was a defined object in `baseline` but is
2170
- * now undefined/null, emit `field: null` (object removed) instead of a partial
2171
- * of nulled leaves.
2172
- */
2173
- function diffObjectField(field, fullPath, baseline, current, changes, patch) {
2174
- const beforeObj = getByPath(baseline, fullPath);
2175
- const afterObj = getByPath(current, fullPath);
2176
- const nested = {};
2177
- diffFields(field.objectDef.fields, fullPath, baseline, current, changes, nested, void 0, field.objectDef.flatMap);
2178
- if ((afterObj === void 0 || afterObj === null) && isPlainObject(beforeObj)) {
2179
- setPatchLeaf(patch, field.path, null);
2180
- return;
2181
- }
2182
- if (Object.keys(nested).length === 0) return;
2183
- if (getFieldMeta(field.prop, "db.patch.strategy") === "merge") setPatchLeaf(patch, field.path, nested);
2184
- else setPatchLeaf(patch, field.path, afterObj === void 0 ? null : afterObj);
2185
- }
2186
- /** Array field — keyed → $update/$insert/$remove; unkeyed → $replace. */
2187
- function diffArrayField(field, fullPath, baseline, current, changes, patch) {
2188
- const before = getByPath(baseline, fullPath);
2189
- const after = getByPath(current, fullPath);
2190
- if (deepEqual(before, after)) return;
2191
- const arrayPatch = diffArray(field, before, after);
2192
- if (arrayPatch === void 0) return;
2193
- changes.push({
2194
- path: fullPath,
2195
- kind: "array",
2196
- before,
2197
- after
2198
- });
2199
- setPatchLeaf(patch, field.path, arrayPatch);
2200
- }
2201
- /**
2202
- * Produces a `TArrayPatch` value for one array field, or `undefined` when no
2203
- * real op results (the caller then skips the field entirely).
2204
- *
2205
- * - Keyed arrays (item object has `@expect.array.key`): emit `$update`
2206
- * (key + changed leaves), `$insert` (wholly-new items, whole), `$remove`
2207
- * (key only). Reorder-only (same key membership, same content, different
2208
- * order) → `$replace` (key-ops can't express a pure reorder).
2209
- * Ambiguous keys (duplicate or missing key values) → `$replace` (the only
2210
- * faithful op when key identity is unreliable).
2211
- * - Unkeyed object arrays / primitive arrays: `$replace` with the whole array.
2212
- * Primitive arrays with `@expect.array.uniqueItems` use by-value
2213
- * `$insert` / `$remove` (set semantics).
2214
- *
2215
- * Deliberate `$insert`-not-`$upsert`: wholly-new keyed items use `$insert`
2216
- * (pure append) rather than `$upsert`. This is safe because `$insert` is only
2217
- * ever used for keys ABSENT from baseline; existing keys go through `$update`.
2218
- * `$upsert` would dedupe-by-key, which we don't need given that invariant.
2219
- */
2220
- function diffArray(field, before, after) {
2221
- const beforeArr = Array.isArray(before) ? before : [];
2222
- const afterArr = Array.isArray(after) ? after : [];
2223
- const keyProps = getArrayKeyProps(field.itemType);
2224
- if (keyProps.length > 0) return diffKeyedArray(beforeArr, afterArr, keyProps);
2225
- if (getFieldMeta(field.prop, "expect.array.uniqueItems") !== void 0 && isPrimitiveItem(field)) {
2226
- const setPatch = diffUniqueArray(beforeArr, afterArr);
2227
- if (setPatch) return setPatch;
2228
- }
2229
- return { $replace: afterArr };
2230
- }
2231
- /**
2232
- * Keyed array diff. Reorder-only (same membership) falls back to $replace.
2233
- *
2234
- * Returns `undefined` when no $update/$insert/$remove op is produced (so the
2235
- * caller skips the field rather than emitting a malformed empty `{}`).
2236
- *
2237
- * Ambiguity fallback: if either side has DUPLICATE key buckets, or ANY element
2238
- * is missing all of its key values, key identity is unreliable — fall back to
2239
- * `{ $replace: after }`, the only faithful op (last-write-wins collapse would
2240
- * silently drop items, and a key-less `$update` is unmatchable by the DB).
2241
- */
2242
- function diffKeyedArray(before, after, keyProps) {
2243
- if (hasKeylessItem(before, keyProps) || hasKeylessItem(after, keyProps)) return { $replace: after };
2244
- const beforeByKey = /* @__PURE__ */ new Map();
2245
- for (const el of before) if (isPlainObject(el)) beforeByKey.set(keyOf(el, keyProps), el);
2246
- const afterByKey = /* @__PURE__ */ new Map();
2247
- for (const el of after) if (isPlainObject(el)) afterByKey.set(keyOf(el, keyProps), el);
2248
- if (beforeByKey.size !== before.length || afterByKey.size !== after.length) return { $replace: after };
2249
- const $insert = [];
2250
- const $update = [];
2251
- const $remove = [];
2252
- let contentChanged = false;
2253
- for (const [k, el] of afterByKey) {
2254
- const prev = beforeByKey.get(k);
2255
- if (prev === void 0) {
2256
- $insert.push(el);
2257
- continue;
2258
- }
2259
- if (!deepEqual(prev, el)) {
2260
- contentChanged = true;
2261
- const partial = buildKeyedUpdate(prev, el, keyProps);
2262
- if (partial) $update.push(partial);
2263
- }
2264
- }
2265
- if (beforeByKey.size === afterByKey.size && $insert.length === 0 && !contentChanged) return { $replace: after };
2266
- for (const [k, el] of beforeByKey) if (!afterByKey.has(k)) $remove.push(pickKeys(el, keyProps));
2267
- return arrayOps({
2268
- $update,
2269
- $insert,
2270
- $remove
2271
- });
2272
- }
2273
- /** Builds a `$update` partial: key fields + changed leaves only. */
2274
- function buildKeyedUpdate(prev, next, keyProps) {
2275
- const partial = {};
2276
- for (const k of keyProps) partial[k] = next[k];
2277
- let changed = false;
2278
- const allKeys = new Set([...Object.keys(prev), ...Object.keys(next)]);
2279
- for (const k of allKeys) {
2280
- if (keyProps.includes(k)) continue;
2281
- const a = prev[k];
2282
- const b = next[k];
2283
- if (!deepEqual(a, b)) {
2284
- partial[k] = b === void 0 ? null : b;
2285
- changed = true;
2286
- }
2287
- }
2288
- return changed ? partial : void 0;
2289
- }
2290
- /** Primitive uniqueItems set diff. Returns undefined if neither side differs. */
2291
- function diffUniqueArray(before, after) {
2292
- const beforeSet = new Set(before.map((v) => stableKey(v)));
2293
- const afterSet = new Set(after.map((v) => stableKey(v)));
2294
- const $insert = [];
2295
- const $remove = [];
2296
- const seenInsert = /* @__PURE__ */ new Set();
2297
- const seenRemove = /* @__PURE__ */ new Set();
2298
- for (const v of after) {
2299
- const k = stableKey(v);
2300
- if (!beforeSet.has(k) && !seenInsert.has(k)) {
2301
- $insert.push(v);
2302
- seenInsert.add(k);
2303
- }
2304
- }
2305
- for (const v of before) {
2306
- const k = stableKey(v);
2307
- if (!afterSet.has(k) && !seenRemove.has(k)) {
2308
- $remove.push(v);
2309
- seenRemove.add(k);
2310
- }
2311
- }
2312
- return arrayOps({
2313
- $insert,
2314
- $remove
2315
- });
2316
- }
2317
- /**
2318
- * Assembles a `TArrayPatch` from named op-arrays, dropping empty ones. Returns
2319
- * `undefined` when no op carries any item, so the caller skips the field rather
2320
- * than emitting a malformed empty `{}`.
2321
- */
2322
- function arrayOps(ops) {
2323
- const result = {};
2324
- for (const k in ops) if (ops[k].length > 0) result[k] = ops[k];
2325
- return Object.keys(result).length > 0 ? result : void 0;
2326
- }
2327
- /** Reads `@expect.array.key` props from an array item's object type. */
2328
- function getArrayKeyProps(itemType) {
2329
- if (itemType.type.kind !== "object") return [];
2330
- const props = itemType.type.props;
2331
- const keys = [];
2332
- for (const [name, prop] of props.entries()) if (getFieldMeta(prop, "expect.array.key") !== void 0) keys.push(name);
2333
- return keys;
2334
- }
2335
- /** True when the array's item type is a primitive (designType, kind === ''). */
2336
- function isPrimitiveItem(field) {
2337
- return field.itemType.type.kind === "";
2338
- }
2339
- /** Finds the form's `@db.column.version` column name, if any (top-level only). */
2340
- function findVersionColumn(def) {
2341
- for (const [path, prop] of def.flatMap.entries()) {
2342
- if (!path || path.includes(".")) continue;
2343
- if (getFieldMeta(prop, "db.column.version") !== void 0) return path;
2344
- }
2345
- }
2346
- /** True when any element lacks ALL of its key values (un-keyable identity). */
2347
- function hasKeylessItem(arr, keyProps) {
2348
- for (const el of arr) {
2349
- if (!isPlainObject(el)) return true;
2350
- let hasAnyKey = false;
2351
- for (const k of keyProps) {
2352
- const v = el[k];
2353
- if (v !== void 0 && v !== null) {
2354
- hasAnyKey = true;
2355
- break;
2356
- }
2357
- }
2358
- if (!hasAnyKey) return true;
2359
- }
2360
- return false;
2361
- }
2362
- /** Composite key string for a keyed-array element. */
2363
- function keyOf(el, keyProps) {
2364
- if (keyProps.length === 1) return stableKey(el[keyProps[0]]);
2365
- return keyProps.map((k) => stableKey(el[k])).join(" ");
2366
- }
2367
- /** Picks only the key fields from an element (for $remove). */
2368
- function pickKeys(el, keyProps) {
2369
- const out = {};
2370
- for (const k of keyProps) out[k] = el[k];
2371
- return out;
2372
- }
2373
- /** Writes a value into a (possibly dotted) leaf path on a local patch object. */
2374
- function setPatchLeaf(patch, path, value) {
2375
- if (!path.includes(".")) {
2376
- patch[path] = value;
2377
- return;
2378
- }
2379
- const keys = path.split(".");
2380
- const last = keys.pop();
2381
- let cur = patch;
2382
- for (const k of keys) {
2383
- let next = cur[k];
2384
- if (next === void 0 || next === null || typeof next !== "object") {
2385
- next = {};
2386
- cur[k] = next;
2387
- }
2388
- cur = next;
2389
- }
2390
- cur[last] = value;
2391
- }
2392
- function isPlainObject(v) {
2393
- return typeof v === "object" && v !== null && !Array.isArray(v);
2394
- }
2395
- /**
2396
- * Stable string key for primitives / values (used for set membership).
2397
- *
2398
- * Key equality is TYPE-STRICT: a number `1` and a string `'1'` produce
2399
- * distinct keys, so a keyed-array item whose key changes JS representation
2400
- * between baseline and current is treated as a remove + insert. Callers that
2401
- * round-trip keys with loose typing should normalise the key type first.
2402
- */
2403
- function stableKey(v) {
2404
- if (typeof v === "string") return `s:${v}`;
2405
- if (typeof v === "number" || typeof v === "boolean") return `p:${String(v)}`;
2406
- if (v === null) return "null";
2407
- if (v === void 0) return "undef";
2408
- return `j:${JSON.stringify(v)}`;
2409
- }
2410
- /**
2411
- * Structural deep equality (order-sensitive for arrays). `NaN` equals `NaN`
2412
- * (revert-aware for NaN scalars) while `0` / `-0` stay equal (matches DB
2413
- * intent — `===` treats them equal, only NaN is special-cased).
2414
- *
2415
- * The single comparator shared across the form engine: diff, conflict
2416
- * detection ({@link buildFormRebase}), and apply all route through this — never
2417
- * reimplement equality elsewhere.
2418
- */
2419
- function deepEqual(a, b) {
2420
- if (a === b) return true;
2421
- if (typeof a === "number" && typeof b === "number") return Number.isNaN(a) && Number.isNaN(b);
2422
- if (a === null || b === null || a === void 0 || b === void 0) return false;
2423
- if (typeof a !== "object" || typeof b !== "object") return false;
2424
- const aIsArr = Array.isArray(a);
2425
- const bIsArr = Array.isArray(b);
2426
- if (aIsArr !== bIsArr) return false;
2427
- if (aIsArr && bIsArr) {
2428
- if (a.length !== b.length) return false;
2429
- for (let i = 0; i < a.length; i++) if (!deepEqual(a[i], b[i])) return false;
2430
- return true;
2431
- }
2432
- const ao = a;
2433
- const bo = b;
2434
- const aKeys = Object.keys(ao);
2435
- const bKeys = Object.keys(bo);
2436
- if (aKeys.length !== bKeys.length) return false;
2437
- for (const k of aKeys) {
2438
- if (!Object.prototype.hasOwnProperty.call(bo, k)) return false;
2439
- if (!deepEqual(ao[k], bo[k])) return false;
2440
- }
2441
- return true;
2442
- }
2443
- //#endregion
2444
- //#region src/form/dirty.ts
2445
- /**
2446
- * True when the field at dot-path `path` is dirty given a {@link FormFieldChange}
2447
- * list (as produced by {@link buildFormDiff}).
2448
- *
2449
- * The change list is leaf-grained for scalars/objects but WHOLE-ARRAY for arrays,
2450
- * so a field at `path` is dirty iff some change path equals `path` OR starts with
2451
- * `path + "."`:
2452
- *
2453
- * - scalar / leaf field (incl. nested `address.city`) → exact match.
2454
- * - object / section container → no entry at its own path, only its leaves →
2455
- * matched by the PREFIX branch.
2456
- * - whole-array field → one entry at the array root → exact match.
2457
- * - a field rendered for an array-ITEM leaf (e.g. `items.0.qty`) → NOT detectable:
2458
- * the array diff emits a single whole-array change at the array root, never
2459
- * per-item leaf paths, so this correctly returns false (the array container
2460
- * lights up instead). This is a known, documented limitation.
2461
- *
2462
- * The prefix uses `path + "."` so field `item` never matches a change at `items`
2463
- * (no false positives).
2464
- *
2465
- * Empty `path` `''` is the wrapped form root — every change is nested under it,
2466
- * so it is considered dirty iff there are ANY changes.
2467
- */
2468
- function isPathDirty(changes, path) {
2469
- if (path === "") return changes.length > 0;
2470
- const prefix = `${path}.`;
2471
- for (const change of changes) if (change.path === path || change.path.startsWith(prefix)) return true;
2472
- return false;
2473
- }
2474
- /**
2475
- * Precomputes the set of ALL dirty paths from a {@link FormFieldChange} list so
2476
- * that membership is an O(1) `Set.has(path)` instead of {@link isPathDirty}'s
2477
- * per-call O(changes) prefix scan. Callers that probe many fields against the
2478
- * same change list (e.g. a form rendering one field per leaf) build this once
2479
- * and query it per field.
2480
- *
2481
- * For each change path `C` it adds `C` AND every dot-prefix ancestor of `C`
2482
- * (so `'address.city'` adds both `'address.city'` and `'address'`), matching
2483
- * `isPathDirty`'s "exact OR `path + '.'` prefix" predicate — an ancestor
2484
- * container is dirty exactly when some change is nested under it. The wrapped
2485
- * root `''` is added iff there are ANY changes, mirroring `isPathDirty('')`.
2486
- *
2487
- * INVARIANT (locked, tested): for EVERY path `P`,
2488
- * `collectDirtyPaths(changes).has(P) === isPathDirty(changes, P)`. This is a
2489
- * precompute of the SAME predicate, not a second one — keep them in lockstep.
2490
- */
2491
- function collectDirtyPaths(changes) {
2492
- const dirty = /* @__PURE__ */ new Set();
2493
- if (changes.length === 0) return dirty;
2494
- dirty.add("");
2495
- for (const change of changes) {
2496
- const path = change.path;
2497
- dirty.add(path);
2498
- let dot = path.indexOf(".");
2499
- while (dot !== -1) {
2500
- dirty.add(path.slice(0, dot));
2501
- dot = path.indexOf(".", dot + 1);
2502
- }
2503
- }
2504
- return dirty;
2505
- }
2506
- //#endregion
2507
- //#region src/form/apply.ts
2508
- /**
2509
- * Applies a {@link FormFieldChange} list onto a WRAPPED form-data container
2510
- * (`{ value: domainData }`), mutating it in place and returning the same
2511
- * reference. The inverse direction of {@link buildFormDiff}: where the diff
2512
- * READS `(baseline, current)` into changes, this WRITES changes onto data.
2513
- *
2514
- * IMPORTANT: pass a CLONE, never the live fetched row — every write mutates
2515
- * `data` directly. Callers that need the original intact should
2516
- * `deepClone(data)` first (see {@link deepClone}).
2517
- *
2518
- * Per-change semantics (the single place the apply rules live, so
2519
- * {@link buildFormRebase} stays consistent):
2520
- *
2521
- * - `kind: 'set'`:
2522
- * - `change.after === undefined` → DELETE the own key at `change.path` (walk
2523
- * to parent, `delete`). A cleared field must read as ABSENT, not as a
2524
- * present `undefined` own-key — otherwise a re-diff sees a structural
2525
- * mismatch where the form intends "no value". `setByPath(…, undefined)`
2526
- * leaves an own key behind, so we use {@link deleteByPath} instead.
2527
- * - otherwise → `setByPath(data, change.path, change.after)`.
2528
- * - `kind: 'array'`: whole-array set via `setByPath(data, change.path,
2529
- * change.after)` (LOCKED Option A — no per-element merge; the diff already
2530
- * carried the full after-array).
2531
- *
2532
- * The `def` is currently unused by the apply walk (paths fully describe the
2533
- * write target) but is part of the signature for parity with
2534
- * `buildFormDiff`/`buildFormRebase`, so the rebase engine threads one `def`
2535
- * uniformly through diff + apply.
2536
- */
2537
- function applyFormChanges(_def, data, changes) {
2538
- for (const change of changes) if (change.kind === "set" && change.after === void 0) deleteByPath(data, change.path);
2539
- else setByPath(data, change.path, change.after);
2540
- return data;
2541
- }
2542
- //#endregion
2543
- //#region src/form/rebase.ts
2544
- /**
2545
- * Pure 3-way rebase for a change-tracked form. Given the current baseline `B0`,
2546
- * the live form `C`, and a fresh upstream `U`, produces the form rewritten as
2547
- * `U` + the local diff (`C` vs `B0`) reapplied on top:
2548
- *
2549
- * - Fields the user never touched adopt upstream's value.
2550
- * - Local edits survive (reapplied onto the upstream clone).
2551
- * - Fields changed on BOTH sides to different values are conflicts, resolved by
2552
- * `opts.conflict` (`'ours'` keeps local, `'theirs'` takes upstream).
2553
- *
2554
- * All inputs are WRAPPED form-data containers (`{ value: domainData }`). The
2555
- * result `next` is a fresh container; no input is mutated.
2556
- *
2557
- * `diffOptions` are forwarded to BOTH internal `buildFormDiff` passes so the
2558
- * same field exclusions apply (notably the `@db.column.version` column and the
2559
- * `$cas` policy) on the local and upstream sides — keep them identical to the
2560
- * options the caller uses for its own change tracking.
2561
- */
2562
- function buildFormRebase(def, baseline, current, upstream, opts, diffOptions) {
2563
- const conflictMode = opts?.conflict ?? "ours";
2564
- const local = buildFormDiff(def, baseline, current, diffOptions).changes;
2565
- const upstreamChanges = buildFormDiff(def, baseline, upstream, diffOptions).changes;
2566
- const upstreamByPath = /* @__PURE__ */ new Map();
2567
- for (const uc of upstreamChanges) upstreamByPath.set(uc.path, uc);
2568
- const next = deepClone(upstream);
2569
- const conflicts = [];
2570
- for (const lc of local) {
2571
- const clearedAncestor = findClearedAncestor(lc.path, baseline, upstream);
2572
- if (clearedAncestor !== void 0) {
2573
- conflicts.push(clearedAncestor);
2574
- if (conflictMode === "ours") setByPath(next, clearedAncestor, deepClone(getByPath(current, clearedAncestor)));
2575
- continue;
2576
- }
2577
- const uc = upstreamByPath.get(lc.path);
2578
- if (uc !== void 0) {
2579
- if (deepEqual(lc.after, uc.after)) continue;
2580
- conflicts.push(lc.path);
2581
- if (conflictMode === "ours") reapply(def, next, lc);
2582
- continue;
2583
- }
2584
- reapply(def, next, lc);
2585
- }
2586
- const reapplied = buildFormDiff(def, upstream, deepClone(next), diffOptions).changes;
2587
- return {
2588
- next,
2589
- conflicts: [...new Set(conflicts)],
2590
- reapplied
2591
- };
2592
- }
2593
- /**
2594
- * Reapplies a single local change onto `next`, DEEP-CLONING its `after` value
2595
- * first. `lc.after` is a LIVE reference into `current` (buildFormDiff holds live
2596
- * refs), so for a `kind:'array'` or whole-object/union `set` change a raw apply
2597
- * would make `next.value`'s node `===` `current.value`'s node — violating the
2598
- * `FormRebaseResult.next` contract ("never aliases any input container"). The
2599
- * ancestor-clear branch already deep-clones before writing; this keeps the two
2600
- * leaf-reapply sites consistent.
2601
- */
2602
- function reapply(def, next, lc) {
2603
- applyFormChanges(def, next, [{
2604
- ...lc,
2605
- after: deepClone(lc.after)
2606
- }]);
2607
- }
2608
- /**
2609
- * Returns the SHALLOWEST strict ancestor of `leafPath` that was an object/array
2610
- * in `baseline` but is `null`/`undefined` in `upstream` (upstream cleared the
2611
- * subtree), or `undefined` when no ancestor was cleared. The leaf path itself is
2612
- * never considered an ancestor.
2613
- */
2614
- function findClearedAncestor(leafPath, baseline, upstream) {
2615
- if (!leafPath.includes(".")) return void 0;
2616
- const segs = leafPath.split(".");
2617
- let acc = "";
2618
- for (let i = 0; i < segs.length - 1; i++) {
2619
- acc = acc ? `${acc}.${segs[i]}` : segs[i];
2620
- const base = getByPath(baseline, acc);
2621
- if (typeof base !== "object" || base === null) continue;
2622
- const up = getByPath(upstream, acc);
2623
- if (up === null || up === void 0) return acc;
2624
- }
2625
- }
2626
- //#endregion
2627
- //#region src/form/union-detect.ts
2628
- /**
2629
- * True when ANY union field in the form resolves to a DIFFERENT discriminated
2630
- * variant between two wrapped data containers. A variant picker typically
2631
- * detects its variant index once at setup and keys the variant subtree on it,
2632
- * so a rebase that lands a different variant (via conflict OR an upstream-only
2633
- * switch) needs a remount to re-detect. This walks union + nested-object fields
2634
- * and compares `detectUnionVariant` at each union path.
2635
- *
2636
- * Scope note (pragmatic): walks standalone + nested-OBJECT union fields. Unions
2637
- * nested INSIDE array items are not walked — an array renderer that keeps a
2638
- * stable per-item key across in-place value mutations would not remount an
2639
- * existing row's picker on an upstream-driven variant flip, but that collision
2640
- * (a 3-way rebase landing a different union variant inside an unchanged array
2641
- * row) is a rare edge. TODO: extend to array-item unions if a real consumer
2642
- * hits a stuck picker inside an array row.
2643
- */
2644
- function unionVariantChanged(def, before, after) {
2645
- return walkUnionFields(def.fields, "", before, after);
2646
- }
2647
- function walkUnionFields(fields, prefix, before, after) {
2648
- for (const field of fields) {
2649
- if (field.phantom) continue;
2650
- const fullPath = field.path ? prefix ? `${prefix}.${field.path}` : field.path : prefix;
2651
- if (isUnionField(field)) {
2652
- const variants = field.unionVariants;
2653
- if (variants.length > 1) {
2654
- if (detectUnionVariant(getByPath(before, fullPath), variants) !== detectUnionVariant(getByPath(after, fullPath), variants)) return true;
2655
- }
2656
- continue;
2657
- }
2658
- if (isObjectField(field)) {
2659
- const objectDef = field.objectDef;
2660
- if (walkUnionFields(objectDef.fields, fullPath, before, after)) return true;
2661
- }
2662
- }
2663
- return false;
2664
- }
2665
- //#endregion
2666
- //#region src/form/grid.ts
2667
- /** Grid layout parsing for `@ui.form.grid.colSpan` / `@ui.form.grid.rowSpan`. */
2668
- const DEFAULT_COL_SPAN = 12;
2669
- const DEFAULT_ROW_SPAN = 1;
2670
- const COL_SPAN_ALIASES = {
2671
- full: 12,
2672
- half: 6,
2673
- third: 4
2674
- };
2675
- /** Accepts "1"-"12" and the aliases "full" (12), "half" (6), "third" (4). */
2676
- function parseColSpan(raw) {
2677
- if (!raw) return void 0;
2678
- const aliased = COL_SPAN_ALIASES[raw];
2679
- if (aliased !== void 0) return aliased;
2680
- const n = Number.parseInt(raw, 10);
2681
- if (Number.isFinite(n) && n >= 1 && n <= 12 && String(n) === raw) return n;
2682
- }
2683
- /** Accepts numeric strings "1"+; rejects "0", negatives, decimals, aliases. */
2684
- function parseRowSpan(raw) {
2685
- if (!raw) return void 0;
2686
- const n = Number.parseInt(raw, 10);
2687
- if (Number.isFinite(n) && n >= 1 && String(n) === raw) return n;
2688
- }
2689
- /**
2690
- * Resolve a field's grid footprint. Narrow defaults to full-width / single-row
2691
- * regardless of the desktop value, so authors can opt into a narrow override
2692
- * via the second annotation arg without it inheriting an unintended desktop span.
2693
- */
2694
- function resolveGridSpec(colSpan, rowSpan) {
2695
- return {
2696
- col: {
2697
- desktop: parseColSpan(colSpan?.desktop) ?? 12,
2698
- narrow: parseColSpan(colSpan?.narrow) ?? 12
2699
- },
2700
- row: {
2701
- desktop: parseRowSpan(rowSpan?.desktop) ?? 1,
2702
- narrow: parseRowSpan(rowSpan?.narrow) ?? 1
2703
- }
2704
- };
2705
- }
2706
- /**
2707
- * Build the UnoCSS class string for a field's grid footprint.
2708
- *
2709
- * - Skips desktop classes that match the default (`as-grid-item` already
2710
- * covers `col-span-full row-span-1`).
2711
- * - Skips narrow overrides that match the desktop value (no override needed).
2712
- * - The narrow variant uses the custom `as-narrow:` prefix, which the
2713
- * atscript-ui UnoCSS preset rewrites to `@container as-grid (max-width:
2714
- * 480px) { ... }`. The parent grid is registered as
2715
- * `container-name: as-grid` via the `as-form-grid` shortcut, so the
2716
- * rule resolves against the actual grid's inline size — not the viewport.
2717
- *
2718
- * Returned string is space-separated, ready to drop into a Vue class binding.
2719
- */
2720
- function buildGridClasses(spec) {
2721
- const out = [];
2722
- if (spec.col.desktop !== 12) out.push(`col-span-${spec.col.desktop}`);
2723
- if (spec.row.desktop !== 1) out.push(`row-span-${spec.row.desktop}`);
2724
- if (spec.col.narrow !== spec.col.desktop) out.push(`as-narrow:col-span-${spec.col.narrow}`);
2725
- if (spec.row.narrow !== spec.row.desktop) out.push(`as-narrow:row-span-${spec.row.narrow}`);
2726
- return out.join(" ");
2727
- }
2728
- //#endregion
2729
- //#region src/form/labels.ts
2730
- /** Singular label for an array field (used by AsArray for "Add <singular>"). */
2731
- function resolveSingularLabel(meta) {
2732
- if (!meta) return "item";
2733
- return getFieldMeta(meta, "ui.form.label.singular") || "item";
2734
- }
2735
- //#endregion
2736
- //#region src/form/decimal-format.ts
2737
- const WHITESPACE_GROUP_RE = /[   ]/g;
2738
- const numberFormatCache = /* @__PURE__ */ new Map();
2739
- function getNumberFormat(locale, opts) {
2740
- const key = `${locale ?? ""}|${opts.style ?? ""}|${opts.currency ?? ""}|${opts.currencyDisplay ?? ""}|${opts.useGrouping ?? ""}|${opts.minimumFractionDigits ?? ""}|${opts.maximumFractionDigits ?? ""}`;
2741
- let f = numberFormatCache.get(key);
2742
- if (!f) {
2743
- f = new Intl.NumberFormat(locale, opts);
2744
- numberFormatCache.set(key, f);
2745
- }
2746
- return f;
2747
- }
2748
- const decimalSeparatorCache = /* @__PURE__ */ new Map();
2749
- const thousandsSeparatorCache = /* @__PURE__ */ new Map();
2750
- const currencyDisplayCache = /* @__PURE__ */ new Map();
2751
- const currencyDecimalsCache = /* @__PURE__ */ new Map();
2752
- /** "." in en-US, "," in fr-FR. Returns "." when locale is undefined. */
2753
- function getDecimalSeparator(locale) {
2754
- const key = locale ?? "";
2755
- const cached = decimalSeparatorCache.get(key);
2756
- if (cached !== void 0) return cached;
2757
- let out = ".";
2758
- try {
2759
- out = getNumberFormat(locale, { useGrouping: false }).formatToParts(1.1).find((p) => p.type === "decimal")?.value ?? ".";
2760
- } catch {}
2761
- decimalSeparatorCache.set(key, out);
2762
- return out;
2763
- }
2764
- /**
2765
- * "," in en-US, NNBSP (U+202F) in fr-FR. Returns "" when no grouping is
2766
- * applied (or when Intl rejects the locale).
2767
- */
2768
- function getThousandsSeparator(locale) {
2769
- const key = locale ?? "";
2770
- const cached = thousandsSeparatorCache.get(key);
2771
- if (cached !== void 0) return cached;
2772
- let out = "";
2773
- try {
2774
- out = getNumberFormat(locale, { useGrouping: true }).formatToParts(1e6).find((p) => p.type === "group")?.value ?? "";
2775
- } catch {}
2776
- thousandsSeparatorCache.set(key, out);
2777
- return out;
2778
- }
2779
- function getCurrencyDisplayParts(code, locale) {
2780
- const key = `${locale ?? ""}|${code}`;
2781
- const cached = currencyDisplayCache.get(key);
2782
- if (cached) return cached;
2783
- let out = {
2784
- symbol: code,
2785
- position: "prefix"
2786
- };
2787
- try {
2788
- const parts = getNumberFormat(locale, {
2789
- style: "currency",
2790
- currency: code,
2791
- currencyDisplay: "narrowSymbol"
2792
- }).formatToParts(0);
2793
- const idxCur = parts.findIndex((p) => p.type === "currency");
2794
- const idxInt = parts.findIndex((p) => p.type === "integer");
2795
- out = {
2796
- symbol: parts[idxCur]?.value ?? code,
2797
- position: idxInt === -1 || idxCur < idxInt ? "prefix" : "suffix"
2798
- };
2799
- } catch {}
2800
- currencyDisplayCache.set(key, out);
2801
- return out;
2802
- }
2803
- /**
2804
- * Currency's natural decimal count via Intl. JPY=0, USD/EUR=2, BHD/KWD=3.
2805
- * Returns `undefined` for codes Intl doesn't know — caller falls back to
2806
- * `dbPrecisionScale`.
2807
- */
2808
- function getCurrencyDecimals(code, locale) {
2809
- if (!code) return void 0;
2810
- const key = `${locale ?? ""}|${code}`;
2811
- if (currencyDecimalsCache.has(key)) return currencyDecimalsCache.get(key);
2812
- let out;
2813
- try {
2814
- const max = getNumberFormat(locale, {
2815
- style: "currency",
2816
- currency: code
2817
- }).resolvedOptions().maximumFractionDigits;
2818
- out = typeof max === "number" ? max : void 0;
2819
- } catch {
2820
- out = void 0;
2821
- }
2822
- currencyDecimalsCache.set(key, out);
2823
- return out;
2824
- }
2825
- /**
2826
- * Parse a user-typed decimal string. Returns the canonical decimal
2827
- * (no thousands separator, "." as decimal separator) or `null` if invalid.
2828
- * Accepts both "." and "," as the decimal separator (locale-aware).
2829
- * Strips the locale thousands separator. Preserves sign. Does NOT
2830
- * enforce scale.
2831
- */
2832
- function parseDecimalInput(raw, locale) {
2833
- if (typeof raw !== "string") return null;
2834
- const trimmed = raw.trim();
2835
- if (trimmed === "") return null;
2836
- const decSep = getDecimalSeparator(locale);
2837
- const thouSep = getThousandsSeparator(locale);
2838
- let sign = "";
2839
- let body = trimmed;
2840
- if (body.startsWith("-")) {
2841
- sign = "-";
2842
- body = body.slice(1);
2843
- } else if (body.startsWith("+")) body = body.slice(1);
2844
- if (body.length === 0) return null;
2845
- if (body.includes("-") || body.includes("+")) return null;
2846
- if (thouSep && body.includes(thouSep)) {
2847
- const decIdx = body.indexOf(decSep);
2848
- const headRaw = decIdx === -1 ? body : body.slice(0, decIdx);
2849
- const tail = decIdx === -1 ? "" : body.slice(decIdx);
2850
- if (tail.includes(thouSep)) return null;
2851
- if (headRaw.includes(thouSep)) {
2852
- const groups = headRaw.split(thouSep);
2853
- const first = groups[0];
2854
- if (first.length < 1 || first.length > 3 || !/^\d+$/.test(first)) return null;
2855
- for (let i = 1; i < groups.length; i += 1) if (!/^\d{3}$/.test(groups[i])) return null;
2856
- }
2857
- body = `${headRaw.split(thouSep).join("")}${tail}`;
2858
- }
2859
- body = body.replace(WHITESPACE_GROUP_RE, "");
2860
- if (decSep !== ".") {
2861
- if ((body.match(/,/g)?.length ?? 0) > 1) return null;
2862
- if (body.includes(".") && body.includes(",")) return null;
2863
- if (body.includes(",")) body = body.replace(",", ".");
2864
- } else if (body.includes(",")) {
2865
- if (body.includes(".")) return null;
2866
- if ((body.match(/,/g)?.length ?? 0) > 1) return null;
2867
- body = body.replace(",", ".");
2868
- }
2869
- if (!/^\d*\.?\d*$/.test(body)) return null;
2870
- if (body === "" || body === ".") return null;
2871
- if (body.endsWith(".")) body = body.slice(0, -1);
2872
- if (body.startsWith(".")) body = `0${body}`;
2873
- const dot = body.indexOf(".");
2874
- if (dot === -1) body = body.replace(/^0+(\d)/, "$1");
2875
- else {
2876
- const head = body.slice(0, dot);
2877
- const tail = body.slice(dot);
2878
- body = `${head.replace(/^0+(\d)/, "$1")}${tail}`;
2879
- }
2880
- if (sign === "-" && /^0+(\.0+)?$/.test(body)) sign = "";
2881
- return `${sign}${body}`;
2882
- }
2883
- /**
2884
- * Enforce a fractional-digit count by truncating or padding. String-only —
2885
- * no float arithmetic. Default behaviour truncates (no rounding) so digits
2886
- * the user typed can't silently shift. Pass `roundHalfUp: true` to round.
2887
- *
2888
- * enforceScale("12.345", 2) → "12.34" (truncate)
2889
- * enforceScale("12.3", 4) → "12.3000" (pad)
2890
- * enforceScale("12", 0) → "12"
2891
- * enforceScale("12.99", 0) → "12" (no rounding)
2892
- */
2893
- function enforceScale(s, scale, opts) {
2894
- if (typeof s !== "string" || s === "") return s;
2895
- if (scale === void 0 || scale < 0) return s;
2896
- const parts = splitDecimalString(s);
2897
- if (scale === 0) {
2898
- if (opts?.roundHalfUp && parts.decimal.length > 0 && parts.decimal[0] >= "5") {
2899
- const bumped = addOne(parts.integer);
2900
- return joinDecimalString({
2901
- sign: parts.sign,
2902
- integer: bumped,
2903
- decimal: ""
2904
- });
2905
- }
2906
- return joinDecimalString({
2907
- sign: parts.sign,
2908
- integer: parts.integer,
2909
- decimal: ""
2910
- });
2911
- }
2912
- if (parts.decimal.length === scale) return joinDecimalString(parts);
2913
- if (parts.decimal.length < scale) return joinDecimalString({
2914
- sign: parts.sign,
2915
- integer: parts.integer,
2916
- decimal: parts.decimal.padEnd(scale, "0")
2917
- });
2918
- let head = parts.decimal.slice(0, scale);
2919
- const dropped = parts.decimal.slice(scale);
2920
- let integer = parts.integer;
2921
- if (opts?.roundHalfUp && dropped.length > 0 && dropped[0] >= "5") {
2922
- const bumpedFrac = addOne(head);
2923
- if (bumpedFrac.length > head.length) {
2924
- integer = addOne(integer);
2925
- head = "0".repeat(scale);
2926
- } else head = bumpedFrac;
2927
- }
2928
- return joinDecimalString({
2929
- sign: parts.sign,
2930
- integer,
2931
- decimal: head
2932
- });
2933
- }
2934
- function addOne(digits) {
2935
- if (digits === "") return "1";
2936
- const out = digits.split("");
2937
- let i = out.length - 1;
2938
- let carry = 1;
2939
- while (i >= 0 && carry > 0) {
2940
- const d = out[i].charCodeAt(0) - 48 + carry | 0;
2941
- if (d >= 10) {
2942
- out[i] = "0";
2943
- carry = 1;
2944
- } else {
2945
- out[i] = String.fromCharCode(d + 48);
2946
- carry = 0;
2947
- }
2948
- i -= 1;
2949
- }
2950
- if (carry > 0) out.unshift("1");
2951
- return out.join("");
2952
- }
2953
- function splitDecimalString(s) {
2954
- if (typeof s !== "string" || s === "") return {
2955
- sign: "",
2956
- integer: "0",
2957
- decimal: ""
2958
- };
2959
- let sign = "";
2960
- let body = s;
2961
- if (body.startsWith("-")) {
2962
- sign = "-";
2963
- body = body.slice(1);
2964
- } else if (body.startsWith("+")) body = body.slice(1);
2965
- if (body === "") return {
2966
- sign: "",
2967
- integer: "0",
2968
- decimal: ""
2969
- };
2970
- const dot = body.indexOf(".");
2971
- let integer;
2972
- let decimal;
2973
- if (dot === -1) {
2974
- integer = body;
2975
- decimal = "";
2976
- } else {
2977
- integer = body.slice(0, dot);
2978
- decimal = body.slice(dot + 1);
2979
- }
2980
- if (integer === "") integer = "0";
2981
- integer = integer.replace(/^0+(\d)/, "$1");
2982
- if (sign === "-" && integer === "0" && !decimal.replace(/0/g, "")) sign = "";
2983
- return {
2984
- sign,
2985
- integer,
2986
- decimal
2987
- };
2988
- }
2989
- function joinDecimalString(parts) {
2990
- const integer = parts.integer === "" ? "0" : parts.integer;
2991
- const decimal = parts.decimal;
2992
- const body = decimal === "" ? integer : `${integer}.${decimal}`;
2993
- return `${parts.sign}${body}`;
2994
- }
2995
- function formatDecimalForDisplay(opts) {
2996
- const { value, scale, locale, currency, unit, useGrouping = currency !== void 0 || unit !== void 0 || scale !== void 0 } = opts;
2997
- if (value === null || value === void 0 || value === "") return "";
2998
- let canonical;
2999
- if (typeof value === "number") {
3000
- if (!Number.isFinite(value)) return "";
3001
- canonical = String(value);
3002
- } else canonical = value;
3003
- if (!/^[+-]?\d*(\.\d*)?$/.test(canonical) || canonical === "." || canonical === "-") return canonical;
3004
- if (scale !== void 0 && scale >= 0) canonical = enforceScale(canonical, scale);
3005
- const parts = splitDecimalString(canonical);
3006
- const asNumber = Number(canonical);
3007
- const intlSafe = Number.isFinite(asNumber);
3008
- if (currency) {
3009
- try {
3010
- const fmt = getNumberFormat(locale, {
3011
- style: "currency",
3012
- currency,
3013
- currencyDisplay: "narrowSymbol",
3014
- minimumFractionDigits: scale,
3015
- maximumFractionDigits: scale,
3016
- useGrouping
3017
- });
3018
- if (intlSafe) return fmt.format(asNumber);
3019
- } catch {}
3020
- return `${currency} ${formatPlain(parts, scale, locale, useGrouping)}`;
3021
- }
3022
- const base = formatPlain(parts, scale, locale, useGrouping);
3023
- return unit ? `${base} ${unit}` : base;
3024
- }
3025
- function formatPlain(parts, scale, locale, useGrouping) {
3026
- const intStr = useGrouping ? groupInteger(parts.integer, locale) : parts.integer;
3027
- const decStr = scale !== void 0 && scale >= 0 ? parts.decimal.padEnd(scale, "0").slice(0, scale) : parts.decimal;
3028
- const decSep = getDecimalSeparator(locale);
3029
- const body = decStr.length > 0 ? `${intStr}${decSep}${decStr}` : intStr;
3030
- return `${parts.sign}${body}`;
3031
- }
3032
- /**
3033
- * Insert the locale's thousands separator into a plain integer string.
3034
- * Pure string-based — no float math, handles arbitrary length.
3035
- */
3036
- function groupInteger(integer, locale) {
3037
- const sep = getThousandsSeparator(locale);
3038
- if (!sep) return integer;
3039
- if (integer.length <= 3) return integer;
3040
- const out = [];
3041
- let i = integer.length;
3042
- while (i > 3) {
3043
- out.unshift(integer.slice(i - 3, i));
3044
- i -= 3;
3045
- }
3046
- out.unshift(integer.slice(0, i));
3047
- return out.join(sep);
3048
- }
3049
- //#endregion
3050
- //#region src/table/value-kind.ts
3051
- /** Storage kinds that hold plain numbers (a `timestamp` is epoch ms, but filters treat it as a date). */
3052
- const NUMERIC_VALUE_KINDS = new Set([
3053
- "number",
3054
- "integer",
3055
- "decimal"
3056
- ]);
3057
- /**
3058
- * The typed value of one of a column's `options` — the literal itself
3059
- * (`true`, `3`, `'a'`), falling back to the string `key` for a hand-built
3060
- * column that has no `value`.
3061
- *
3062
- * @internal Shared with `@atscript/vue-table`.
3063
- */
3064
- function optionValue(option) {
3065
- return option.value ?? option.key;
3066
- }
3067
- //#endregion
3068
- //#region src/table/column-resolver.ts
3069
- /** Get sortable columns. */
3070
- function getSortableColumns(def) {
3071
- return def.columns.filter((c) => c.sortable);
3072
- }
3073
- /** Get filterable columns. */
3074
- function getFilterableColumns(def) {
3075
- return def.columns.filter((c) => c.filterable);
3076
- }
3077
- /** Find a column by path. */
3078
- function getColumn(def, path) {
3079
- return def.columns.find((c) => c.path === path);
3080
- }
3081
- //#endregion
3082
- //#region src/table/navigate-href.ts
3083
- /**
3084
- * Compute the href a `processor: 'navigate'` action would open — synchronously,
3085
- * at render time. Mirrors the interpolation `Client` performs when the action
3086
- * is invoked (`action.value` with every `$1` replaced by the URL-encoded,
3087
- * `/`-joined `preferredId` fields — see `encodeNavigateId`), so tables can
3088
- * render navigate actions as real `<a href>` anchors and native link behaviour
3089
- * (middle-click → new tab, copy link, hover preview) just works.
3090
- *
3091
- * Returns `undefined` when no link is possible — the caller should fall back to
3092
- * a button and let `Client` handle the invoke:
3093
- *
3094
- * - `action.processor !== 'navigate'` — backend/custom actions stay buttons;
3095
- * - row-level action with `id === undefined` — the row is not identifiable
3096
- * (note this deliberately differs from `Client`, which navigates to the raw
3097
- * template in that case; a raw-template href would be a broken link);
3098
- * - row-level action with an empty `preferredId` — `$1` has nothing to encode.
3099
- *
3100
- * Table/rows-level navigate actions carry no `$1` placeholder and return
3101
- * `action.value` verbatim.
3102
- *
3103
- * A delegated action (`action.idMap`, since 0.1.147) reads `id` as one of THIS
3104
- * table's rows (or identifiers) and encodes the owner's identification it maps
3105
- * to, in `Object.keys(idMap)` order — the same as `Client`. A row the map
3106
- * cannot address (a missing path) has no link.
3107
- */
3108
- function navigateHrefFor(action, id, preferredId) {
3109
- if (action.processor !== "navigate") return void 0;
3110
- if (action.level !== "row") return action.value;
3111
- if (id === void 0) return void 0;
3112
- if (action.idMap) {
3113
- let mapped;
3114
- try {
3115
- mapped = (0, _atscript_db_client.actionIdentifier)(action, id, []);
3116
- } catch {
3117
- return;
3118
- }
3119
- return action.value.replace(/\$1/g, (0, _atscript_db_client.encodeNavigateId)(mapped, Object.keys(action.idMap)));
3120
- }
3121
- if (preferredId.length === 0) return void 0;
3122
- return action.value.replace(/\$1/g, (0, _atscript_db_client.encodeNavigateId)(id, preferredId));
3123
- }
3124
- //#endregion
3125
- //#region src/nav/model-routes.ts
3126
- /**
3127
- * Derives navigable routes from DB-backed models' metadata.
3128
- *
3129
- * A model is included only when it is a DB entity (`@db.table`, `@db.view`,
3130
- * or `@db.view.for`) AND a path can be derived: `@db.http.path` first, then
3131
- * the string value of `@db.table` / `@db.view`, then the type's own id
3132
- * as-is. Models where none of these yield a non-empty path are omitted.
3133
- *
3134
- * Routes are sorted by `order` ascending (undefined last, ties keep input
3135
- * order). Hidden models are returned with `hidden: true` — filtering and
3136
- * grouping are left to the consumer.
3137
- */
3138
- function buildModelRoutes(models) {
3139
- const routes = [];
3140
- for (const model of models) {
3141
- const table = getFieldMeta(model, DB_TABLE);
3142
- const view = getFieldMeta(model, DB_VIEW);
3143
- const isView = view !== void 0 || hasFieldMeta(model, "db.view.for");
3144
- if (table === void 0 && !isView) continue;
3145
- const path = resolvePath(model, table, view);
3146
- if (path === void 0) continue;
3147
- const route = {
3148
- model,
3149
- path,
3150
- label: getFieldMeta(model, "meta.label") ?? humanizePath(path.slice(path.lastIndexOf("/") + 1)),
3151
- kind: isView ? "view" : "table"
3152
- };
3153
- const group = getFieldMeta(model, UI_NAV_GROUP);
3154
- if (typeof group === "string") route.group = group;
3155
- const order = getFieldMeta(model, UI_NAV_ORDER);
3156
- if (typeof order === "number") route.order = order;
3157
- if (getFieldMeta(model, "ui.nav.hidden") === true) route.hidden = true;
3158
- routes.push(route);
3159
- }
3160
- routes.sort((a, b) => {
3161
- const ao = a.order ?? Number.POSITIVE_INFINITY;
3162
- const bo = b.order ?? Number.POSITIVE_INFINITY;
3163
- return ao === bo ? 0 : ao - bo;
3164
- });
3165
- return routes;
3166
- }
3167
- /** `db.http.path` > string `db.table`/`db.view` name > type id — mirrors moost-db's controller prefix resolution, so the path matches the HTTP mount of a token-bound controller. */
3168
- function resolvePath(model, table, view) {
3169
- const http = getFieldMeta(model, DB_HTTP_PATH);
3170
- let raw;
3171
- if (typeof http === "string") raw = http;
3172
- else if (typeof table === "string") raw = table;
3173
- else if (typeof view === "string") raw = view;
3174
- else if (typeof model.id === "string") raw = model.id;
3175
- if (!raw) return void 0;
3176
- const path = raw.replace(/^\/+|\/+$/g, "");
3177
- return path.length > 0 ? path : void 0;
3178
- }
3179
- //#endregion
3180
- exports.DB_AMOUNT_CURRENCY = DB_AMOUNT_CURRENCY;
3181
- exports.DB_AMOUNT_CURRENCY_REF = DB_AMOUNT_CURRENCY_REF;
3182
- exports.DB_COLUMN_PRECISION = DB_COLUMN_PRECISION;
3183
- exports.DB_HTTP_PATH = DB_HTTP_PATH;
3184
- exports.DB_REL_FK = DB_REL_FK;
3185
- exports.DB_UNIT = DB_UNIT;
3186
- exports.DB_UNIT_REF = DB_UNIT_REF;
3187
- exports.DEFAULT_COL_SPAN = DEFAULT_COL_SPAN;
3188
- exports.DEFAULT_ROW_SPAN = DEFAULT_ROW_SPAN;
3189
- exports.EXPECT_MAX_LENGTH = EXPECT_MAX_LENGTH;
3190
- exports.FORM_ERROR_KEY = FORM_ERROR_KEY;
3191
- exports.META_DEFAULT = META_DEFAULT;
3192
- exports.META_DESCRIPTION = META_DESCRIPTION;
3193
- exports.META_ID = META_ID;
3194
- exports.META_LABEL = META_LABEL;
3195
- exports.META_READONLY = META_READONLY;
3196
- exports.META_REQUIRED = META_REQUIRED;
3197
- exports.META_SENSITIVE = META_SENSITIVE;
3198
- exports.NUMERIC_VALUE_KINDS = NUMERIC_VALUE_KINDS;
3199
- exports.StaticFieldResolver = StaticFieldResolver;
3200
- exports.UI_DICT_ATTR = UI_DICT_ATTR;
3201
- exports.UI_DICT_DESCR = UI_DICT_DESCR;
3202
- exports.UI_DICT_FILTERABLE = UI_DICT_FILTERABLE;
3203
- exports.UI_DICT_LABEL = UI_DICT_LABEL;
3204
- exports.UI_DICT_SEARCHABLE = UI_DICT_SEARCHABLE;
3205
- exports.UI_DICT_SORTABLE = UI_DICT_SORTABLE;
3206
- exports.UI_FORM_ACTION = UI_FORM_ACTION;
3207
- exports.UI_FORM_ATTR = UI_FORM_ATTR;
3208
- exports.UI_FORM_AUTOCOMPLETE = UI_FORM_AUTOCOMPLETE;
3209
- exports.UI_FORM_CLASSES = UI_FORM_CLASSES;
3210
- exports.UI_FORM_COMPONENT = UI_FORM_COMPONENT;
3211
- exports.UI_FORM_DISABLED = UI_FORM_DISABLED;
3212
- exports.UI_FORM_FN_ATTR = UI_FORM_FN_ATTR;
3213
- exports.UI_FORM_FN_CLASSES = UI_FORM_FN_CLASSES;
3214
- exports.UI_FORM_FN_DESCRIPTION = UI_FORM_FN_DESCRIPTION;
3215
- exports.UI_FORM_FN_DISABLED = UI_FORM_FN_DISABLED;
3216
- exports.UI_FORM_FN_HIDDEN = UI_FORM_FN_HIDDEN;
3217
- exports.UI_FORM_FN_HINT = UI_FORM_FN_HINT;
3218
- exports.UI_FORM_FN_LABEL = UI_FORM_FN_LABEL;
3219
- exports.UI_FORM_FN_OPTIONS = UI_FORM_FN_OPTIONS;
3220
- exports.UI_FORM_FN_PLACEHOLDER = UI_FORM_FN_PLACEHOLDER;
3221
- exports.UI_FORM_FN_PREFIX = UI_FORM_FN_PREFIX;
3222
- exports.UI_FORM_FN_READONLY = UI_FORM_FN_READONLY;
3223
- exports.UI_FORM_FN_STYLES = UI_FORM_FN_STYLES;
3224
- exports.UI_FORM_FN_SUBMIT_DISABLED = UI_FORM_FN_SUBMIT_DISABLED;
3225
- exports.UI_FORM_FN_SUBMIT_TEXT = UI_FORM_FN_SUBMIT_TEXT;
3226
- exports.UI_FORM_FN_TITLE = UI_FORM_FN_TITLE;
3227
- exports.UI_FORM_FN_VALUE = UI_FORM_FN_VALUE;
3228
- exports.UI_FORM_GRID_COL_SPAN = UI_FORM_GRID_COL_SPAN;
3229
- exports.UI_FORM_GRID_ROW_SPAN = UI_FORM_GRID_ROW_SPAN;
3230
- exports.UI_FORM_HIDDEN = UI_FORM_HIDDEN;
3231
- exports.UI_FORM_HINT = UI_FORM_HINT;
3232
- exports.UI_FORM_LABEL_SINGULAR = UI_FORM_LABEL_SINGULAR;
3233
- exports.UI_FORM_OPTIONS = UI_FORM_OPTIONS;
3234
- exports.UI_FORM_ORDER = UI_FORM_ORDER;
3235
- exports.UI_FORM_PLACEHOLDER = UI_FORM_PLACEHOLDER;
3236
- exports.UI_FORM_PREFIX = UI_FORM_PREFIX;
3237
- exports.UI_FORM_PREFIX_ICON = UI_FORM_PREFIX_ICON;
3238
- exports.UI_FORM_PREFIX_REF = UI_FORM_PREFIX_REF;
3239
- exports.UI_FORM_STYLES = UI_FORM_STYLES;
3240
- exports.UI_FORM_SUBMIT_TEXT = UI_FORM_SUBMIT_TEXT;
3241
- exports.UI_FORM_SUFFIX = UI_FORM_SUFFIX;
3242
- exports.UI_FORM_SUFFIX_ICON = UI_FORM_SUFFIX_ICON;
3243
- exports.UI_FORM_SUFFIX_REF = UI_FORM_SUFFIX_REF;
3244
- exports.UI_FORM_TYPE = UI_FORM_TYPE;
3245
- exports.UI_FORM_VALIDATE = UI_FORM_VALIDATE;
3246
- exports.UI_NAV_GROUP = UI_NAV_GROUP;
3247
- exports.UI_NAV_HIDDEN = UI_NAV_HIDDEN;
3248
- exports.UI_NAV_ORDER = UI_NAV_ORDER;
3249
- exports.UI_TABLE_ATTR = UI_TABLE_ATTR;
3250
- exports.UI_TABLE_CLASSES = UI_TABLE_CLASSES;
3251
- exports.UI_TABLE_COMPONENT = UI_TABLE_COMPONENT;
3252
- exports.UI_TABLE_EXCLUDE = UI_TABLE_EXCLUDE;
3253
- exports.UI_TABLE_FN_ATTR = UI_TABLE_FN_ATTR;
3254
- exports.UI_TABLE_FN_CLASSES = UI_TABLE_FN_CLASSES;
3255
- exports.UI_TABLE_FN_PREFIX = UI_TABLE_FN_PREFIX;
3256
- exports.UI_TABLE_FN_STYLES = UI_TABLE_FN_STYLES;
3257
- exports.UI_TABLE_ORDER = UI_TABLE_ORDER;
3258
- exports.UI_TABLE_SELECT_WITH = UI_TABLE_SELECT_WITH;
3259
- exports.UI_TABLE_STYLES = UI_TABLE_STYLES;
3260
- exports.UI_TABLE_TYPE = UI_TABLE_TYPE;
3261
- exports.UI_TABLE_WIDTH = UI_TABLE_WIDTH;
3262
- exports.UI_TYPE = UI_TYPE;
3263
- exports.ValueHelpClient = ValueHelpClient;
3264
- exports.WF_ACTION_WITH_DATA = WF_ACTION_WITH_DATA;
3265
- exports.applyFormChanges = applyFormChanges;
3266
- exports.asArray = asArray;
3267
- exports.buildDescendantErrorCounts = buildDescendantErrorCounts;
3268
- exports.buildFormDiff = buildFormDiff;
3269
- exports.buildFormRebase = buildFormRebase;
3270
- exports.buildGridClasses = buildGridClasses;
3271
- exports.buildModelRoutes = buildModelRoutes;
3272
- exports.buildUnionVariants = buildUnionVariants;
3273
- exports.collectDirtyPaths = collectDirtyPaths;
3274
- exports.createFieldValidator = createFieldValidator;
3275
- exports.createFormData = createFormData;
3276
- exports.createFormDef = createFormDef;
3277
- exports.createFormValueResolver = createFormValueResolver;
3278
- exports.createTableDef = createTableDef;
3279
- exports.deepClone = deepClone;
3280
- exports.deepEqual = deepEqual;
3281
- exports.defaultResolver = defaultResolver;
3282
- exports.deleteByPath = deleteByPath;
3283
- exports.detectUnionVariant = detectUnionVariant;
3284
- exports.enforceScale = enforceScale;
3285
- exports.escapeRegex = escapeRegex;
3286
- exports.extractFieldLiteralOptions = extractFieldLiteralOptions;
3287
- exports.extractLiteralOptions = extractLiteralOptions;
3288
- exports.extractMeasurement = extractMeasurement;
3289
- exports.extractValueHelp = extractValueHelp;
3290
- exports.fetchDistinctValues = fetchDistinctValues;
3291
- exports.formatDecimalForDisplay = formatDecimalForDisplay;
3292
- exports.getByPath = getByPath;
3293
- exports.getColumn = getColumn;
3294
- exports.getCurrencyDecimals = getCurrencyDecimals;
3295
- exports.getCurrencyDisplayParts = getCurrencyDisplayParts;
3296
- exports.getDecimalSeparator = getDecimalSeparator;
3297
- exports.getDeclaredFormActions = getDeclaredFormActions;
3298
- exports.getDefaultClientFactory = getDefaultClientFactory;
3299
- exports.getDefaultValidatorPlugins = getDefaultValidatorPlugins;
3300
- exports.getFieldMeta = getFieldMeta;
3301
- exports.getFilterableColumns = getFilterableColumns;
3302
- exports.getFormValidator = getFormValidator;
3303
- exports.getMetaCacheIdentity = getMetaCacheIdentity;
3304
- exports.getMetaEntry = getMetaEntry;
3305
- exports.getMetaTableDef = getMetaTableDef;
3306
- exports.getResolver = getResolver;
3307
- exports.getSortableColumns = getSortableColumns;
3308
- exports.getThousandsSeparator = getThousandsSeparator;
3309
- exports.groupInteger = groupInteger;
3310
- exports.hasComputedAnnotations = hasComputedAnnotations;
3311
- exports.hasFieldMeta = hasFieldMeta;
3312
- exports.invalidateValueHelpCache = invalidateValueHelpCache;
3313
- exports.isArrayField = isArrayField;
3314
- exports.isContainerKind = isContainerKind;
3315
- exports.isFieldHidden = isFieldHidden;
3316
- exports.isObjectField = isObjectField;
3317
- exports.isPathDirty = isPathDirty;
3318
- exports.isPickerDeclined = isPickerDeclined;
3319
- exports.isPureLiteralUnion = isPureLiteralUnion;
3320
- exports.isTupleField = isTupleField;
3321
- exports.isUnionField = isUnionField;
3322
- exports.iteratePathAncestors = iteratePathAncestors;
3323
- exports.joinDecimalString = joinDecimalString;
3324
- exports.joinPath = joinPath;
3325
- exports.mergeErrorMaps = mergeErrorMaps;
3326
- exports.navigateHrefFor = navigateHrefFor;
3327
- exports.omitPaths = omitPaths;
3328
- exports.onMetaCacheReset = onMetaCacheReset;
3329
- exports.optKey = optKey;
3330
- exports.optLabel = optLabel;
3331
- exports.optionLabel = optionLabel;
3332
- exports.optionValue = optionValue;
3333
- exports.parseColSpan = parseColSpan;
3334
- exports.parseDecimalInput = parseDecimalInput;
3335
- exports.parseRowSpan = parseRowSpan;
3336
- exports.parseStaticAttrs = parseStaticAttrs;
3337
- exports.parseStaticOptions = parseStaticOptions;
3338
- exports.resetDefaultClientFactory = resetDefaultClientFactory;
3339
- exports.resetMetaCache = resetMetaCache;
3340
- exports.resetValueHelpCache = resetValueHelpCache;
3341
- exports.resolveAttrs = resolveAttrs;
3342
- exports.resolveFieldProp = resolveFieldProp;
3343
- exports.resolveFormProp = resolveFormProp;
3344
- exports.resolveGridSpec = resolveGridSpec;
3345
- exports.resolveOptions = resolveOptions;
3346
- exports.resolveSingularLabel = resolveSingularLabel;
3347
- exports.resolveStatic = resolveStatic;
3348
- exports.resolveValueHelp = resolveValueHelp;
3349
- exports.retainMetaEntry = retainMetaEntry;
3350
- exports.setByPath = setByPath;
3351
- exports.setDefaultClientFactory = setDefaultClientFactory;
3352
- exports.setDefaultValidatorPlugins = setDefaultValidatorPlugins;
3353
- exports.setMetaCacheIdentity = setMetaCacheIdentity;
3354
- exports.setMetaCacheMaxEntries = setMetaCacheMaxEntries;
3355
- exports.setResolver = setResolver;
3356
- exports.setValueHelpCacheTtl = setValueHelpCacheTtl;
3357
- exports.splitDecimalString = splitDecimalString;
3358
- exports.str = str;
3359
- exports.unionVariantChanged = unionVariantChanged;
3360
- exports.validatorErrorsToMap = validatorErrorsToMap;
3361
- exports.valueHelpDictPaths = valueHelpDictPaths;
2
+ const require_annotation_keys = require("./shared/annotation-keys.cjs");
3
+ const require_types = require("./form/types.cjs");
4
+ const require_field_resolver = require("./shared/field-resolver.cjs");
5
+ const require_extract_literals = require("./value-help/extract-literals.cjs");
6
+ const require_extract_ref = require("./value-help/extract-ref.cjs");
7
+ const require_clone = require("./form/clone.cjs");
8
+ const require_path_utils = require("./form/path-utils.cjs");
9
+ const require_skipped_nav = require("./form/skipped-nav.cjs");
10
+ const require_create_form_def = require("./form/create-form-def.cjs");
11
+ const require_form_actions = require("./form/form-actions.cjs");
12
+ const require_dict_paths = require("./value-help/dict-paths.cjs");
13
+ const require_resolve_options = require("./value-help/resolve-options.cjs");
14
+ const require_str = require("./shared/str.cjs");
15
+ const require_value_help_client = require("./value-help/value-help-client.cjs");
16
+ const require_distinct_client = require("./value-help/distinct-client.cjs");
17
+ const require_client_factory = require("./client-factory.cjs");
18
+ const require_measurement = require("./form/measurement.cjs");
19
+ const require_create_table_def = require("./table/create-table-def.cjs");
20
+ const require_meta_cache = require("./shared/meta-cache.cjs");
21
+ const require_resolve = require("./value-help/resolve.cjs");
22
+ const require_error_utils = require("./form/error-utils.cjs");
23
+ const require_validate = require("./form/validate.cjs");
24
+ const require_diff = require("./form/diff.cjs");
25
+ const require_dirty = require("./form/dirty.cjs");
26
+ const require_apply = require("./form/apply.cjs");
27
+ const require_rebase = require("./form/rebase.cjs");
28
+ const require_union_detect = require("./form/union-detect.cjs");
29
+ const require_grid = require("./form/grid.cjs");
30
+ const require_labels = require("./form/labels.cjs");
31
+ const require_decimal_format = require("./form/decimal-format.cjs");
32
+ const require_value_kind = require("./table/value-kind.cjs");
33
+ const require_column_resolver = require("./table/column-resolver.cjs");
34
+ const require_navigate_href = require("./table/navigate-href.cjs");
35
+ const require_model_routes = require("./nav/model-routes.cjs");
36
+ exports.DB_AMOUNT_CURRENCY = require_annotation_keys.DB_AMOUNT_CURRENCY;
37
+ exports.DB_AMOUNT_CURRENCY_REF = require_annotation_keys.DB_AMOUNT_CURRENCY_REF;
38
+ exports.DB_COLUMN_PRECISION = require_annotation_keys.DB_COLUMN_PRECISION;
39
+ exports.DB_HTTP_PATH = require_annotation_keys.DB_HTTP_PATH;
40
+ exports.DB_REL_FK = require_annotation_keys.DB_REL_FK;
41
+ exports.DB_UNIT = require_annotation_keys.DB_UNIT;
42
+ exports.DB_UNIT_REF = require_annotation_keys.DB_UNIT_REF;
43
+ exports.DEFAULT_COL_SPAN = require_grid.DEFAULT_COL_SPAN;
44
+ exports.DEFAULT_ROW_SPAN = require_grid.DEFAULT_ROW_SPAN;
45
+ exports.EXPECT_MAX_LENGTH = require_annotation_keys.EXPECT_MAX_LENGTH;
46
+ exports.FORM_ERROR_KEY = require_error_utils.FORM_ERROR_KEY;
47
+ exports.META_DEFAULT = require_annotation_keys.META_DEFAULT;
48
+ exports.META_DESCRIPTION = require_annotation_keys.META_DESCRIPTION;
49
+ exports.META_ID = require_annotation_keys.META_ID;
50
+ exports.META_LABEL = require_annotation_keys.META_LABEL;
51
+ exports.META_READONLY = require_annotation_keys.META_READONLY;
52
+ exports.META_REQUIRED = require_annotation_keys.META_REQUIRED;
53
+ exports.META_SENSITIVE = require_annotation_keys.META_SENSITIVE;
54
+ exports.NUMERIC_VALUE_KINDS = require_value_kind.NUMERIC_VALUE_KINDS;
55
+ exports.StaticFieldResolver = require_field_resolver.StaticFieldResolver;
56
+ exports.UI_DICT_ATTR = require_annotation_keys.UI_DICT_ATTR;
57
+ exports.UI_DICT_DESCR = require_annotation_keys.UI_DICT_DESCR;
58
+ exports.UI_DICT_FILTERABLE = require_annotation_keys.UI_DICT_FILTERABLE;
59
+ exports.UI_DICT_LABEL = require_annotation_keys.UI_DICT_LABEL;
60
+ exports.UI_DICT_SEARCHABLE = require_annotation_keys.UI_DICT_SEARCHABLE;
61
+ exports.UI_DICT_SORTABLE = require_annotation_keys.UI_DICT_SORTABLE;
62
+ exports.UI_FORM_ACTION = require_annotation_keys.UI_FORM_ACTION;
63
+ exports.UI_FORM_ATTR = require_annotation_keys.UI_FORM_ATTR;
64
+ exports.UI_FORM_AUTOCOMPLETE = require_annotation_keys.UI_FORM_AUTOCOMPLETE;
65
+ exports.UI_FORM_CLASSES = require_annotation_keys.UI_FORM_CLASSES;
66
+ exports.UI_FORM_COMPONENT = require_annotation_keys.UI_FORM_COMPONENT;
67
+ exports.UI_FORM_DISABLED = require_annotation_keys.UI_FORM_DISABLED;
68
+ exports.UI_FORM_FN_ATTR = require_annotation_keys.UI_FORM_FN_ATTR;
69
+ exports.UI_FORM_FN_CLASSES = require_annotation_keys.UI_FORM_FN_CLASSES;
70
+ exports.UI_FORM_FN_DESCRIPTION = require_annotation_keys.UI_FORM_FN_DESCRIPTION;
71
+ exports.UI_FORM_FN_DISABLED = require_annotation_keys.UI_FORM_FN_DISABLED;
72
+ exports.UI_FORM_FN_HIDDEN = require_annotation_keys.UI_FORM_FN_HIDDEN;
73
+ exports.UI_FORM_FN_HINT = require_annotation_keys.UI_FORM_FN_HINT;
74
+ exports.UI_FORM_FN_LABEL = require_annotation_keys.UI_FORM_FN_LABEL;
75
+ exports.UI_FORM_FN_OPTIONS = require_annotation_keys.UI_FORM_FN_OPTIONS;
76
+ exports.UI_FORM_FN_PLACEHOLDER = require_annotation_keys.UI_FORM_FN_PLACEHOLDER;
77
+ exports.UI_FORM_FN_PREFIX = require_annotation_keys.UI_FORM_FN_PREFIX;
78
+ exports.UI_FORM_FN_READONLY = require_annotation_keys.UI_FORM_FN_READONLY;
79
+ exports.UI_FORM_FN_STYLES = require_annotation_keys.UI_FORM_FN_STYLES;
80
+ exports.UI_FORM_FN_SUBMIT_DISABLED = require_annotation_keys.UI_FORM_FN_SUBMIT_DISABLED;
81
+ exports.UI_FORM_FN_SUBMIT_TEXT = require_annotation_keys.UI_FORM_FN_SUBMIT_TEXT;
82
+ exports.UI_FORM_FN_TITLE = require_annotation_keys.UI_FORM_FN_TITLE;
83
+ exports.UI_FORM_FN_VALUE = require_annotation_keys.UI_FORM_FN_VALUE;
84
+ exports.UI_FORM_GRID_COL_SPAN = require_annotation_keys.UI_FORM_GRID_COL_SPAN;
85
+ exports.UI_FORM_GRID_ROW_SPAN = require_annotation_keys.UI_FORM_GRID_ROW_SPAN;
86
+ exports.UI_FORM_HIDDEN = require_annotation_keys.UI_FORM_HIDDEN;
87
+ exports.UI_FORM_HINT = require_annotation_keys.UI_FORM_HINT;
88
+ exports.UI_FORM_LABEL_SINGULAR = require_annotation_keys.UI_FORM_LABEL_SINGULAR;
89
+ exports.UI_FORM_OPTIONS = require_annotation_keys.UI_FORM_OPTIONS;
90
+ exports.UI_FORM_ORDER = require_annotation_keys.UI_FORM_ORDER;
91
+ exports.UI_FORM_PLACEHOLDER = require_annotation_keys.UI_FORM_PLACEHOLDER;
92
+ exports.UI_FORM_PREFIX = require_annotation_keys.UI_FORM_PREFIX;
93
+ exports.UI_FORM_PREFIX_ICON = require_annotation_keys.UI_FORM_PREFIX_ICON;
94
+ exports.UI_FORM_PREFIX_REF = require_annotation_keys.UI_FORM_PREFIX_REF;
95
+ exports.UI_FORM_STYLES = require_annotation_keys.UI_FORM_STYLES;
96
+ exports.UI_FORM_SUBMIT_TEXT = require_annotation_keys.UI_FORM_SUBMIT_TEXT;
97
+ exports.UI_FORM_SUFFIX = require_annotation_keys.UI_FORM_SUFFIX;
98
+ exports.UI_FORM_SUFFIX_ICON = require_annotation_keys.UI_FORM_SUFFIX_ICON;
99
+ exports.UI_FORM_SUFFIX_REF = require_annotation_keys.UI_FORM_SUFFIX_REF;
100
+ exports.UI_FORM_TYPE = require_annotation_keys.UI_FORM_TYPE;
101
+ exports.UI_FORM_VALIDATE = require_annotation_keys.UI_FORM_VALIDATE;
102
+ exports.UI_NAV_GROUP = require_annotation_keys.UI_NAV_GROUP;
103
+ exports.UI_NAV_HIDDEN = require_annotation_keys.UI_NAV_HIDDEN;
104
+ exports.UI_NAV_ORDER = require_annotation_keys.UI_NAV_ORDER;
105
+ exports.UI_TABLE_ATTR = require_annotation_keys.UI_TABLE_ATTR;
106
+ exports.UI_TABLE_CLASSES = require_annotation_keys.UI_TABLE_CLASSES;
107
+ exports.UI_TABLE_COMPONENT = require_annotation_keys.UI_TABLE_COMPONENT;
108
+ exports.UI_TABLE_EXCLUDE = require_annotation_keys.UI_TABLE_EXCLUDE;
109
+ exports.UI_TABLE_FN_ATTR = require_annotation_keys.UI_TABLE_FN_ATTR;
110
+ exports.UI_TABLE_FN_CLASSES = require_annotation_keys.UI_TABLE_FN_CLASSES;
111
+ exports.UI_TABLE_FN_PREFIX = require_annotation_keys.UI_TABLE_FN_PREFIX;
112
+ exports.UI_TABLE_FN_STYLES = require_annotation_keys.UI_TABLE_FN_STYLES;
113
+ exports.UI_TABLE_ORDER = require_annotation_keys.UI_TABLE_ORDER;
114
+ exports.UI_TABLE_SELECT_WITH = require_annotation_keys.UI_TABLE_SELECT_WITH;
115
+ exports.UI_TABLE_STYLES = require_annotation_keys.UI_TABLE_STYLES;
116
+ exports.UI_TABLE_TYPE = require_annotation_keys.UI_TABLE_TYPE;
117
+ exports.UI_TABLE_WIDTH = require_annotation_keys.UI_TABLE_WIDTH;
118
+ exports.UI_TYPE = require_annotation_keys.UI_TYPE;
119
+ exports.ValueHelpClient = require_value_help_client.ValueHelpClient;
120
+ exports.WF_ACTION_WITH_DATA = require_annotation_keys.WF_ACTION_WITH_DATA;
121
+ exports.applyFormChanges = require_apply.applyFormChanges;
122
+ exports.asArray = require_field_resolver.asArray;
123
+ exports.buildDescendantErrorCounts = require_error_utils.buildDescendantErrorCounts;
124
+ exports.buildFormDiff = require_diff.buildFormDiff;
125
+ exports.buildFormRebase = require_rebase.buildFormRebase;
126
+ exports.buildGridClasses = require_grid.buildGridClasses;
127
+ exports.buildModelRoutes = require_model_routes.buildModelRoutes;
128
+ exports.buildUnionVariants = require_create_form_def.buildUnionVariants;
129
+ exports.collectDirtyPaths = require_dirty.collectDirtyPaths;
130
+ exports.createFieldValidator = require_validate.createFieldValidator;
131
+ exports.createFormData = require_path_utils.createFormData;
132
+ exports.createFormDef = require_create_form_def.createFormDef;
133
+ exports.createFormValueResolver = require_path_utils.createFormValueResolver;
134
+ exports.createTableDef = require_create_table_def.createTableDef;
135
+ exports.deepClone = require_clone.deepClone;
136
+ exports.deepEqual = require_diff.deepEqual;
137
+ exports.defaultResolver = require_field_resolver.defaultResolver;
138
+ exports.deleteByPath = require_path_utils.deleteByPath;
139
+ exports.detectUnionVariant = require_path_utils.detectUnionVariant;
140
+ exports.enforceScale = require_decimal_format.enforceScale;
141
+ exports.escapeRegex = require_str.escapeRegex;
142
+ exports.extractFieldLiteralOptions = require_extract_literals.extractFieldLiteralOptions;
143
+ exports.extractLiteralOptions = require_extract_literals.extractLiteralOptions;
144
+ exports.extractMeasurement = require_measurement.extractMeasurement;
145
+ exports.extractValueHelp = require_extract_ref.extractValueHelp;
146
+ exports.fetchDistinctValues = require_distinct_client.fetchDistinctValues;
147
+ exports.formatDecimalForDisplay = require_decimal_format.formatDecimalForDisplay;
148
+ exports.getByPath = require_path_utils.getByPath;
149
+ exports.getColumn = require_column_resolver.getColumn;
150
+ exports.getCurrencyDecimals = require_decimal_format.getCurrencyDecimals;
151
+ exports.getCurrencyDisplayParts = require_decimal_format.getCurrencyDisplayParts;
152
+ exports.getDecimalSeparator = require_decimal_format.getDecimalSeparator;
153
+ exports.getDeclaredFormActions = require_form_actions.getDeclaredFormActions;
154
+ exports.getDefaultClientFactory = require_client_factory.getDefaultClientFactory;
155
+ exports.getDefaultValidatorPlugins = require_validate.getDefaultValidatorPlugins;
156
+ exports.getFieldMeta = require_field_resolver.getFieldMeta;
157
+ exports.getFilterableColumns = require_column_resolver.getFilterableColumns;
158
+ exports.getFormValidator = require_validate.getFormValidator;
159
+ exports.getMetaCacheIdentity = require_meta_cache.getMetaCacheIdentity;
160
+ exports.getMetaEntry = require_meta_cache.getMetaEntry;
161
+ exports.getMetaTableDef = require_meta_cache.getMetaTableDef;
162
+ exports.getResolver = require_field_resolver.getResolver;
163
+ exports.getSortableColumns = require_column_resolver.getSortableColumns;
164
+ exports.getThousandsSeparator = require_decimal_format.getThousandsSeparator;
165
+ exports.groupInteger = require_decimal_format.groupInteger;
166
+ exports.hasComputedAnnotations = require_field_resolver.hasComputedAnnotations;
167
+ exports.hasFieldMeta = require_field_resolver.hasFieldMeta;
168
+ exports.invalidateValueHelpCache = require_value_help_client.invalidateValueHelpCache;
169
+ exports.isArrayField = require_types.isArrayField;
170
+ exports.isContainerKind = require_validate.isContainerKind;
171
+ exports.isFieldHidden = require_field_resolver.isFieldHidden;
172
+ exports.isObjectField = require_types.isObjectField;
173
+ exports.isPathDirty = require_dirty.isPathDirty;
174
+ exports.isPickerDeclined = require_distinct_client.isPickerDeclined;
175
+ exports.isPureLiteralUnion = require_extract_literals.isPureLiteralUnion;
176
+ exports.isTupleField = require_types.isTupleField;
177
+ exports.isUnionField = require_types.isUnionField;
178
+ exports.iteratePathAncestors = require_error_utils.iteratePathAncestors;
179
+ exports.joinDecimalString = require_decimal_format.joinDecimalString;
180
+ exports.joinPath = require_path_utils.joinPath;
181
+ exports.mergeErrorMaps = require_error_utils.mergeErrorMaps;
182
+ exports.navigateHrefFor = require_navigate_href.navigateHrefFor;
183
+ exports.omitPaths = require_error_utils.omitPaths;
184
+ exports.omitSkippedNavFields = require_skipped_nav.omitSkippedNavFields;
185
+ exports.onMetaCacheReset = require_meta_cache.onMetaCacheReset;
186
+ exports.optKey = require_resolve_options.optKey;
187
+ exports.optLabel = require_resolve_options.optLabel;
188
+ exports.optionLabel = require_resolve_options.optionLabel;
189
+ exports.optionValue = require_value_kind.optionValue;
190
+ exports.parseColSpan = require_grid.parseColSpan;
191
+ exports.parseDecimalInput = require_decimal_format.parseDecimalInput;
192
+ exports.parseRowSpan = require_grid.parseRowSpan;
193
+ exports.parseStaticAttrs = require_field_resolver.parseStaticAttrs;
194
+ exports.parseStaticOptions = require_resolve_options.parseStaticOptions;
195
+ exports.resetDefaultClientFactory = require_client_factory.resetDefaultClientFactory;
196
+ exports.resetMetaCache = require_meta_cache.resetMetaCache;
197
+ exports.resetValueHelpCache = require_resolve.resetValueHelpCache;
198
+ exports.resolveAttrs = require_field_resolver.resolveAttrs;
199
+ exports.resolveFieldProp = require_field_resolver.resolveFieldProp;
200
+ exports.resolveFormProp = require_field_resolver.resolveFormProp;
201
+ exports.resolveGridSpec = require_grid.resolveGridSpec;
202
+ exports.resolveOptions = require_resolve_options.resolveOptions;
203
+ exports.resolveSingularLabel = require_labels.resolveSingularLabel;
204
+ exports.resolveStatic = require_field_resolver.resolveStatic;
205
+ exports.resolveValueHelp = require_resolve.resolveValueHelp;
206
+ exports.retainMetaEntry = require_meta_cache.retainMetaEntry;
207
+ exports.setByPath = require_path_utils.setByPath;
208
+ exports.setDefaultClientFactory = require_client_factory.setDefaultClientFactory;
209
+ exports.setDefaultValidatorPlugins = require_validate.setDefaultValidatorPlugins;
210
+ exports.setMetaCacheIdentity = require_meta_cache.setMetaCacheIdentity;
211
+ exports.setMetaCacheMaxEntries = require_meta_cache.setMetaCacheMaxEntries;
212
+ exports.setResolver = require_field_resolver.setResolver;
213
+ exports.setValueHelpCacheTtl = require_value_help_client.setValueHelpCacheTtl;
214
+ exports.splitDecimalString = require_decimal_format.splitDecimalString;
215
+ exports.str = require_str.str;
216
+ exports.unionVariantChanged = require_union_detect.unionVariantChanged;
217
+ exports.validatorErrorsToMap = require_error_utils.validatorErrorsToMap;
218
+ exports.valueHelpDictPaths = require_dict_paths.valueHelpDictPaths;