@atscript/ui 0.1.150 → 0.1.151

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -834,6 +834,65 @@ function str(value) {
834
834
  }
835
835
  //#endregion
836
836
  //#region src/value-help/value-help-client.ts
837
+ let cacheTtl = 5e3;
838
+ let searches = /* @__PURE__ */ new WeakMap();
839
+ /**
840
+ * How long (ms) a settled value-help search is reused for an identical
841
+ * search on the same client. Default 5000. `0` shares only searches still in
842
+ * flight; a negative value turns sharing off. Server-side rendering never
843
+ * shares (one process serves many viewers).
844
+ */
845
+ function setValueHelpCacheTtl(ms) {
846
+ cacheTtl = ms;
847
+ }
848
+ /**
849
+ * Drop shared value-help search results — for one `client`, or for every
850
+ * client when omitted. Call after writing to a dictionary outside the
851
+ * built-in table actions to make pickers refetch at once.
852
+ */
853
+ function invalidateValueHelpCache(client) {
854
+ if (client) searches.get(client)?.clear();
855
+ else searches = /* @__PURE__ */ new WeakMap();
856
+ }
857
+ function now() {
858
+ return typeof performance === "undefined" ? Date.now() : performance.now();
859
+ }
860
+ /** Cache key of a plain-JSON request; `undefined` when it holds anything else (never shared). */
861
+ function requestKey(request) {
862
+ let plain = true;
863
+ try {
864
+ const key = JSON.stringify(request, (_k, v) => {
865
+ if (typeof v === "function" || typeof v === "symbol") plain = false;
866
+ else if (v !== null && typeof v === "object" && !Array.isArray(v)) {
867
+ const proto = Object.getPrototypeOf(v);
868
+ if (proto !== Object.prototype && proto !== null) plain = false;
869
+ }
870
+ return v;
871
+ });
872
+ return plain ? key : void 0;
873
+ } catch {
874
+ return;
875
+ }
876
+ }
877
+ function sharedQuery(client, request) {
878
+ const run = () => client.query(request);
879
+ if (cacheTtl < 0 || typeof window === "undefined") return run();
880
+ const key = requestKey(request);
881
+ if (key === void 0) return run();
882
+ let byKey = searches.get(client);
883
+ if (!byKey) searches.set(client, byKey = /* @__PURE__ */ new Map());
884
+ const hit = byKey.get(key);
885
+ if (hit && (hit.settledAt === void 0 || now() - hit.settledAt < cacheTtl)) return hit.promise;
886
+ const entry = { promise: run().then((items) => {
887
+ entry.settledAt = now();
888
+ return items;
889
+ }, (err) => {
890
+ if (byKey.get(key) === entry) byKey.delete(key);
891
+ throw err;
892
+ }) };
893
+ byKey.set(key, entry);
894
+ return entry.promise;
895
+ }
837
896
  /**
838
897
  * Value-help query client. Wraps a `Client` from `@atscript/db-client`
839
898
  * with FK-specific search logic (regex fallback for non-searchable tables,
@@ -842,6 +901,9 @@ function str(value) {
842
901
  * Consumers resolve the target's metadata once via `resolveValueHelp(url)`
843
902
  * and pass the resulting `ResolvedValueHelp` to `search()`. Label resolution
844
903
  * for cells is deliberately unsupported — cells always display raw ids.
904
+ *
905
+ * Identical searches on the same `Client` are shared (see
906
+ * {@link setValueHelpCacheTtl}).
845
907
  */
846
908
  var ValueHelpClient = class {
847
909
  _client;
@@ -871,10 +933,11 @@ var ValueHelpClient = class {
871
933
  const search = buildOrFilter(text, selectFields, valueField ?? resolved.primaryKeys[0] ?? resolved.labelField);
872
934
  filter = scope ? { $and: [scope, search] } : search;
873
935
  }
874
- return { items: await this._client.query({
936
+ const items = await sharedQuery(this._client, {
875
937
  ...filter && { filter },
876
938
  controls
877
- }) };
939
+ });
940
+ return { items: Array.isArray(items) ? items.slice() : items };
878
941
  }
879
942
  };
880
943
  /**
@@ -972,17 +1035,21 @@ function resetDefaultClientFactory() {
972
1035
  //#endregion
973
1036
  //#region src/shared/meta-cache.ts
974
1037
  const cache = /* @__PURE__ */ new Map();
1038
+ /** `undefined` until the first `setMetaCacheIdentity` call; `null` = anonymous. */
1039
+ let identity;
975
1040
  /**
976
1041
  * Get or create the cache entry for `url`. First caller's `factory` seeds the
977
1042
  * `Client`; subsequent callers reuse it. On `meta` rejection, the entry is
978
- * evicted so the next call retries.
1043
+ * evicted so the next call retries. Without a browser `window` nothing is
1044
+ * cached.
979
1045
  */
980
1046
  function getMetaEntry(url, factory) {
981
- const existing = cache.get(url);
1047
+ const browser = typeof window !== "undefined";
1048
+ const existing = browser ? cache.get(url) : void 0;
982
1049
  if (existing) return existing;
983
1050
  const client = (factory ?? getDefaultClientFactory())(url);
984
1051
  const meta = client.meta().catch((err) => {
985
- cache.delete(url);
1052
+ if (cache.get(url) === entry) cache.delete(url);
986
1053
  throw err;
987
1054
  });
988
1055
  const entry = {
@@ -990,11 +1057,32 @@ function getMetaEntry(url, factory) {
990
1057
  meta,
991
1058
  type: meta.then((m) => (0, _atscript_typescript_utils.deserializeAnnotatedType)(m.type))
992
1059
  };
993
- cache.set(url, entry);
1060
+ if (browser) cache.set(url, entry);
994
1061
  return entry;
995
1062
  }
1063
+ /**
1064
+ * Drop every cached `/meta` — including the copy each cached `Client`
1065
+ * memoizes — and the value-help searches shared under them. Entries already
1066
+ * handed out keep working; the next `getMetaEntry` refetches.
1067
+ */
996
1068
  function resetMetaCache() {
1069
+ const entries = [...cache.values()];
997
1070
  cache.clear();
1071
+ for (const entry of entries) entry.client.invalidateMeta?.();
1072
+ invalidateValueHelpCache();
1073
+ }
1074
+ /**
1075
+ * Bind the meta cache to the current viewer. Call it whenever the signed-in
1076
+ * user or their role may have changed — after login, after logout and on
1077
+ * every reload of the current user. A key that differs from the previous
1078
+ * one resets the cache (`resetMetaCache`); the same key keeps it. `null` /
1079
+ * `undefined` = anonymous.
1080
+ */
1081
+ function setMetaCacheIdentity(key) {
1082
+ const next = key ?? null;
1083
+ if (next === identity) return;
1084
+ identity = next;
1085
+ resetMetaCache();
998
1086
  }
999
1087
  //#endregion
1000
1088
  //#region src/value-help/resolve.ts
@@ -1305,15 +1393,34 @@ function getFormValidator(def, opts) {
1305
1393
  };
1306
1394
  }
1307
1395
  /**
1396
+ * Root-only plugin: passes every descendant without visiting it. Only
1397
+ * `object` / `array` / `tuple` roots use it — their root-path errors (shape,
1398
+ * length, a container-level `@ui.form.validate`) are all decided before the
1399
+ * walk descends, so skipping the children cannot change the root error. A
1400
+ * union or intersection root evaluates its branches AT the root path, where
1401
+ * a branch's verdict depends on its children — those keep the full walk.
1402
+ */
1403
+ const skipDescendantsPlugin = (ctx) => ctx.path === "" ? void 0 : true;
1404
+ function skipsDescendants(prop) {
1405
+ const kind = prop.type.kind;
1406
+ return kind === "object" || kind === "array" || kind === "tuple";
1407
+ }
1408
+ /**
1308
1409
  * Creates a cached validator function for a single ATScript prop.
1309
1410
  *
1310
1411
  * The `Validator` instance is created lazily on first call and reused.
1311
1412
  * Returns `true` when valid, or the first error message string when invalid.
1413
+ * With `rootOnly`, an object / array / tuple prop is validated at its root
1414
+ * only (descendants are not walked — their errors would be discarded anyway).
1312
1415
  */
1313
1416
  function createFieldValidator(prop, opts) {
1314
1417
  let cached;
1315
1418
  return (value, externalCtx) => {
1316
- cached ??= new _atscript_typescript_utils.Validator(prop, { plugins: [serverManagedPlugin, ...defaultValidatorPlugins] });
1419
+ cached ??= new _atscript_typescript_utils.Validator(prop, { plugins: opts?.rootOnly && skipsDescendants(prop) ? [
1420
+ skipDescendantsPlugin,
1421
+ serverManagedPlugin,
1422
+ ...defaultValidatorPlugins
1423
+ ] : [serverManagedPlugin, ...defaultValidatorPlugins] });
1317
1424
  if (!cached.validate(value, true, externalCtx)) {
1318
1425
  if (opts?.rootOnly) {
1319
1426
  const rootError = cached.errors?.find((e) => e.path === "");
@@ -1555,20 +1662,10 @@ function diffKeyedArray(before, after, keyProps) {
1555
1662
  const afterByKey = /* @__PURE__ */ new Map();
1556
1663
  for (const el of after) if (isPlainObject(el)) afterByKey.set(keyOf(el, keyProps), el);
1557
1664
  if (beforeByKey.size !== before.length || afterByKey.size !== after.length) return { $replace: after };
1558
- if (beforeByKey.size === afterByKey.size) {
1559
- let sameMembershipAndContent = true;
1560
- for (const [k, el] of afterByKey) {
1561
- const prev = beforeByKey.get(k);
1562
- if (prev === void 0 || !deepEqual(prev, el)) {
1563
- sameMembershipAndContent = false;
1564
- break;
1565
- }
1566
- }
1567
- if (sameMembershipAndContent) return { $replace: after };
1568
- }
1569
1665
  const $insert = [];
1570
1666
  const $update = [];
1571
1667
  const $remove = [];
1668
+ let contentChanged = false;
1572
1669
  for (const [k, el] of afterByKey) {
1573
1670
  const prev = beforeByKey.get(k);
1574
1671
  if (prev === void 0) {
@@ -1576,10 +1673,12 @@ function diffKeyedArray(before, after, keyProps) {
1576
1673
  continue;
1577
1674
  }
1578
1675
  if (!deepEqual(prev, el)) {
1676
+ contentChanged = true;
1579
1677
  const partial = buildKeyedUpdate(prev, el, keyProps);
1580
1678
  if (partial) $update.push(partial);
1581
1679
  }
1582
1680
  }
1681
+ if (beforeByKey.size === afterByKey.size && $insert.length === 0 && !contentChanged) return { $replace: after };
1583
1682
  for (const [k, el] of beforeByKey) if (!afterByKey.has(k)) $remove.push(pickKeys(el, keyProps));
1584
1683
  return arrayOps({
1585
1684
  $update,
@@ -2943,6 +3042,7 @@ exports.getThousandsSeparator = getThousandsSeparator;
2943
3042
  exports.groupInteger = groupInteger;
2944
3043
  exports.hasComputedAnnotations = hasComputedAnnotations;
2945
3044
  exports.hasFieldMeta = hasFieldMeta;
3045
+ exports.invalidateValueHelpCache = invalidateValueHelpCache;
2946
3046
  exports.isArrayField = isArrayField;
2947
3047
  exports.isFieldHidden = isFieldHidden;
2948
3048
  exports.isObjectField = isObjectField;
@@ -2980,7 +3080,9 @@ exports.resolveValueHelp = resolveValueHelp;
2980
3080
  exports.setByPath = setByPath;
2981
3081
  exports.setDefaultClientFactory = setDefaultClientFactory;
2982
3082
  exports.setDefaultValidatorPlugins = setDefaultValidatorPlugins;
3083
+ exports.setMetaCacheIdentity = setMetaCacheIdentity;
2983
3084
  exports.setResolver = setResolver;
3085
+ exports.setValueHelpCacheTtl = setValueHelpCacheTtl;
2984
3086
  exports.splitDecimalString = splitDecimalString;
2985
3087
  exports.str = str;
2986
3088
  exports.unionVariantChanged = unionVariantChanged;
package/dist/index.d.cts CHANGED
@@ -421,6 +421,19 @@ interface ValueHelpSearchOptions {
421
421
  interface ValueHelpResult {
422
422
  items: Record<string, unknown>[];
423
423
  }
424
+ /**
425
+ * How long (ms) a settled value-help search is reused for an identical
426
+ * search on the same client. Default 5000. `0` shares only searches still in
427
+ * flight; a negative value turns sharing off. Server-side rendering never
428
+ * shares (one process serves many viewers).
429
+ */
430
+ declare function setValueHelpCacheTtl(ms: number): void;
431
+ /**
432
+ * Drop shared value-help search results — for one `client`, or for every
433
+ * client when omitted. Call after writing to a dictionary outside the
434
+ * built-in table actions to make pickers refetch at once.
435
+ */
436
+ declare function invalidateValueHelpCache(client?: Client): void;
424
437
  /**
425
438
  * Value-help query client. Wraps a `Client` from `@atscript/db-client`
426
439
  * with FK-specific search logic (regex fallback for non-searchable tables,
@@ -429,6 +442,9 @@ interface ValueHelpResult {
429
442
  * Consumers resolve the target's metadata once via `resolveValueHelp(url)`
430
443
  * and pass the resulting `ResolvedValueHelp` to `search()`. Label resolution
431
444
  * for cells is deliberately unsupported — cells always display raw ids.
445
+ *
446
+ * Identical searches on the same `Client` are shared (see
447
+ * {@link setValueHelpCacheTtl}).
432
448
  */
433
449
  declare class ValueHelpClient {
434
450
  private readonly _client;
@@ -673,6 +689,8 @@ interface TFieldValidatorOptions {
673
689
  *
674
690
  * The `Validator` instance is created lazily on first call and reused.
675
691
  * Returns `true` when valid, or the first error message string when invalid.
692
+ * With `rootOnly`, an object / array / tuple prop is validated at its root
693
+ * only (descendants are not walked — their errors would be discarded anyway).
676
694
  */
677
695
  declare function createFieldValidator(prop: TAtscriptAnnotatedType, opts?: TFieldValidatorOptions): (value: unknown, externalCtx?: {
678
696
  data: unknown;
@@ -1448,6 +1466,11 @@ declare function resetDefaultClientFactory(): void;
1448
1466
  * (`ResolvedValueHelp` for value-help, `TableDef` for tables). Both
1449
1467
  * `resolveValueHelp` and `useTable` route through it so a given URL triggers
1450
1468
  * at most one network round-trip and one `deserializeAnnotatedType`.
1469
+ *
1470
+ * `/meta` is projected per viewer, so the cache belongs to one identity
1471
+ * (`setMetaCacheIdentity`) and exists only in the browser: during server
1472
+ * rendering one process serves many viewers, so every call builds a fresh,
1473
+ * uncached entry.
1451
1474
  */
1452
1475
  interface MetaCacheEntry {
1453
1476
  client: Client;
@@ -1459,10 +1482,24 @@ interface MetaCacheEntry {
1459
1482
  /**
1460
1483
  * Get or create the cache entry for `url`. First caller's `factory` seeds the
1461
1484
  * `Client`; subsequent callers reuse it. On `meta` rejection, the entry is
1462
- * evicted so the next call retries.
1485
+ * evicted so the next call retries. Without a browser `window` nothing is
1486
+ * cached.
1463
1487
  */
1464
1488
  declare function getMetaEntry(url: string, factory?: ClientFactory): MetaCacheEntry;
1489
+ /**
1490
+ * Drop every cached `/meta` — including the copy each cached `Client`
1491
+ * memoizes — and the value-help searches shared under them. Entries already
1492
+ * handed out keep working; the next `getMetaEntry` refetches.
1493
+ */
1465
1494
  declare function resetMetaCache(): void;
1495
+ /**
1496
+ * Bind the meta cache to the current viewer. Call it whenever the signed-in
1497
+ * user or their role may have changed — after login, after logout and on
1498
+ * every reload of the current user. A key that differs from the previous
1499
+ * one resets the cache (`resetMetaCache`); the same key keeps it. `null` /
1500
+ * `undefined` = anonymous.
1501
+ */
1502
+ declare function setMetaCacheIdentity(key: string | null | undefined): void;
1466
1503
  //#endregion
1467
1504
  //#region src/shared/str.d.ts
1468
1505
  /** Escape special regex characters in user input for safe embedding in a `$regex` filter. */
@@ -1536,4 +1573,4 @@ interface TModelRoute {
1536
1573
  */
1537
1574
  declare function buildModelRoutes(models: readonly TAtscriptAnnotatedType[]): TModelRoute[];
1538
1575
  //#endregion
1539
- export { type ClientFactory, type CloneUnwrap, type ColumnDef, type ColumnValueKind, type CreateFormDefOptions, type CurrencyDisplay, DB_AMOUNT_CURRENCY, DB_AMOUNT_CURRENCY_REF, DB_COLUMN_PRECISION, DB_HTTP_PATH, DB_REL_FK, DB_UNIT, DB_UNIT_REF, DEFAULT_COL_SPAN, DEFAULT_ROW_SPAN, type DecimalParts, EXPECT_MAX_LENGTH, type FieldMeta, type FieldResolver, type FormActionInfo, type FormArrayFieldDef, type FormDef, type FormDiffOptions, type FormDiffResult, type FormFieldChange, type FormFieldDef, type FormObjectFieldDef, type FormRebaseOptions, type FormRebaseResult, type FormTupleFieldDef, type FormUnionFieldDef, type FormUnionVariant, type FormatDecimalOptions, type GridSpanArgs, type GridSpec, META_DEFAULT, META_DESCRIPTION, META_ID, META_LABEL, META_READONLY, META_REQUIRED, META_SENSITIVE, type MeasurementInfo, type MetaCacheEntry, type MetaResponse, NUMERIC_VALUE_KINDS, type PaginationControl, type RelationInfo, type ResolvedValueHelp, type SearchIndexInfo, type SortControl, StaticFieldResolver, type TCrudOp, type TCrudPermissions, type TDbActionInfo, type TDbActionIntent, type TDbActionLevel, type TDbActionProcessor, type TFieldValidatorOptions, type TFormAction, type TFormEntryOptions, type TFormValidatorCallOptions, type TFormValueResolver, type TModelRoute, type TResolveOptions, type TableActionsModel, type TableDef, type TableQueryState, UI_DICT_ATTR, UI_DICT_DESCR, UI_DICT_FILTERABLE, UI_DICT_LABEL, UI_DICT_SEARCHABLE, UI_DICT_SORTABLE, UI_FORM_ACTION, UI_FORM_ATTR, UI_FORM_AUTOCOMPLETE, UI_FORM_CLASSES, UI_FORM_COMPONENT, UI_FORM_DISABLED, UI_FORM_FN_ATTR, UI_FORM_FN_CLASSES, UI_FORM_FN_DESCRIPTION, UI_FORM_FN_DISABLED, UI_FORM_FN_HIDDEN, UI_FORM_FN_HINT, UI_FORM_FN_LABEL, UI_FORM_FN_OPTIONS, UI_FORM_FN_PLACEHOLDER, UI_FORM_FN_PREFIX, UI_FORM_FN_READONLY, UI_FORM_FN_STYLES, UI_FORM_FN_SUBMIT_DISABLED, UI_FORM_FN_SUBMIT_TEXT, UI_FORM_FN_TITLE, UI_FORM_FN_VALUE, UI_FORM_GRID_COL_SPAN, UI_FORM_GRID_ROW_SPAN, UI_FORM_HIDDEN, UI_FORM_HINT, UI_FORM_LABEL_SINGULAR, UI_FORM_OPTIONS, UI_FORM_ORDER, UI_FORM_PLACEHOLDER, UI_FORM_PREFIX, UI_FORM_PREFIX_ICON, UI_FORM_PREFIX_REF, UI_FORM_STYLES, UI_FORM_SUBMIT_TEXT, UI_FORM_SUFFIX, UI_FORM_SUFFIX_ICON, UI_FORM_SUFFIX_REF, UI_FORM_TYPE, UI_FORM_VALIDATE, UI_NAV_GROUP, UI_NAV_HIDDEN, UI_NAV_ORDER, UI_TABLE_ATTR, UI_TABLE_CLASSES, UI_TABLE_COMPONENT, UI_TABLE_EXCLUDE, UI_TABLE_FN_ATTR, UI_TABLE_FN_CLASSES, UI_TABLE_FN_PREFIX, UI_TABLE_FN_STYLES, UI_TABLE_ORDER, UI_TABLE_SELECT_WITH, UI_TABLE_STYLES, UI_TABLE_TYPE, UI_TABLE_WIDTH, UI_TYPE, ValueHelpClient, type ValueHelpInfo, type ValueHelpResult, type ValueHelpSearchOptions, WF_ACTION_WITH_DATA, applyFormChanges, asArray, buildDescendantErrorCounts, buildFormDiff, buildFormRebase, buildGridClasses, buildModelRoutes, buildUnionVariants, collectDirtyPaths, createFieldValidator, createFormData, createFormDef, createFormValueResolver, createTableDef, deepClone, deepEqual, defaultResolver, deleteByPath, detectUnionVariant, enforceScale, escapeRegex, extractFieldLiteralOptions, extractLiteralOptions, extractMeasurement, extractValueHelp, fetchDistinctValues, formatDecimalForDisplay, getByPath, getColumn, getCurrencyDecimals, getCurrencyDisplayParts, getDecimalSeparator, getDeclaredFormActions, getDefaultClientFactory, getDefaultValidatorPlugins, getFieldMeta, getFilterableColumns, getFormValidator, getMetaEntry, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, isArrayField, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, optKey, optLabel, optionLabel, optionValue, parseColSpan, parseDecimalInput, parseRowSpan, parseStaticAttrs, parseStaticOptions, resetDefaultClientFactory, resetMetaCache, resetValueHelpCache, resolveAttrs, resolveFieldProp, resolveFormProp, resolveGridSpec, resolveOptions, resolveSingularLabel, resolveStatic, resolveValueHelp, setByPath, setDefaultClientFactory, setDefaultValidatorPlugins, setResolver, splitDecimalString, str, unionVariantChanged, valueHelpDictPaths };
1576
+ export { type ClientFactory, type CloneUnwrap, type ColumnDef, type ColumnValueKind, type CreateFormDefOptions, type CurrencyDisplay, DB_AMOUNT_CURRENCY, DB_AMOUNT_CURRENCY_REF, DB_COLUMN_PRECISION, DB_HTTP_PATH, DB_REL_FK, DB_UNIT, DB_UNIT_REF, DEFAULT_COL_SPAN, DEFAULT_ROW_SPAN, type DecimalParts, EXPECT_MAX_LENGTH, type FieldMeta, type FieldResolver, type FormActionInfo, type FormArrayFieldDef, type FormDef, type FormDiffOptions, type FormDiffResult, type FormFieldChange, type FormFieldDef, type FormObjectFieldDef, type FormRebaseOptions, type FormRebaseResult, type FormTupleFieldDef, type FormUnionFieldDef, type FormUnionVariant, type FormatDecimalOptions, type GridSpanArgs, type GridSpec, META_DEFAULT, META_DESCRIPTION, META_ID, META_LABEL, META_READONLY, META_REQUIRED, META_SENSITIVE, type MeasurementInfo, type MetaCacheEntry, type MetaResponse, NUMERIC_VALUE_KINDS, type PaginationControl, type RelationInfo, type ResolvedValueHelp, type SearchIndexInfo, type SortControl, StaticFieldResolver, type TCrudOp, type TCrudPermissions, type TDbActionInfo, type TDbActionIntent, type TDbActionLevel, type TDbActionProcessor, type TFieldValidatorOptions, type TFormAction, type TFormEntryOptions, type TFormValidatorCallOptions, type TFormValueResolver, type TModelRoute, type TResolveOptions, type TableActionsModel, type TableDef, type TableQueryState, UI_DICT_ATTR, UI_DICT_DESCR, UI_DICT_FILTERABLE, UI_DICT_LABEL, UI_DICT_SEARCHABLE, UI_DICT_SORTABLE, UI_FORM_ACTION, UI_FORM_ATTR, UI_FORM_AUTOCOMPLETE, UI_FORM_CLASSES, UI_FORM_COMPONENT, UI_FORM_DISABLED, UI_FORM_FN_ATTR, UI_FORM_FN_CLASSES, UI_FORM_FN_DESCRIPTION, UI_FORM_FN_DISABLED, UI_FORM_FN_HIDDEN, UI_FORM_FN_HINT, UI_FORM_FN_LABEL, UI_FORM_FN_OPTIONS, UI_FORM_FN_PLACEHOLDER, UI_FORM_FN_PREFIX, UI_FORM_FN_READONLY, UI_FORM_FN_STYLES, UI_FORM_FN_SUBMIT_DISABLED, UI_FORM_FN_SUBMIT_TEXT, UI_FORM_FN_TITLE, UI_FORM_FN_VALUE, UI_FORM_GRID_COL_SPAN, UI_FORM_GRID_ROW_SPAN, UI_FORM_HIDDEN, UI_FORM_HINT, UI_FORM_LABEL_SINGULAR, UI_FORM_OPTIONS, UI_FORM_ORDER, UI_FORM_PLACEHOLDER, UI_FORM_PREFIX, UI_FORM_PREFIX_ICON, UI_FORM_PREFIX_REF, UI_FORM_STYLES, UI_FORM_SUBMIT_TEXT, UI_FORM_SUFFIX, UI_FORM_SUFFIX_ICON, UI_FORM_SUFFIX_REF, UI_FORM_TYPE, UI_FORM_VALIDATE, UI_NAV_GROUP, UI_NAV_HIDDEN, UI_NAV_ORDER, UI_TABLE_ATTR, UI_TABLE_CLASSES, UI_TABLE_COMPONENT, UI_TABLE_EXCLUDE, UI_TABLE_FN_ATTR, UI_TABLE_FN_CLASSES, UI_TABLE_FN_PREFIX, UI_TABLE_FN_STYLES, UI_TABLE_ORDER, UI_TABLE_SELECT_WITH, UI_TABLE_STYLES, UI_TABLE_TYPE, UI_TABLE_WIDTH, UI_TYPE, ValueHelpClient, type ValueHelpInfo, type ValueHelpResult, type ValueHelpSearchOptions, WF_ACTION_WITH_DATA, applyFormChanges, asArray, buildDescendantErrorCounts, buildFormDiff, buildFormRebase, buildGridClasses, buildModelRoutes, buildUnionVariants, collectDirtyPaths, createFieldValidator, createFormData, createFormDef, createFormValueResolver, createTableDef, deepClone, deepEqual, defaultResolver, deleteByPath, detectUnionVariant, enforceScale, escapeRegex, extractFieldLiteralOptions, extractLiteralOptions, extractMeasurement, extractValueHelp, fetchDistinctValues, formatDecimalForDisplay, getByPath, getColumn, getCurrencyDecimals, getCurrencyDisplayParts, getDecimalSeparator, getDeclaredFormActions, getDefaultClientFactory, getDefaultValidatorPlugins, getFieldMeta, getFilterableColumns, getFormValidator, getMetaEntry, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, invalidateValueHelpCache, isArrayField, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, optKey, optLabel, optionLabel, optionValue, parseColSpan, parseDecimalInput, parseRowSpan, parseStaticAttrs, parseStaticOptions, resetDefaultClientFactory, resetMetaCache, resetValueHelpCache, resolveAttrs, resolveFieldProp, resolveFormProp, resolveGridSpec, resolveOptions, resolveSingularLabel, resolveStatic, resolveValueHelp, setByPath, setDefaultClientFactory, setDefaultValidatorPlugins, setMetaCacheIdentity, setResolver, setValueHelpCacheTtl, splitDecimalString, str, unionVariantChanged, valueHelpDictPaths };
package/dist/index.d.mts CHANGED
@@ -421,6 +421,19 @@ interface ValueHelpSearchOptions {
421
421
  interface ValueHelpResult {
422
422
  items: Record<string, unknown>[];
423
423
  }
424
+ /**
425
+ * How long (ms) a settled value-help search is reused for an identical
426
+ * search on the same client. Default 5000. `0` shares only searches still in
427
+ * flight; a negative value turns sharing off. Server-side rendering never
428
+ * shares (one process serves many viewers).
429
+ */
430
+ declare function setValueHelpCacheTtl(ms: number): void;
431
+ /**
432
+ * Drop shared value-help search results — for one `client`, or for every
433
+ * client when omitted. Call after writing to a dictionary outside the
434
+ * built-in table actions to make pickers refetch at once.
435
+ */
436
+ declare function invalidateValueHelpCache(client?: Client): void;
424
437
  /**
425
438
  * Value-help query client. Wraps a `Client` from `@atscript/db-client`
426
439
  * with FK-specific search logic (regex fallback for non-searchable tables,
@@ -429,6 +442,9 @@ interface ValueHelpResult {
429
442
  * Consumers resolve the target's metadata once via `resolveValueHelp(url)`
430
443
  * and pass the resulting `ResolvedValueHelp` to `search()`. Label resolution
431
444
  * for cells is deliberately unsupported — cells always display raw ids.
445
+ *
446
+ * Identical searches on the same `Client` are shared (see
447
+ * {@link setValueHelpCacheTtl}).
432
448
  */
433
449
  declare class ValueHelpClient {
434
450
  private readonly _client;
@@ -673,6 +689,8 @@ interface TFieldValidatorOptions {
673
689
  *
674
690
  * The `Validator` instance is created lazily on first call and reused.
675
691
  * Returns `true` when valid, or the first error message string when invalid.
692
+ * With `rootOnly`, an object / array / tuple prop is validated at its root
693
+ * only (descendants are not walked — their errors would be discarded anyway).
676
694
  */
677
695
  declare function createFieldValidator(prop: TAtscriptAnnotatedType, opts?: TFieldValidatorOptions): (value: unknown, externalCtx?: {
678
696
  data: unknown;
@@ -1448,6 +1466,11 @@ declare function resetDefaultClientFactory(): void;
1448
1466
  * (`ResolvedValueHelp` for value-help, `TableDef` for tables). Both
1449
1467
  * `resolveValueHelp` and `useTable` route through it so a given URL triggers
1450
1468
  * at most one network round-trip and one `deserializeAnnotatedType`.
1469
+ *
1470
+ * `/meta` is projected per viewer, so the cache belongs to one identity
1471
+ * (`setMetaCacheIdentity`) and exists only in the browser: during server
1472
+ * rendering one process serves many viewers, so every call builds a fresh,
1473
+ * uncached entry.
1451
1474
  */
1452
1475
  interface MetaCacheEntry {
1453
1476
  client: Client;
@@ -1459,10 +1482,24 @@ interface MetaCacheEntry {
1459
1482
  /**
1460
1483
  * Get or create the cache entry for `url`. First caller's `factory` seeds the
1461
1484
  * `Client`; subsequent callers reuse it. On `meta` rejection, the entry is
1462
- * evicted so the next call retries.
1485
+ * evicted so the next call retries. Without a browser `window` nothing is
1486
+ * cached.
1463
1487
  */
1464
1488
  declare function getMetaEntry(url: string, factory?: ClientFactory): MetaCacheEntry;
1489
+ /**
1490
+ * Drop every cached `/meta` — including the copy each cached `Client`
1491
+ * memoizes — and the value-help searches shared under them. Entries already
1492
+ * handed out keep working; the next `getMetaEntry` refetches.
1493
+ */
1465
1494
  declare function resetMetaCache(): void;
1495
+ /**
1496
+ * Bind the meta cache to the current viewer. Call it whenever the signed-in
1497
+ * user or their role may have changed — after login, after logout and on
1498
+ * every reload of the current user. A key that differs from the previous
1499
+ * one resets the cache (`resetMetaCache`); the same key keeps it. `null` /
1500
+ * `undefined` = anonymous.
1501
+ */
1502
+ declare function setMetaCacheIdentity(key: string | null | undefined): void;
1466
1503
  //#endregion
1467
1504
  //#region src/shared/str.d.ts
1468
1505
  /** Escape special regex characters in user input for safe embedding in a `$regex` filter. */
@@ -1536,4 +1573,4 @@ interface TModelRoute {
1536
1573
  */
1537
1574
  declare function buildModelRoutes(models: readonly TAtscriptAnnotatedType[]): TModelRoute[];
1538
1575
  //#endregion
1539
- export { type ClientFactory, type CloneUnwrap, type ColumnDef, type ColumnValueKind, type CreateFormDefOptions, type CurrencyDisplay, DB_AMOUNT_CURRENCY, DB_AMOUNT_CURRENCY_REF, DB_COLUMN_PRECISION, DB_HTTP_PATH, DB_REL_FK, DB_UNIT, DB_UNIT_REF, DEFAULT_COL_SPAN, DEFAULT_ROW_SPAN, type DecimalParts, EXPECT_MAX_LENGTH, type FieldMeta, type FieldResolver, type FormActionInfo, type FormArrayFieldDef, type FormDef, type FormDiffOptions, type FormDiffResult, type FormFieldChange, type FormFieldDef, type FormObjectFieldDef, type FormRebaseOptions, type FormRebaseResult, type FormTupleFieldDef, type FormUnionFieldDef, type FormUnionVariant, type FormatDecimalOptions, type GridSpanArgs, type GridSpec, META_DEFAULT, META_DESCRIPTION, META_ID, META_LABEL, META_READONLY, META_REQUIRED, META_SENSITIVE, type MeasurementInfo, type MetaCacheEntry, type MetaResponse, NUMERIC_VALUE_KINDS, type PaginationControl, type RelationInfo, type ResolvedValueHelp, type SearchIndexInfo, type SortControl, StaticFieldResolver, type TCrudOp, type TCrudPermissions, type TDbActionInfo, type TDbActionIntent, type TDbActionLevel, type TDbActionProcessor, type TFieldValidatorOptions, type TFormAction, type TFormEntryOptions, type TFormValidatorCallOptions, type TFormValueResolver, type TModelRoute, type TResolveOptions, type TableActionsModel, type TableDef, type TableQueryState, UI_DICT_ATTR, UI_DICT_DESCR, UI_DICT_FILTERABLE, UI_DICT_LABEL, UI_DICT_SEARCHABLE, UI_DICT_SORTABLE, UI_FORM_ACTION, UI_FORM_ATTR, UI_FORM_AUTOCOMPLETE, UI_FORM_CLASSES, UI_FORM_COMPONENT, UI_FORM_DISABLED, UI_FORM_FN_ATTR, UI_FORM_FN_CLASSES, UI_FORM_FN_DESCRIPTION, UI_FORM_FN_DISABLED, UI_FORM_FN_HIDDEN, UI_FORM_FN_HINT, UI_FORM_FN_LABEL, UI_FORM_FN_OPTIONS, UI_FORM_FN_PLACEHOLDER, UI_FORM_FN_PREFIX, UI_FORM_FN_READONLY, UI_FORM_FN_STYLES, UI_FORM_FN_SUBMIT_DISABLED, UI_FORM_FN_SUBMIT_TEXT, UI_FORM_FN_TITLE, UI_FORM_FN_VALUE, UI_FORM_GRID_COL_SPAN, UI_FORM_GRID_ROW_SPAN, UI_FORM_HIDDEN, UI_FORM_HINT, UI_FORM_LABEL_SINGULAR, UI_FORM_OPTIONS, UI_FORM_ORDER, UI_FORM_PLACEHOLDER, UI_FORM_PREFIX, UI_FORM_PREFIX_ICON, UI_FORM_PREFIX_REF, UI_FORM_STYLES, UI_FORM_SUBMIT_TEXT, UI_FORM_SUFFIX, UI_FORM_SUFFIX_ICON, UI_FORM_SUFFIX_REF, UI_FORM_TYPE, UI_FORM_VALIDATE, UI_NAV_GROUP, UI_NAV_HIDDEN, UI_NAV_ORDER, UI_TABLE_ATTR, UI_TABLE_CLASSES, UI_TABLE_COMPONENT, UI_TABLE_EXCLUDE, UI_TABLE_FN_ATTR, UI_TABLE_FN_CLASSES, UI_TABLE_FN_PREFIX, UI_TABLE_FN_STYLES, UI_TABLE_ORDER, UI_TABLE_SELECT_WITH, UI_TABLE_STYLES, UI_TABLE_TYPE, UI_TABLE_WIDTH, UI_TYPE, ValueHelpClient, type ValueHelpInfo, type ValueHelpResult, type ValueHelpSearchOptions, WF_ACTION_WITH_DATA, applyFormChanges, asArray, buildDescendantErrorCounts, buildFormDiff, buildFormRebase, buildGridClasses, buildModelRoutes, buildUnionVariants, collectDirtyPaths, createFieldValidator, createFormData, createFormDef, createFormValueResolver, createTableDef, deepClone, deepEqual, defaultResolver, deleteByPath, detectUnionVariant, enforceScale, escapeRegex, extractFieldLiteralOptions, extractLiteralOptions, extractMeasurement, extractValueHelp, fetchDistinctValues, formatDecimalForDisplay, getByPath, getColumn, getCurrencyDecimals, getCurrencyDisplayParts, getDecimalSeparator, getDeclaredFormActions, getDefaultClientFactory, getDefaultValidatorPlugins, getFieldMeta, getFilterableColumns, getFormValidator, getMetaEntry, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, isArrayField, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, optKey, optLabel, optionLabel, optionValue, parseColSpan, parseDecimalInput, parseRowSpan, parseStaticAttrs, parseStaticOptions, resetDefaultClientFactory, resetMetaCache, resetValueHelpCache, resolveAttrs, resolveFieldProp, resolveFormProp, resolveGridSpec, resolveOptions, resolveSingularLabel, resolveStatic, resolveValueHelp, setByPath, setDefaultClientFactory, setDefaultValidatorPlugins, setResolver, splitDecimalString, str, unionVariantChanged, valueHelpDictPaths };
1576
+ export { type ClientFactory, type CloneUnwrap, type ColumnDef, type ColumnValueKind, type CreateFormDefOptions, type CurrencyDisplay, DB_AMOUNT_CURRENCY, DB_AMOUNT_CURRENCY_REF, DB_COLUMN_PRECISION, DB_HTTP_PATH, DB_REL_FK, DB_UNIT, DB_UNIT_REF, DEFAULT_COL_SPAN, DEFAULT_ROW_SPAN, type DecimalParts, EXPECT_MAX_LENGTH, type FieldMeta, type FieldResolver, type FormActionInfo, type FormArrayFieldDef, type FormDef, type FormDiffOptions, type FormDiffResult, type FormFieldChange, type FormFieldDef, type FormObjectFieldDef, type FormRebaseOptions, type FormRebaseResult, type FormTupleFieldDef, type FormUnionFieldDef, type FormUnionVariant, type FormatDecimalOptions, type GridSpanArgs, type GridSpec, META_DEFAULT, META_DESCRIPTION, META_ID, META_LABEL, META_READONLY, META_REQUIRED, META_SENSITIVE, type MeasurementInfo, type MetaCacheEntry, type MetaResponse, NUMERIC_VALUE_KINDS, type PaginationControl, type RelationInfo, type ResolvedValueHelp, type SearchIndexInfo, type SortControl, StaticFieldResolver, type TCrudOp, type TCrudPermissions, type TDbActionInfo, type TDbActionIntent, type TDbActionLevel, type TDbActionProcessor, type TFieldValidatorOptions, type TFormAction, type TFormEntryOptions, type TFormValidatorCallOptions, type TFormValueResolver, type TModelRoute, type TResolveOptions, type TableActionsModel, type TableDef, type TableQueryState, UI_DICT_ATTR, UI_DICT_DESCR, UI_DICT_FILTERABLE, UI_DICT_LABEL, UI_DICT_SEARCHABLE, UI_DICT_SORTABLE, UI_FORM_ACTION, UI_FORM_ATTR, UI_FORM_AUTOCOMPLETE, UI_FORM_CLASSES, UI_FORM_COMPONENT, UI_FORM_DISABLED, UI_FORM_FN_ATTR, UI_FORM_FN_CLASSES, UI_FORM_FN_DESCRIPTION, UI_FORM_FN_DISABLED, UI_FORM_FN_HIDDEN, UI_FORM_FN_HINT, UI_FORM_FN_LABEL, UI_FORM_FN_OPTIONS, UI_FORM_FN_PLACEHOLDER, UI_FORM_FN_PREFIX, UI_FORM_FN_READONLY, UI_FORM_FN_STYLES, UI_FORM_FN_SUBMIT_DISABLED, UI_FORM_FN_SUBMIT_TEXT, UI_FORM_FN_TITLE, UI_FORM_FN_VALUE, UI_FORM_GRID_COL_SPAN, UI_FORM_GRID_ROW_SPAN, UI_FORM_HIDDEN, UI_FORM_HINT, UI_FORM_LABEL_SINGULAR, UI_FORM_OPTIONS, UI_FORM_ORDER, UI_FORM_PLACEHOLDER, UI_FORM_PREFIX, UI_FORM_PREFIX_ICON, UI_FORM_PREFIX_REF, UI_FORM_STYLES, UI_FORM_SUBMIT_TEXT, UI_FORM_SUFFIX, UI_FORM_SUFFIX_ICON, UI_FORM_SUFFIX_REF, UI_FORM_TYPE, UI_FORM_VALIDATE, UI_NAV_GROUP, UI_NAV_HIDDEN, UI_NAV_ORDER, UI_TABLE_ATTR, UI_TABLE_CLASSES, UI_TABLE_COMPONENT, UI_TABLE_EXCLUDE, UI_TABLE_FN_ATTR, UI_TABLE_FN_CLASSES, UI_TABLE_FN_PREFIX, UI_TABLE_FN_STYLES, UI_TABLE_ORDER, UI_TABLE_SELECT_WITH, UI_TABLE_STYLES, UI_TABLE_TYPE, UI_TABLE_WIDTH, UI_TYPE, ValueHelpClient, type ValueHelpInfo, type ValueHelpResult, type ValueHelpSearchOptions, WF_ACTION_WITH_DATA, applyFormChanges, asArray, buildDescendantErrorCounts, buildFormDiff, buildFormRebase, buildGridClasses, buildModelRoutes, buildUnionVariants, collectDirtyPaths, createFieldValidator, createFormData, createFormDef, createFormValueResolver, createTableDef, deepClone, deepEqual, defaultResolver, deleteByPath, detectUnionVariant, enforceScale, escapeRegex, extractFieldLiteralOptions, extractLiteralOptions, extractMeasurement, extractValueHelp, fetchDistinctValues, formatDecimalForDisplay, getByPath, getColumn, getCurrencyDecimals, getCurrencyDisplayParts, getDecimalSeparator, getDeclaredFormActions, getDefaultClientFactory, getDefaultValidatorPlugins, getFieldMeta, getFilterableColumns, getFormValidator, getMetaEntry, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, invalidateValueHelpCache, isArrayField, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, optKey, optLabel, optionLabel, optionValue, parseColSpan, parseDecimalInput, parseRowSpan, parseStaticAttrs, parseStaticOptions, resetDefaultClientFactory, resetMetaCache, resetValueHelpCache, resolveAttrs, resolveFieldProp, resolveFormProp, resolveGridSpec, resolveOptions, resolveSingularLabel, resolveStatic, resolveValueHelp, setByPath, setDefaultClientFactory, setDefaultValidatorPlugins, setMetaCacheIdentity, setResolver, setValueHelpCacheTtl, splitDecimalString, str, unionVariantChanged, valueHelpDictPaths };
package/dist/index.mjs CHANGED
@@ -833,6 +833,65 @@ function str(value) {
833
833
  }
834
834
  //#endregion
835
835
  //#region src/value-help/value-help-client.ts
836
+ let cacheTtl = 5e3;
837
+ let searches = /* @__PURE__ */ new WeakMap();
838
+ /**
839
+ * How long (ms) a settled value-help search is reused for an identical
840
+ * search on the same client. Default 5000. `0` shares only searches still in
841
+ * flight; a negative value turns sharing off. Server-side rendering never
842
+ * shares (one process serves many viewers).
843
+ */
844
+ function setValueHelpCacheTtl(ms) {
845
+ cacheTtl = ms;
846
+ }
847
+ /**
848
+ * Drop shared value-help search results — for one `client`, or for every
849
+ * client when omitted. Call after writing to a dictionary outside the
850
+ * built-in table actions to make pickers refetch at once.
851
+ */
852
+ function invalidateValueHelpCache(client) {
853
+ if (client) searches.get(client)?.clear();
854
+ else searches = /* @__PURE__ */ new WeakMap();
855
+ }
856
+ function now() {
857
+ return typeof performance === "undefined" ? Date.now() : performance.now();
858
+ }
859
+ /** Cache key of a plain-JSON request; `undefined` when it holds anything else (never shared). */
860
+ function requestKey(request) {
861
+ let plain = true;
862
+ try {
863
+ const key = JSON.stringify(request, (_k, v) => {
864
+ if (typeof v === "function" || typeof v === "symbol") plain = false;
865
+ else if (v !== null && typeof v === "object" && !Array.isArray(v)) {
866
+ const proto = Object.getPrototypeOf(v);
867
+ if (proto !== Object.prototype && proto !== null) plain = false;
868
+ }
869
+ return v;
870
+ });
871
+ return plain ? key : void 0;
872
+ } catch {
873
+ return;
874
+ }
875
+ }
876
+ function sharedQuery(client, request) {
877
+ const run = () => client.query(request);
878
+ if (cacheTtl < 0 || typeof window === "undefined") return run();
879
+ const key = requestKey(request);
880
+ if (key === void 0) return run();
881
+ let byKey = searches.get(client);
882
+ if (!byKey) searches.set(client, byKey = /* @__PURE__ */ new Map());
883
+ const hit = byKey.get(key);
884
+ if (hit && (hit.settledAt === void 0 || now() - hit.settledAt < cacheTtl)) return hit.promise;
885
+ const entry = { promise: run().then((items) => {
886
+ entry.settledAt = now();
887
+ return items;
888
+ }, (err) => {
889
+ if (byKey.get(key) === entry) byKey.delete(key);
890
+ throw err;
891
+ }) };
892
+ byKey.set(key, entry);
893
+ return entry.promise;
894
+ }
836
895
  /**
837
896
  * Value-help query client. Wraps a `Client` from `@atscript/db-client`
838
897
  * with FK-specific search logic (regex fallback for non-searchable tables,
@@ -841,6 +900,9 @@ function str(value) {
841
900
  * Consumers resolve the target's metadata once via `resolveValueHelp(url)`
842
901
  * and pass the resulting `ResolvedValueHelp` to `search()`. Label resolution
843
902
  * for cells is deliberately unsupported — cells always display raw ids.
903
+ *
904
+ * Identical searches on the same `Client` are shared (see
905
+ * {@link setValueHelpCacheTtl}).
844
906
  */
845
907
  var ValueHelpClient = class {
846
908
  _client;
@@ -870,10 +932,11 @@ var ValueHelpClient = class {
870
932
  const search = buildOrFilter(text, selectFields, valueField ?? resolved.primaryKeys[0] ?? resolved.labelField);
871
933
  filter = scope ? { $and: [scope, search] } : search;
872
934
  }
873
- return { items: await this._client.query({
935
+ const items = await sharedQuery(this._client, {
874
936
  ...filter && { filter },
875
937
  controls
876
- }) };
938
+ });
939
+ return { items: Array.isArray(items) ? items.slice() : items };
877
940
  }
878
941
  };
879
942
  /**
@@ -971,17 +1034,21 @@ function resetDefaultClientFactory() {
971
1034
  //#endregion
972
1035
  //#region src/shared/meta-cache.ts
973
1036
  const cache = /* @__PURE__ */ new Map();
1037
+ /** `undefined` until the first `setMetaCacheIdentity` call; `null` = anonymous. */
1038
+ let identity;
974
1039
  /**
975
1040
  * Get or create the cache entry for `url`. First caller's `factory` seeds the
976
1041
  * `Client`; subsequent callers reuse it. On `meta` rejection, the entry is
977
- * evicted so the next call retries.
1042
+ * evicted so the next call retries. Without a browser `window` nothing is
1043
+ * cached.
978
1044
  */
979
1045
  function getMetaEntry(url, factory) {
980
- const existing = cache.get(url);
1046
+ const browser = typeof window !== "undefined";
1047
+ const existing = browser ? cache.get(url) : void 0;
981
1048
  if (existing) return existing;
982
1049
  const client = (factory ?? getDefaultClientFactory())(url);
983
1050
  const meta = client.meta().catch((err) => {
984
- cache.delete(url);
1051
+ if (cache.get(url) === entry) cache.delete(url);
985
1052
  throw err;
986
1053
  });
987
1054
  const entry = {
@@ -989,11 +1056,32 @@ function getMetaEntry(url, factory) {
989
1056
  meta,
990
1057
  type: meta.then((m) => deserializeAnnotatedType(m.type))
991
1058
  };
992
- cache.set(url, entry);
1059
+ if (browser) cache.set(url, entry);
993
1060
  return entry;
994
1061
  }
1062
+ /**
1063
+ * Drop every cached `/meta` — including the copy each cached `Client`
1064
+ * memoizes — and the value-help searches shared under them. Entries already
1065
+ * handed out keep working; the next `getMetaEntry` refetches.
1066
+ */
995
1067
  function resetMetaCache() {
1068
+ const entries = [...cache.values()];
996
1069
  cache.clear();
1070
+ for (const entry of entries) entry.client.invalidateMeta?.();
1071
+ invalidateValueHelpCache();
1072
+ }
1073
+ /**
1074
+ * Bind the meta cache to the current viewer. Call it whenever the signed-in
1075
+ * user or their role may have changed — after login, after logout and on
1076
+ * every reload of the current user. A key that differs from the previous
1077
+ * one resets the cache (`resetMetaCache`); the same key keeps it. `null` /
1078
+ * `undefined` = anonymous.
1079
+ */
1080
+ function setMetaCacheIdentity(key) {
1081
+ const next = key ?? null;
1082
+ if (next === identity) return;
1083
+ identity = next;
1084
+ resetMetaCache();
997
1085
  }
998
1086
  //#endregion
999
1087
  //#region src/value-help/resolve.ts
@@ -1304,15 +1392,34 @@ function getFormValidator(def, opts) {
1304
1392
  };
1305
1393
  }
1306
1394
  /**
1395
+ * Root-only plugin: passes every descendant without visiting it. Only
1396
+ * `object` / `array` / `tuple` roots use it — their root-path errors (shape,
1397
+ * length, a container-level `@ui.form.validate`) are all decided before the
1398
+ * walk descends, so skipping the children cannot change the root error. A
1399
+ * union or intersection root evaluates its branches AT the root path, where
1400
+ * a branch's verdict depends on its children — those keep the full walk.
1401
+ */
1402
+ const skipDescendantsPlugin = (ctx) => ctx.path === "" ? void 0 : true;
1403
+ function skipsDescendants(prop) {
1404
+ const kind = prop.type.kind;
1405
+ return kind === "object" || kind === "array" || kind === "tuple";
1406
+ }
1407
+ /**
1307
1408
  * Creates a cached validator function for a single ATScript prop.
1308
1409
  *
1309
1410
  * The `Validator` instance is created lazily on first call and reused.
1310
1411
  * Returns `true` when valid, or the first error message string when invalid.
1412
+ * With `rootOnly`, an object / array / tuple prop is validated at its root
1413
+ * only (descendants are not walked — their errors would be discarded anyway).
1311
1414
  */
1312
1415
  function createFieldValidator(prop, opts) {
1313
1416
  let cached;
1314
1417
  return (value, externalCtx) => {
1315
- cached ??= new Validator(prop, { plugins: [serverManagedPlugin, ...defaultValidatorPlugins] });
1418
+ cached ??= new Validator(prop, { plugins: opts?.rootOnly && skipsDescendants(prop) ? [
1419
+ skipDescendantsPlugin,
1420
+ serverManagedPlugin,
1421
+ ...defaultValidatorPlugins
1422
+ ] : [serverManagedPlugin, ...defaultValidatorPlugins] });
1316
1423
  if (!cached.validate(value, true, externalCtx)) {
1317
1424
  if (opts?.rootOnly) {
1318
1425
  const rootError = cached.errors?.find((e) => e.path === "");
@@ -1554,20 +1661,10 @@ function diffKeyedArray(before, after, keyProps) {
1554
1661
  const afterByKey = /* @__PURE__ */ new Map();
1555
1662
  for (const el of after) if (isPlainObject(el)) afterByKey.set(keyOf(el, keyProps), el);
1556
1663
  if (beforeByKey.size !== before.length || afterByKey.size !== after.length) return { $replace: after };
1557
- if (beforeByKey.size === afterByKey.size) {
1558
- let sameMembershipAndContent = true;
1559
- for (const [k, el] of afterByKey) {
1560
- const prev = beforeByKey.get(k);
1561
- if (prev === void 0 || !deepEqual(prev, el)) {
1562
- sameMembershipAndContent = false;
1563
- break;
1564
- }
1565
- }
1566
- if (sameMembershipAndContent) return { $replace: after };
1567
- }
1568
1664
  const $insert = [];
1569
1665
  const $update = [];
1570
1666
  const $remove = [];
1667
+ let contentChanged = false;
1571
1668
  for (const [k, el] of afterByKey) {
1572
1669
  const prev = beforeByKey.get(k);
1573
1670
  if (prev === void 0) {
@@ -1575,10 +1672,12 @@ function diffKeyedArray(before, after, keyProps) {
1575
1672
  continue;
1576
1673
  }
1577
1674
  if (!deepEqual(prev, el)) {
1675
+ contentChanged = true;
1578
1676
  const partial = buildKeyedUpdate(prev, el, keyProps);
1579
1677
  if (partial) $update.push(partial);
1580
1678
  }
1581
1679
  }
1680
+ if (beforeByKey.size === afterByKey.size && $insert.length === 0 && !contentChanged) return { $replace: after };
1582
1681
  for (const [k, el] of beforeByKey) if (!afterByKey.has(k)) $remove.push(pickKeys(el, keyProps));
1583
1682
  return arrayOps({
1584
1683
  $update,
@@ -2813,4 +2912,4 @@ function resolvePath(model, table, view) {
2813
2912
  return path.length > 0 ? path : void 0;
2814
2913
  }
2815
2914
  //#endregion
2816
- export { DB_AMOUNT_CURRENCY, DB_AMOUNT_CURRENCY_REF, DB_COLUMN_PRECISION, DB_HTTP_PATH, DB_REL_FK, DB_UNIT, DB_UNIT_REF, DEFAULT_COL_SPAN, DEFAULT_ROW_SPAN, EXPECT_MAX_LENGTH, META_DEFAULT, META_DESCRIPTION, META_ID, META_LABEL, META_READONLY, META_REQUIRED, META_SENSITIVE, NUMERIC_VALUE_KINDS, StaticFieldResolver, UI_DICT_ATTR, UI_DICT_DESCR, UI_DICT_FILTERABLE, UI_DICT_LABEL, UI_DICT_SEARCHABLE, UI_DICT_SORTABLE, UI_FORM_ACTION, UI_FORM_ATTR, UI_FORM_AUTOCOMPLETE, UI_FORM_CLASSES, UI_FORM_COMPONENT, UI_FORM_DISABLED, UI_FORM_FN_ATTR, UI_FORM_FN_CLASSES, UI_FORM_FN_DESCRIPTION, UI_FORM_FN_DISABLED, UI_FORM_FN_HIDDEN, UI_FORM_FN_HINT, UI_FORM_FN_LABEL, UI_FORM_FN_OPTIONS, UI_FORM_FN_PLACEHOLDER, UI_FORM_FN_PREFIX, UI_FORM_FN_READONLY, UI_FORM_FN_STYLES, UI_FORM_FN_SUBMIT_DISABLED, UI_FORM_FN_SUBMIT_TEXT, UI_FORM_FN_TITLE, UI_FORM_FN_VALUE, UI_FORM_GRID_COL_SPAN, UI_FORM_GRID_ROW_SPAN, UI_FORM_HIDDEN, UI_FORM_HINT, UI_FORM_LABEL_SINGULAR, UI_FORM_OPTIONS, UI_FORM_ORDER, UI_FORM_PLACEHOLDER, UI_FORM_PREFIX, UI_FORM_PREFIX_ICON, UI_FORM_PREFIX_REF, UI_FORM_STYLES, UI_FORM_SUBMIT_TEXT, UI_FORM_SUFFIX, UI_FORM_SUFFIX_ICON, UI_FORM_SUFFIX_REF, UI_FORM_TYPE, UI_FORM_VALIDATE, UI_NAV_GROUP, UI_NAV_HIDDEN, UI_NAV_ORDER, UI_TABLE_ATTR, UI_TABLE_CLASSES, UI_TABLE_COMPONENT, UI_TABLE_EXCLUDE, UI_TABLE_FN_ATTR, UI_TABLE_FN_CLASSES, UI_TABLE_FN_PREFIX, UI_TABLE_FN_STYLES, UI_TABLE_ORDER, UI_TABLE_SELECT_WITH, UI_TABLE_STYLES, UI_TABLE_TYPE, UI_TABLE_WIDTH, UI_TYPE, ValueHelpClient, WF_ACTION_WITH_DATA, applyFormChanges, asArray, buildDescendantErrorCounts, buildFormDiff, buildFormRebase, buildGridClasses, buildModelRoutes, buildUnionVariants, collectDirtyPaths, createFieldValidator, createFormData, createFormDef, createFormValueResolver, createTableDef, deepClone, deepEqual, defaultResolver, deleteByPath, detectUnionVariant, enforceScale, escapeRegex, extractFieldLiteralOptions, extractLiteralOptions, extractMeasurement, extractValueHelp, fetchDistinctValues, formatDecimalForDisplay, getByPath, getColumn, getCurrencyDecimals, getCurrencyDisplayParts, getDecimalSeparator, getDeclaredFormActions, getDefaultClientFactory, getDefaultValidatorPlugins, getFieldMeta, getFilterableColumns, getFormValidator, getMetaEntry, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, isArrayField, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, optKey, optLabel, optionLabel, optionValue, parseColSpan, parseDecimalInput, parseRowSpan, parseStaticAttrs, parseStaticOptions, resetDefaultClientFactory, resetMetaCache, resetValueHelpCache, resolveAttrs, resolveFieldProp, resolveFormProp, resolveGridSpec, resolveOptions, resolveSingularLabel, resolveStatic, resolveValueHelp, setByPath, setDefaultClientFactory, setDefaultValidatorPlugins, setResolver, splitDecimalString, str, unionVariantChanged, valueHelpDictPaths };
2915
+ export { DB_AMOUNT_CURRENCY, DB_AMOUNT_CURRENCY_REF, DB_COLUMN_PRECISION, DB_HTTP_PATH, DB_REL_FK, DB_UNIT, DB_UNIT_REF, DEFAULT_COL_SPAN, DEFAULT_ROW_SPAN, EXPECT_MAX_LENGTH, META_DEFAULT, META_DESCRIPTION, META_ID, META_LABEL, META_READONLY, META_REQUIRED, META_SENSITIVE, NUMERIC_VALUE_KINDS, StaticFieldResolver, UI_DICT_ATTR, UI_DICT_DESCR, UI_DICT_FILTERABLE, UI_DICT_LABEL, UI_DICT_SEARCHABLE, UI_DICT_SORTABLE, UI_FORM_ACTION, UI_FORM_ATTR, UI_FORM_AUTOCOMPLETE, UI_FORM_CLASSES, UI_FORM_COMPONENT, UI_FORM_DISABLED, UI_FORM_FN_ATTR, UI_FORM_FN_CLASSES, UI_FORM_FN_DESCRIPTION, UI_FORM_FN_DISABLED, UI_FORM_FN_HIDDEN, UI_FORM_FN_HINT, UI_FORM_FN_LABEL, UI_FORM_FN_OPTIONS, UI_FORM_FN_PLACEHOLDER, UI_FORM_FN_PREFIX, UI_FORM_FN_READONLY, UI_FORM_FN_STYLES, UI_FORM_FN_SUBMIT_DISABLED, UI_FORM_FN_SUBMIT_TEXT, UI_FORM_FN_TITLE, UI_FORM_FN_VALUE, UI_FORM_GRID_COL_SPAN, UI_FORM_GRID_ROW_SPAN, UI_FORM_HIDDEN, UI_FORM_HINT, UI_FORM_LABEL_SINGULAR, UI_FORM_OPTIONS, UI_FORM_ORDER, UI_FORM_PLACEHOLDER, UI_FORM_PREFIX, UI_FORM_PREFIX_ICON, UI_FORM_PREFIX_REF, UI_FORM_STYLES, UI_FORM_SUBMIT_TEXT, UI_FORM_SUFFIX, UI_FORM_SUFFIX_ICON, UI_FORM_SUFFIX_REF, UI_FORM_TYPE, UI_FORM_VALIDATE, UI_NAV_GROUP, UI_NAV_HIDDEN, UI_NAV_ORDER, UI_TABLE_ATTR, UI_TABLE_CLASSES, UI_TABLE_COMPONENT, UI_TABLE_EXCLUDE, UI_TABLE_FN_ATTR, UI_TABLE_FN_CLASSES, UI_TABLE_FN_PREFIX, UI_TABLE_FN_STYLES, UI_TABLE_ORDER, UI_TABLE_SELECT_WITH, UI_TABLE_STYLES, UI_TABLE_TYPE, UI_TABLE_WIDTH, UI_TYPE, ValueHelpClient, WF_ACTION_WITH_DATA, applyFormChanges, asArray, buildDescendantErrorCounts, buildFormDiff, buildFormRebase, buildGridClasses, buildModelRoutes, buildUnionVariants, collectDirtyPaths, createFieldValidator, createFormData, createFormDef, createFormValueResolver, createTableDef, deepClone, deepEqual, defaultResolver, deleteByPath, detectUnionVariant, enforceScale, escapeRegex, extractFieldLiteralOptions, extractLiteralOptions, extractMeasurement, extractValueHelp, fetchDistinctValues, formatDecimalForDisplay, getByPath, getColumn, getCurrencyDecimals, getCurrencyDisplayParts, getDecimalSeparator, getDeclaredFormActions, getDefaultClientFactory, getDefaultValidatorPlugins, getFieldMeta, getFilterableColumns, getFormValidator, getMetaEntry, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, invalidateValueHelpCache, isArrayField, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, optKey, optLabel, optionLabel, optionValue, parseColSpan, parseDecimalInput, parseRowSpan, parseStaticAttrs, parseStaticOptions, resetDefaultClientFactory, resetMetaCache, resetValueHelpCache, resolveAttrs, resolveFieldProp, resolveFormProp, resolveGridSpec, resolveOptions, resolveSingularLabel, resolveStatic, resolveValueHelp, setByPath, setDefaultClientFactory, setDefaultValidatorPlugins, setMetaCacheIdentity, setResolver, setValueHelpCacheTtl, splitDecimalString, str, unionVariantChanged, valueHelpDictPaths };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/ui",
3
- "version": "0.1.150",
3
+ "version": "0.1.151",
4
4
  "description": "Framework-agnostic runtime for form and table definitions from atscript annotated types",
5
5
  "keywords": [
6
6
  "annotations",
@@ -47,20 +47,20 @@
47
47
  "access": "public"
48
48
  },
49
49
  "dependencies": {
50
- "@atscript/db-client": "^0.1.150"
50
+ "@atscript/db-client": "^0.1.151"
51
51
  },
52
52
  "devDependencies": {
53
- "@atscript/core": "^0.1.101",
54
- "@atscript/db": "^0.1.150",
55
- "@atscript/typescript": "^0.1.101",
56
- "@uniqu/core": "^0.1.13",
57
- "unplugin-atscript": "^0.1.101",
53
+ "@atscript/core": "^0.1.102",
54
+ "@atscript/db": "^0.1.151",
55
+ "@atscript/typescript": "^0.1.102",
56
+ "@uniqu/core": "^0.1.14",
57
+ "unplugin-atscript": "^0.1.102",
58
58
  "vitest": "npm:@voidzero-dev/vite-plus-test@0.1.14"
59
59
  },
60
60
  "peerDependencies": {
61
- "@atscript/core": "^0.1.101",
62
- "@atscript/db": "^0.1.150",
63
- "@atscript/typescript": "^0.1.101"
61
+ "@atscript/core": "^0.1.102",
62
+ "@atscript/db": "^0.1.151",
63
+ "@atscript/typescript": "^0.1.102"
64
64
  },
65
65
  "scripts": {
66
66
  "build": "vp pack",