@atscript/ui 0.1.153 → 0.1.155

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
@@ -435,6 +435,7 @@ const UI_TAGS = new Set([
435
435
  "radio",
436
436
  "checkbox"
437
437
  ]);
438
+ const EDIT = { mode: "edit" };
438
439
  /**
439
440
  * Converts an ATScript annotated type into a FormDef.
440
441
  *
@@ -443,11 +444,13 @@ const UI_TAGS = new Set([
443
444
  * with `path: ''`.
444
445
  *
445
446
  * A `@db.column.derived` field is marked `derived` straight from its metadata;
446
- * a computed view column, from `opts.metaFields`.
447
+ * a computed view column, from `opts.metaFields`; an `@db.onUpdate.now` field,
448
+ * when `opts.mode` is `"edit"`.
447
449
  */
448
450
  function createFormDef(type, opts) {
451
+ const edit = opts?.mode === "edit";
449
452
  if (type.type.kind !== "object") {
450
- const rootField = createFieldDef("", type);
453
+ const rootField = createFieldDef("", type, edit);
451
454
  const fields = [rootField];
452
455
  return {
453
456
  type,
@@ -473,7 +476,7 @@ function createFormDef(type, opts) {
473
476
  if (originalProp.type.of.type.kind === "array" && !getFieldMeta(originalProp, "ui.form.component")) continue;
474
477
  }
475
478
  if (kind === "array" || kind === "object" || kind === "union" || kind === "tuple") structuredPrefixes.add(path + ".");
476
- const field = createFieldDef(path, originalProp);
479
+ const field = createFieldDef(path, originalProp, edit);
477
480
  if (opts?.metaFields?.[path]?.computed) field.derived = true;
478
481
  fields.push(field);
479
482
  }
@@ -505,14 +508,18 @@ function createFormDef(type, opts) {
505
508
  rootField.objectDef = def;
506
509
  return def;
507
510
  }
508
- /** Creates a FormFieldDef from any ATScript annotated type. */
509
- function createFieldDef(path, prop) {
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) {
510
516
  const kind = prop.type.kind;
511
517
  const name = path.slice(path.lastIndexOf(".") + 1);
512
518
  const allStatic = !hasComputedAnnotations(prop);
513
519
  const uiType = getFieldMeta(prop, "ui.form.type") ?? getFieldMeta(prop, "ui.type");
514
520
  const pushDown = getFieldMeta(prop, UI_FORM_PUSH_DOWN) !== void 0;
515
521
  const valueHelpInfo = extractValueHelp(prop);
522
+ const derived = getFieldMeta(prop, "db.column.derived") !== void 0 || edit && path !== "" && isUpdateStamped(prop);
516
523
  const base = {
517
524
  path,
518
525
  prop,
@@ -521,7 +528,7 @@ function createFieldDef(path, prop) {
521
528
  allStatic,
522
529
  pushDown,
523
530
  valueHelpInfo,
524
- ...getFieldMeta(prop, "db.column.derived") !== void 0 && { derived: true }
531
+ ...derived && { derived: true }
525
532
  };
526
533
  const customType = uiType;
527
534
  if (kind === "array") {
@@ -532,21 +539,21 @@ function createFieldDef(path, prop) {
532
539
  type: "array",
533
540
  customType: isMultiselect ? "multiselect" : customType,
534
541
  itemType: arrayType.of,
535
- itemField: createFieldDef("", arrayType.of)
542
+ itemField: createFieldDef("", arrayType.of, edit)
536
543
  };
537
544
  }
538
545
  if (kind === "object") return {
539
546
  ...base,
540
547
  type: "object",
541
548
  customType,
542
- objectDef: createFormDef(prop)
549
+ objectDef: createFormDef(prop, edit ? EDIT : void 0)
543
550
  };
544
551
  if (kind === "union") {
545
552
  if (isPureLiteralUnion(prop)) return {
546
553
  ...base,
547
554
  type: uiType ?? "select"
548
555
  };
549
- const unionVariants = buildUnionVariants(prop);
556
+ const unionVariants = createUnionVariants(prop, edit && soleValueMember(prop) !== void 0);
550
557
  if (unionVariants.length > 1) return {
551
558
  ...base,
552
559
  type: "union",
@@ -559,7 +566,8 @@ function createFieldDef(path, prop) {
559
566
  path,
560
567
  name,
561
568
  allStatic,
562
- pushDown
569
+ pushDown,
570
+ ...derived && { derived: true }
563
571
  };
564
572
  if (v?.def) return {
565
573
  ...base,
@@ -677,17 +685,20 @@ function isChildOfStructured(path, prefixes) {
677
685
  * Iterates top-level items directly — one variant per item.
678
686
  */
679
687
  function buildUnionVariants(typeDef) {
688
+ return createUnionVariants(typeDef, false);
689
+ }
690
+ function createUnionVariants(typeDef, edit) {
680
691
  const items = typeDef.type.items ?? [typeDef];
681
692
  const variants = [];
682
693
  for (const item of items) {
683
- const v = createVariant(item);
694
+ const v = createVariant(item, edit);
684
695
  if (items.length > 1) v.label = `${String(variants.length + 1)}. ${v.label}`;
685
696
  variants.push(v);
686
697
  }
687
698
  return variants;
688
699
  }
689
700
  /** Creates a single union variant from an annotated type item. */
690
- function createVariant(def) {
701
+ function createVariant(def, edit) {
691
702
  const kind = def.type.kind;
692
703
  if (kind === "object") {
693
704
  const label = getFieldMeta(def, "meta.label") ?? "Object";
@@ -695,8 +706,8 @@ function createVariant(def) {
695
706
  return {
696
707
  label,
697
708
  type: def,
698
- def: createFormDef(def),
699
- itemField: hasComponent ? createFieldDef("", def) : void 0
709
+ def: createFormDef(def, edit ? EDIT : void 0),
710
+ itemField: hasComponent ? createFieldDef("", def, edit) : void 0
700
711
  };
701
712
  }
702
713
  if (kind === "") {
@@ -704,15 +715,36 @@ function createVariant(def) {
704
715
  return {
705
716
  label: capitalize(dt === "phantom" ? "item" : dt),
706
717
  type: def,
707
- itemField: createFieldDef("", def),
718
+ itemField: createFieldDef("", def, edit),
708
719
  designType: dt
709
720
  };
710
721
  }
711
722
  return {
712
723
  label: capitalize(kind),
713
724
  type: def,
714
- itemField: createFieldDef("", def)
725
+ itemField: createFieldDef("", def, edit)
726
+ };
727
+ }
728
+ /**
729
+ * `@db.onUpdate.now` (`number.timestamp.updated`): the server sets the field
730
+ * on every update. Read off the prop, or — as `@atscript/db` does — off the one
731
+ * value member of `T | null`, unless the prop references another field.
732
+ */
733
+ function isUpdateStamped(prop) {
734
+ if (hasFieldMeta(prop, "db.onUpdate.now")) return true;
735
+ const member = prop.ref?.field ? void 0 : soleValueMember(prop);
736
+ return member !== void 0 && hasFieldMeta(member, "db.onUpdate.now");
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);
715
745
  };
746
+ visit(prop);
747
+ return members.size === 1 ? members.values().next().value : void 0;
716
748
  }
717
749
  function capitalize(s) {
718
750
  return s.charAt(0).toUpperCase() + s.slice(1);
@@ -1276,39 +1308,50 @@ function inferValueKind(prop) {
1276
1308
  }
1277
1309
  //#endregion
1278
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. */
1279
1321
  const cache = /* @__PURE__ */ new Map();
1280
- /** Derived shapes per `ETag`, least recently used first. Browser only. */
1322
+ const slots = /* @__PURE__ */ new WeakMap();
1323
+ /** Derived shapes per `ETag`, counted by the cached entries that use them. Browser only. */
1281
1324
  const derivedByEtag = /* @__PURE__ */ new Map();
1282
- const MAX_DERIVED = 50;
1283
- /** The `Derived` promise behind each handed-out entry (kept off the public shape). */
1284
- const derivedOf = /* @__PURE__ */ new WeakMap();
1285
- /** Custom `/meta` stores of clients this cache created in the browser. */
1286
- const customStores = /* @__PURE__ */ new Set();
1325
+ /** Custom `/meta` stores of cached clients, counted by the entries that use them. */
1326
+ const customStores = /* @__PURE__ */ new Map();
1287
1327
  /** `undefined` until the first `setMetaCacheIdentity` call; `null` = anonymous. */
1288
1328
  let identity;
1289
1329
  const resetListeners = /* @__PURE__ */ new Set();
1290
1330
  /**
1291
1331
  * Get or create the cache entry for `url`. First caller's `factory` (and
1292
1332
  * `options.metaKey`) seeds the `Client`; subsequent callers reuse it. On
1293
- * `meta` rejection, the entry is evicted so the next call retries. Without a
1294
- * browser `window` nothing is cached and the client is asked for
1295
- * `metaStore: false`.
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`.
1296
1337
  */
1297
1338
  function getMetaEntry(url, factory, options) {
1298
1339
  const browser = typeof window !== "undefined";
1299
1340
  const existing = browser ? cache.get(url) : void 0;
1300
- if (existing) return existing;
1341
+ if (existing) {
1342
+ touch(url, existing);
1343
+ return existing;
1344
+ }
1301
1345
  const f = factory ?? getDefaultClientFactory();
1302
1346
  let client;
1303
1347
  if (!browser) client = f(url, { metaStore: false });
1304
1348
  else if (options?.metaKey) client = f(url, { metaKey: options.metaKey });
1305
1349
  else client = f(url);
1306
- if (browser) rememberStore(client);
1307
1350
  const meta = client.meta().catch((err) => {
1308
- if (cache.get(url) === entry) cache.delete(url);
1351
+ if (cache.get(url) === entry) evict(url, entry);
1309
1352
  throw err;
1310
1353
  });
1311
- const derived = meta.then((m) => derive(client, m, browser));
1354
+ const derived = meta.then((m) => derive(entry, client, m));
1312
1355
  const type = derived.then((d) => d.type);
1313
1356
  type.catch(() => {});
1314
1357
  const entry = {
@@ -1316,44 +1359,130 @@ function getMetaEntry(url, factory, options) {
1316
1359
  meta,
1317
1360
  type
1318
1361
  };
1319
- derivedOf.set(entry, derived);
1320
- if (browser) cache.set(url, entry);
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
+ }
1321
1374
  return entry;
1322
1375
  }
1323
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
+ /**
1324
1446
  * The `TableDef` for a cache entry, built once per entry — and once per
1325
1447
  * `/meta` `ETag` across entries. Since 0.1.153.
1326
1448
  */
1327
1449
  function getMetaTableDef(entry) {
1328
1450
  if (!entry.tableDef) {
1329
- const derived = derivedOf.get(entry);
1451
+ const derived = slots.get(entry)?.derived;
1330
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));
1331
1453
  }
1332
1454
  return entry.tableDef;
1333
1455
  }
1334
- function derive(client, meta, browser) {
1335
- const etag = browser ? client.metaEtag?.() : void 0;
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;
1336
1463
  if (etag === void 0) return { type: (0, _atscript_typescript_utils.deserializeAnnotatedType)(meta.type) };
1337
- const hit = derivedByEtag.get(etag);
1338
- if (hit) {
1339
- derivedByEtag.delete(etag);
1340
- derivedByEtag.set(etag, hit);
1341
- return hit;
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);
1342
1472
  }
1343
- const fresh = { type: (0, _atscript_typescript_utils.deserializeAnnotatedType)(meta.type) };
1344
- derivedByEtag.set(etag, fresh);
1345
- if (derivedByEtag.size > MAX_DERIVED) derivedByEtag.delete(derivedByEtag.keys().next().value);
1346
- return fresh;
1473
+ slot.etag = etag;
1474
+ return shared.derived;
1347
1475
  }
1348
1476
  /**
1349
- * Remember a custom `/meta` store a factory gave `client`, so a reset can
1350
- * clear it. The store is a private field of `Client`, read defensively: the
1351
- * default store is cleared through `clearMetaStore()`, and a store-less
1352
- * client or a test double is skipped.
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.
1353
1482
  */
1354
- function rememberStore(client) {
1355
- const store = client._metaStore;
1356
- if (typeof store?.clear === "function") customStores.add(store);
1483
+ function customStoreOf(client) {
1484
+ const store = client.metaStore;
1485
+ return store && store !== _atscript_db_client.defaultMetaStore ? store : void 0;
1357
1486
  }
1358
1487
  /**
1359
1488
  * Drop every cached `/meta` — including the copy each cached `Client`
@@ -1369,7 +1498,7 @@ function resetMetaCache() {
1369
1498
  derivedByEtag.clear();
1370
1499
  for (const entry of entries) entry.client.invalidateMeta?.();
1371
1500
  (0, _atscript_db_client.clearMetaStore)();
1372
- for (const store of customStores) store.clear();
1501
+ for (const store of customStores.keys()) store.clear();
1373
1502
  customStores.clear();
1374
1503
  invalidateValueHelpCache();
1375
1504
  for (const listener of resetListeners) listener();
@@ -1679,6 +1808,36 @@ const serverManagedPlugin = (ctx, def, value) => {
1679
1808
  if (value !== void 0 || def.metadata.has("db.rel.FK")) return void 0;
1680
1809
  return dbPlugin(Object.create(ctx, { context: { value: INSERT_CONTEXT } }), def, value);
1681
1810
  };
1811
+ /**
1812
+ * The props of the fields `createFormDef` marked `derived`, at any depth — a
1813
+ * computed view column (`metaFields`) or an edit form's `@db.onUpdate.now`
1814
+ * field carries no annotation the plugin above could read. The validator
1815
+ * matches by prop, so a prop that is also used where it is not derived (an
1816
+ * interface's stamp below a union of several types, too) stays validated.
1817
+ */
1818
+ function collectDerivedProps(def) {
1819
+ const derived = /* @__PURE__ */ new Set();
1820
+ const kept = /* @__PURE__ */ new Set();
1821
+ const walk = (fields) => {
1822
+ for (const field of fields) {
1823
+ if (field.derived) {
1824
+ derived.add(field.prop);
1825
+ continue;
1826
+ }
1827
+ kept.add(field.prop);
1828
+ if (isObjectField(field)) walk(field.objectDef.fields);
1829
+ else if (isArrayField(field)) walk([field.itemField]);
1830
+ else if (isTupleField(field)) walk(field.itemFields);
1831
+ else if (isUnionField(field)) for (const v of field.unionVariants) {
1832
+ if (v.def) walk(v.def.fields);
1833
+ if (v.itemField) walk([v.itemField]);
1834
+ }
1835
+ }
1836
+ };
1837
+ walk(def.fields);
1838
+ for (const prop of kept) derived.delete(prop);
1839
+ return derived;
1840
+ }
1682
1841
  let defaultValidatorPlugins = [];
1683
1842
  /** Replace the default validator plugins applied to every form/field validator. */
1684
1843
  function setDefaultValidatorPlugins(plugins) {
@@ -1693,14 +1852,17 @@ function getDefaultValidatorPlugins() {
1693
1852
  *
1694
1853
  * Validator is created once and reused on every call.
1695
1854
  * ATScript's @expect.* validation runs automatically; server-managed db
1696
- * fields (`@db.column.derived`, absent `@db.default*` / version) pass.
1855
+ * fields (every `derived` field, absent `@db.default*` / version) pass.
1697
1856
  * For custom `ui.fn.*` validators, install ui-fns and pass its plugin via `opts.plugins`.
1698
1857
  */
1699
1858
  function getFormValidator(def, opts) {
1859
+ const derived = collectDerivedProps(def);
1860
+ const derivedPlugin = (_ctx, prop) => derived.has(prop) ? true : void 0;
1700
1861
  const validator = new _atscript_typescript_utils.Validator(def.type, {
1701
1862
  unknownProps: "ignore",
1702
1863
  ...opts,
1703
1864
  plugins: [
1865
+ ...derived.size > 0 ? [derivedPlugin] : [],
1704
1866
  serverManagedPlugin,
1705
1867
  ...defaultValidatorPlugins,
1706
1868
  ...opts?.plugins ?? []
@@ -3162,10 +3324,12 @@ exports.resolveOptions = resolveOptions;
3162
3324
  exports.resolveSingularLabel = resolveSingularLabel;
3163
3325
  exports.resolveStatic = resolveStatic;
3164
3326
  exports.resolveValueHelp = resolveValueHelp;
3327
+ exports.retainMetaEntry = retainMetaEntry;
3165
3328
  exports.setByPath = setByPath;
3166
3329
  exports.setDefaultClientFactory = setDefaultClientFactory;
3167
3330
  exports.setDefaultValidatorPlugins = setDefaultValidatorPlugins;
3168
3331
  exports.setMetaCacheIdentity = setMetaCacheIdentity;
3332
+ exports.setMetaCacheMaxEntries = setMetaCacheMaxEntries;
3169
3333
  exports.setResolver = setResolver;
3170
3334
  exports.setValueHelpCacheTtl = setValueHelpCacheTtl;
3171
3335
  exports.splitDecimalString = splitDecimalString;
package/dist/index.d.cts CHANGED
@@ -171,9 +171,12 @@ interface FormFieldDef {
171
171
  */
172
172
  valueHelpInfo?: ValueHelpInfo;
173
173
  /**
174
- * Server-computed `@db.column.derived` field, read from the type metadata.
174
+ * Server-owned field: a `@db.column.derived` one (read from the type
175
+ * metadata), a computed view column (`CreateFormDefOptions.metaFields`) or,
176
+ * in an edit form (`CreateFormDefOptions.mode`), an `@db.onUpdate.now` one.
175
177
  * Rendered read-only, exempt from form validation and never sent by
176
- * `buildFormDiff` (the server drops a written value anyway). Since 0.1.144.
178
+ * `buildFormDiff` (the server drops or overwrites a written value anyway).
179
+ * Since 0.1.144.
177
180
  */
178
181
  derived?: true;
179
182
  }
@@ -261,6 +264,18 @@ interface CreateFormDefOptions {
261
264
  metaFields?: Record<string, {
262
265
  computed?: boolean;
263
266
  }>;
267
+ /**
268
+ * What the form is for. `"edit"` — the form edits a stored row and is sent
269
+ * as an update: an `@db.onUpdate.now` field (`number.timestamp.updated`),
270
+ * which the server sets on every update and whose sent value it ignores, is
271
+ * then marked `derived` — read-only, never validated, never sent. Applies at
272
+ * every depth (embedded objects, objects in arrays), except for a reference
273
+ * to another field, an element of an array of numbers, and below a tuple or
274
+ * a union of several types, where the server does not set the field.
275
+ * `"create"` (default) — the field stays editable: the server only fills it
276
+ * when it has `@db.default.now` and the value is left out. Since 0.1.154.
277
+ */
278
+ mode?: "create" | "edit";
264
279
  }
265
280
  /**
266
281
  * Converts an ATScript annotated type into a FormDef.
@@ -270,7 +285,8 @@ interface CreateFormDefOptions {
270
285
  * with `path: ''`.
271
286
  *
272
287
  * A `@db.column.derived` field is marked `derived` straight from its metadata;
273
- * a computed view column, from `opts.metaFields`.
288
+ * a computed view column, from `opts.metaFields`; an `@db.onUpdate.now` field,
289
+ * when `opts.mode` is `"edit"`.
274
290
  */
275
291
  declare function createFormDef(type: TAtscriptAnnotatedType, opts?: CreateFormDefOptions): FormDef;
276
292
  /**
@@ -675,7 +691,7 @@ declare function getDefaultValidatorPlugins(): TValidatorPlugin[];
675
691
  *
676
692
  * Validator is created once and reused on every call.
677
693
  * ATScript's @expect.* validation runs automatically; server-managed db
678
- * fields (`@db.column.derived`, absent `@db.default*` / version) pass.
694
+ * fields (every `derived` field, absent `@db.default*` / version) pass.
679
695
  * For custom `ui.fn.*` validators, install ui-fns and pass its plugin via `opts.plugins`.
680
696
  */
681
697
  declare function getFormValidator(def: FormDef, opts?: Partial<TValidatorOptions>): (callOpts: TFormValidatorCallOptions) => Record<string, string>;
@@ -1486,6 +1502,9 @@ declare function resetDefaultClientFactory(): void;
1486
1502
  * under different route params) also share the deserialized type and the
1487
1503
  * `TableDef` across URLs.
1488
1504
  *
1505
+ * The cache keeps the {@link setMetaCacheMaxEntries} most recently used
1506
+ * URLs; an entry held with {@link retainMetaEntry} is never evicted.
1507
+ *
1489
1508
  * `/meta` is projected per viewer, so the cache belongs to one identity
1490
1509
  * (`setMetaCacheIdentity`) and exists only in the browser: during server
1491
1510
  * rendering one process serves many viewers, so every call builds a fresh,
@@ -1514,11 +1533,29 @@ interface MetaEntryOptions {
1514
1533
  /**
1515
1534
  * Get or create the cache entry for `url`. First caller's `factory` (and
1516
1535
  * `options.metaKey`) seeds the `Client`; subsequent callers reuse it. On
1517
- * `meta` rejection, the entry is evicted so the next call retries. Without a
1518
- * browser `window` nothing is cached and the client is asked for
1519
- * `metaStore: false`.
1536
+ * `meta` rejection, the entry is evicted so the next call retries. A hit
1537
+ * marks the URL most recently used; hold an entry you keep using with
1538
+ * {@link retainMetaEntry}. Without a browser `window` nothing is cached and
1539
+ * the client is asked for `metaStore: false`.
1520
1540
  */
1521
1541
  declare function getMetaEntry(url: string, factory?: ClientFactory, options?: MetaEntryOptions): MetaCacheEntry;
1542
+ /**
1543
+ * Keep `entry` in the cache while it is in use: a held entry is never
1544
+ * evicted by the size limit ({@link setMetaCacheMaxEntries}), so later
1545
+ * `getMetaEntry` / `resolveValueHelp` calls for its URL keep returning it.
1546
+ * Call the returned function (idempotent) once done — `useTable` and the
1547
+ * form value-help do this for their component's lifetime. A reset still
1548
+ * drops held entries. Since 0.1.154.
1549
+ */
1550
+ declare function retainMetaEntry(entry: MetaCacheEntry): () => void;
1551
+ /**
1552
+ * How many URLs the meta cache keeps (default `100`). Least recently used
1553
+ * entries beyond it are dropped — entries held with {@link retainMetaEntry}
1554
+ * (every mounted table and form value-help) never are, and may exceed it.
1555
+ * At least `1`; `Infinity` turns the limit off; no argument restores the
1556
+ * default. Since 0.1.154.
1557
+ */
1558
+ declare function setMetaCacheMaxEntries(max?: number): void;
1522
1559
  /**
1523
1560
  * The `TableDef` for a cache entry, built once per entry — and once per
1524
1561
  * `/meta` `ETag` across entries. Since 0.1.153.
@@ -1628,4 +1665,4 @@ interface TModelRoute {
1628
1665
  */
1629
1666
  declare function buildModelRoutes(models: readonly TAtscriptAnnotatedType[]): TModelRoute[];
1630
1667
  //#endregion
1631
- export { type ClientFactory, type ClientFactoryOptions, 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 MetaEntryOptions, 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, getMetaCacheIdentity, getMetaEntry, getMetaTableDef, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, invalidateValueHelpCache, isArrayField, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, onMetaCacheReset, 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 };
1668
+ export { type ClientFactory, type ClientFactoryOptions, 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 MetaEntryOptions, 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, getMetaCacheIdentity, getMetaEntry, getMetaTableDef, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, invalidateValueHelpCache, isArrayField, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, onMetaCacheReset, optKey, optLabel, optionLabel, optionValue, parseColSpan, parseDecimalInput, parseRowSpan, parseStaticAttrs, parseStaticOptions, resetDefaultClientFactory, resetMetaCache, resetValueHelpCache, resolveAttrs, resolveFieldProp, resolveFormProp, resolveGridSpec, resolveOptions, resolveSingularLabel, resolveStatic, resolveValueHelp, retainMetaEntry, setByPath, setDefaultClientFactory, setDefaultValidatorPlugins, setMetaCacheIdentity, setMetaCacheMaxEntries, setResolver, setValueHelpCacheTtl, splitDecimalString, str, unionVariantChanged, valueHelpDictPaths };
package/dist/index.d.mts CHANGED
@@ -171,9 +171,12 @@ interface FormFieldDef {
171
171
  */
172
172
  valueHelpInfo?: ValueHelpInfo;
173
173
  /**
174
- * Server-computed `@db.column.derived` field, read from the type metadata.
174
+ * Server-owned field: a `@db.column.derived` one (read from the type
175
+ * metadata), a computed view column (`CreateFormDefOptions.metaFields`) or,
176
+ * in an edit form (`CreateFormDefOptions.mode`), an `@db.onUpdate.now` one.
175
177
  * Rendered read-only, exempt from form validation and never sent by
176
- * `buildFormDiff` (the server drops a written value anyway). Since 0.1.144.
178
+ * `buildFormDiff` (the server drops or overwrites a written value anyway).
179
+ * Since 0.1.144.
177
180
  */
178
181
  derived?: true;
179
182
  }
@@ -261,6 +264,18 @@ interface CreateFormDefOptions {
261
264
  metaFields?: Record<string, {
262
265
  computed?: boolean;
263
266
  }>;
267
+ /**
268
+ * What the form is for. `"edit"` — the form edits a stored row and is sent
269
+ * as an update: an `@db.onUpdate.now` field (`number.timestamp.updated`),
270
+ * which the server sets on every update and whose sent value it ignores, is
271
+ * then marked `derived` — read-only, never validated, never sent. Applies at
272
+ * every depth (embedded objects, objects in arrays), except for a reference
273
+ * to another field, an element of an array of numbers, and below a tuple or
274
+ * a union of several types, where the server does not set the field.
275
+ * `"create"` (default) — the field stays editable: the server only fills it
276
+ * when it has `@db.default.now` and the value is left out. Since 0.1.154.
277
+ */
278
+ mode?: "create" | "edit";
264
279
  }
265
280
  /**
266
281
  * Converts an ATScript annotated type into a FormDef.
@@ -270,7 +285,8 @@ interface CreateFormDefOptions {
270
285
  * with `path: ''`.
271
286
  *
272
287
  * A `@db.column.derived` field is marked `derived` straight from its metadata;
273
- * a computed view column, from `opts.metaFields`.
288
+ * a computed view column, from `opts.metaFields`; an `@db.onUpdate.now` field,
289
+ * when `opts.mode` is `"edit"`.
274
290
  */
275
291
  declare function createFormDef(type: TAtscriptAnnotatedType, opts?: CreateFormDefOptions): FormDef;
276
292
  /**
@@ -675,7 +691,7 @@ declare function getDefaultValidatorPlugins(): TValidatorPlugin[];
675
691
  *
676
692
  * Validator is created once and reused on every call.
677
693
  * ATScript's @expect.* validation runs automatically; server-managed db
678
- * fields (`@db.column.derived`, absent `@db.default*` / version) pass.
694
+ * fields (every `derived` field, absent `@db.default*` / version) pass.
679
695
  * For custom `ui.fn.*` validators, install ui-fns and pass its plugin via `opts.plugins`.
680
696
  */
681
697
  declare function getFormValidator(def: FormDef, opts?: Partial<TValidatorOptions>): (callOpts: TFormValidatorCallOptions) => Record<string, string>;
@@ -1486,6 +1502,9 @@ declare function resetDefaultClientFactory(): void;
1486
1502
  * under different route params) also share the deserialized type and the
1487
1503
  * `TableDef` across URLs.
1488
1504
  *
1505
+ * The cache keeps the {@link setMetaCacheMaxEntries} most recently used
1506
+ * URLs; an entry held with {@link retainMetaEntry} is never evicted.
1507
+ *
1489
1508
  * `/meta` is projected per viewer, so the cache belongs to one identity
1490
1509
  * (`setMetaCacheIdentity`) and exists only in the browser: during server
1491
1510
  * rendering one process serves many viewers, so every call builds a fresh,
@@ -1514,11 +1533,29 @@ interface MetaEntryOptions {
1514
1533
  /**
1515
1534
  * Get or create the cache entry for `url`. First caller's `factory` (and
1516
1535
  * `options.metaKey`) seeds the `Client`; subsequent callers reuse it. On
1517
- * `meta` rejection, the entry is evicted so the next call retries. Without a
1518
- * browser `window` nothing is cached and the client is asked for
1519
- * `metaStore: false`.
1536
+ * `meta` rejection, the entry is evicted so the next call retries. A hit
1537
+ * marks the URL most recently used; hold an entry you keep using with
1538
+ * {@link retainMetaEntry}. Without a browser `window` nothing is cached and
1539
+ * the client is asked for `metaStore: false`.
1520
1540
  */
1521
1541
  declare function getMetaEntry(url: string, factory?: ClientFactory, options?: MetaEntryOptions): MetaCacheEntry;
1542
+ /**
1543
+ * Keep `entry` in the cache while it is in use: a held entry is never
1544
+ * evicted by the size limit ({@link setMetaCacheMaxEntries}), so later
1545
+ * `getMetaEntry` / `resolveValueHelp` calls for its URL keep returning it.
1546
+ * Call the returned function (idempotent) once done — `useTable` and the
1547
+ * form value-help do this for their component's lifetime. A reset still
1548
+ * drops held entries. Since 0.1.154.
1549
+ */
1550
+ declare function retainMetaEntry(entry: MetaCacheEntry): () => void;
1551
+ /**
1552
+ * How many URLs the meta cache keeps (default `100`). Least recently used
1553
+ * entries beyond it are dropped — entries held with {@link retainMetaEntry}
1554
+ * (every mounted table and form value-help) never are, and may exceed it.
1555
+ * At least `1`; `Infinity` turns the limit off; no argument restores the
1556
+ * default. Since 0.1.154.
1557
+ */
1558
+ declare function setMetaCacheMaxEntries(max?: number): void;
1522
1559
  /**
1523
1560
  * The `TableDef` for a cache entry, built once per entry — and once per
1524
1561
  * `/meta` `ETag` across entries. Since 0.1.153.
@@ -1628,4 +1665,4 @@ interface TModelRoute {
1628
1665
  */
1629
1666
  declare function buildModelRoutes(models: readonly TAtscriptAnnotatedType[]): TModelRoute[];
1630
1667
  //#endregion
1631
- export { type ClientFactory, type ClientFactoryOptions, 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 MetaEntryOptions, 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, getMetaCacheIdentity, getMetaEntry, getMetaTableDef, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, invalidateValueHelpCache, isArrayField, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, onMetaCacheReset, 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 };
1668
+ export { type ClientFactory, type ClientFactoryOptions, 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 MetaEntryOptions, 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, getMetaCacheIdentity, getMetaEntry, getMetaTableDef, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, invalidateValueHelpCache, isArrayField, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, onMetaCacheReset, optKey, optLabel, optionLabel, optionValue, parseColSpan, parseDecimalInput, parseRowSpan, parseStaticAttrs, parseStaticOptions, resetDefaultClientFactory, resetMetaCache, resetValueHelpCache, resolveAttrs, resolveFieldProp, resolveFormProp, resolveGridSpec, resolveOptions, resolveSingularLabel, resolveStatic, resolveValueHelp, retainMetaEntry, setByPath, setDefaultClientFactory, setDefaultValidatorPlugins, setMetaCacheIdentity, setMetaCacheMaxEntries, setResolver, setValueHelpCacheTtl, splitDecimalString, str, unionVariantChanged, valueHelpDictPaths };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Validator, createDataFromAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType } from "@atscript/typescript/utils";
2
- import { Client, actionIdentifier, clearMetaStore, encodeNavigateId } from "@atscript/db-client";
2
+ import { Client, actionIdentifier, clearMetaStore, defaultMetaStore, encodeNavigateId } from "@atscript/db-client";
3
3
  import { createDbValidatorPlugin } from "@atscript/db/validator";
4
4
  //#region src/shared/annotation-keys.ts
5
5
  const UI_TYPE = "ui.type";
@@ -434,6 +434,7 @@ const UI_TAGS = new Set([
434
434
  "radio",
435
435
  "checkbox"
436
436
  ]);
437
+ const EDIT = { mode: "edit" };
437
438
  /**
438
439
  * Converts an ATScript annotated type into a FormDef.
439
440
  *
@@ -442,11 +443,13 @@ const UI_TAGS = new Set([
442
443
  * with `path: ''`.
443
444
  *
444
445
  * A `@db.column.derived` field is marked `derived` straight from its metadata;
445
- * a computed view column, from `opts.metaFields`.
446
+ * a computed view column, from `opts.metaFields`; an `@db.onUpdate.now` field,
447
+ * when `opts.mode` is `"edit"`.
446
448
  */
447
449
  function createFormDef(type, opts) {
450
+ const edit = opts?.mode === "edit";
448
451
  if (type.type.kind !== "object") {
449
- const rootField = createFieldDef("", type);
452
+ const rootField = createFieldDef("", type, edit);
450
453
  const fields = [rootField];
451
454
  return {
452
455
  type,
@@ -472,7 +475,7 @@ function createFormDef(type, opts) {
472
475
  if (originalProp.type.of.type.kind === "array" && !getFieldMeta(originalProp, "ui.form.component")) continue;
473
476
  }
474
477
  if (kind === "array" || kind === "object" || kind === "union" || kind === "tuple") structuredPrefixes.add(path + ".");
475
- const field = createFieldDef(path, originalProp);
478
+ const field = createFieldDef(path, originalProp, edit);
476
479
  if (opts?.metaFields?.[path]?.computed) field.derived = true;
477
480
  fields.push(field);
478
481
  }
@@ -504,14 +507,18 @@ function createFormDef(type, opts) {
504
507
  rootField.objectDef = def;
505
508
  return def;
506
509
  }
507
- /** Creates a FormFieldDef from any ATScript annotated type. */
508
- function createFieldDef(path, prop) {
510
+ /**
511
+ * Creates a FormFieldDef from any ATScript annotated type. `edit`: the form
512
+ * edits a stored row (`CreateFormDefOptions.mode`).
513
+ */
514
+ function createFieldDef(path, prop, edit = false) {
509
515
  const kind = prop.type.kind;
510
516
  const name = path.slice(path.lastIndexOf(".") + 1);
511
517
  const allStatic = !hasComputedAnnotations(prop);
512
518
  const uiType = getFieldMeta(prop, "ui.form.type") ?? getFieldMeta(prop, "ui.type");
513
519
  const pushDown = getFieldMeta(prop, UI_FORM_PUSH_DOWN) !== void 0;
514
520
  const valueHelpInfo = extractValueHelp(prop);
521
+ const derived = getFieldMeta(prop, "db.column.derived") !== void 0 || edit && path !== "" && isUpdateStamped(prop);
515
522
  const base = {
516
523
  path,
517
524
  prop,
@@ -520,7 +527,7 @@ function createFieldDef(path, prop) {
520
527
  allStatic,
521
528
  pushDown,
522
529
  valueHelpInfo,
523
- ...getFieldMeta(prop, "db.column.derived") !== void 0 && { derived: true }
530
+ ...derived && { derived: true }
524
531
  };
525
532
  const customType = uiType;
526
533
  if (kind === "array") {
@@ -531,21 +538,21 @@ function createFieldDef(path, prop) {
531
538
  type: "array",
532
539
  customType: isMultiselect ? "multiselect" : customType,
533
540
  itemType: arrayType.of,
534
- itemField: createFieldDef("", arrayType.of)
541
+ itemField: createFieldDef("", arrayType.of, edit)
535
542
  };
536
543
  }
537
544
  if (kind === "object") return {
538
545
  ...base,
539
546
  type: "object",
540
547
  customType,
541
- objectDef: createFormDef(prop)
548
+ objectDef: createFormDef(prop, edit ? EDIT : void 0)
542
549
  };
543
550
  if (kind === "union") {
544
551
  if (isPureLiteralUnion(prop)) return {
545
552
  ...base,
546
553
  type: uiType ?? "select"
547
554
  };
548
- const unionVariants = buildUnionVariants(prop);
555
+ const unionVariants = createUnionVariants(prop, edit && soleValueMember(prop) !== void 0);
549
556
  if (unionVariants.length > 1) return {
550
557
  ...base,
551
558
  type: "union",
@@ -558,7 +565,8 @@ function createFieldDef(path, prop) {
558
565
  path,
559
566
  name,
560
567
  allStatic,
561
- pushDown
568
+ pushDown,
569
+ ...derived && { derived: true }
562
570
  };
563
571
  if (v?.def) return {
564
572
  ...base,
@@ -676,17 +684,20 @@ function isChildOfStructured(path, prefixes) {
676
684
  * Iterates top-level items directly — one variant per item.
677
685
  */
678
686
  function buildUnionVariants(typeDef) {
687
+ return createUnionVariants(typeDef, false);
688
+ }
689
+ function createUnionVariants(typeDef, edit) {
679
690
  const items = typeDef.type.items ?? [typeDef];
680
691
  const variants = [];
681
692
  for (const item of items) {
682
- const v = createVariant(item);
693
+ const v = createVariant(item, edit);
683
694
  if (items.length > 1) v.label = `${String(variants.length + 1)}. ${v.label}`;
684
695
  variants.push(v);
685
696
  }
686
697
  return variants;
687
698
  }
688
699
  /** Creates a single union variant from an annotated type item. */
689
- function createVariant(def) {
700
+ function createVariant(def, edit) {
690
701
  const kind = def.type.kind;
691
702
  if (kind === "object") {
692
703
  const label = getFieldMeta(def, "meta.label") ?? "Object";
@@ -694,8 +705,8 @@ function createVariant(def) {
694
705
  return {
695
706
  label,
696
707
  type: def,
697
- def: createFormDef(def),
698
- itemField: hasComponent ? createFieldDef("", def) : void 0
708
+ def: createFormDef(def, edit ? EDIT : void 0),
709
+ itemField: hasComponent ? createFieldDef("", def, edit) : void 0
699
710
  };
700
711
  }
701
712
  if (kind === "") {
@@ -703,15 +714,36 @@ function createVariant(def) {
703
714
  return {
704
715
  label: capitalize(dt === "phantom" ? "item" : dt),
705
716
  type: def,
706
- itemField: createFieldDef("", def),
717
+ itemField: createFieldDef("", def, edit),
707
718
  designType: dt
708
719
  };
709
720
  }
710
721
  return {
711
722
  label: capitalize(kind),
712
723
  type: def,
713
- itemField: createFieldDef("", def)
724
+ itemField: createFieldDef("", def, edit)
725
+ };
726
+ }
727
+ /**
728
+ * `@db.onUpdate.now` (`number.timestamp.updated`): the server sets the field
729
+ * on every update. Read off the prop, or — as `@atscript/db` does — off the one
730
+ * value member of `T | null`, unless the prop references another field.
731
+ */
732
+ function isUpdateStamped(prop) {
733
+ if (hasFieldMeta(prop, "db.onUpdate.now")) return true;
734
+ const member = prop.ref?.field ? void 0 : soleValueMember(prop);
735
+ return member !== void 0 && hasFieldMeta(member, "db.onUpdate.now");
736
+ }
737
+ /** The one non-`null` / `undefined` member of a (nested) union, if there is exactly one. */
738
+ function soleValueMember(prop) {
739
+ if (prop.type.kind !== "union") return void 0;
740
+ const members = /* @__PURE__ */ new Set();
741
+ const visit = (t) => {
742
+ if (t.type.kind === "union") for (const item of t.type.items) visit(item);
743
+ else if (t.type.kind !== "" || t.type.designType !== "null" && t.type.designType !== "undefined") members.add(t);
714
744
  };
745
+ visit(prop);
746
+ return members.size === 1 ? members.values().next().value : void 0;
715
747
  }
716
748
  function capitalize(s) {
717
749
  return s.charAt(0).toUpperCase() + s.slice(1);
@@ -1275,39 +1307,50 @@ function inferValueKind(prop) {
1275
1307
  }
1276
1308
  //#endregion
1277
1309
  //#region src/shared/meta-cache.ts
1310
+ /**
1311
+ * Enough for every URL a page touches — a table, the dictionaries its
1312
+ * filters and forms pick from — plus the recent navigation history, so going
1313
+ * back is instant; small enough to cap a long session at a few MB of parsed
1314
+ * `/meta`. Twice the `@atscript/db-client` `MetaStore` body limit, since
1315
+ * parametric URLs share bodies.
1316
+ */
1317
+ const DEFAULT_MAX_ENTRIES = 100;
1318
+ let maxEntries = DEFAULT_MAX_ENTRIES;
1319
+ /** Per-URL entries, least recently used first. Browser only. */
1278
1320
  const cache = /* @__PURE__ */ new Map();
1279
- /** Derived shapes per `ETag`, least recently used first. Browser only. */
1321
+ const slots = /* @__PURE__ */ new WeakMap();
1322
+ /** Derived shapes per `ETag`, counted by the cached entries that use them. Browser only. */
1280
1323
  const derivedByEtag = /* @__PURE__ */ new Map();
1281
- const MAX_DERIVED = 50;
1282
- /** The `Derived` promise behind each handed-out entry (kept off the public shape). */
1283
- const derivedOf = /* @__PURE__ */ new WeakMap();
1284
- /** Custom `/meta` stores of clients this cache created in the browser. */
1285
- const customStores = /* @__PURE__ */ new Set();
1324
+ /** Custom `/meta` stores of cached clients, counted by the entries that use them. */
1325
+ const customStores = /* @__PURE__ */ new Map();
1286
1326
  /** `undefined` until the first `setMetaCacheIdentity` call; `null` = anonymous. */
1287
1327
  let identity;
1288
1328
  const resetListeners = /* @__PURE__ */ new Set();
1289
1329
  /**
1290
1330
  * Get or create the cache entry for `url`. First caller's `factory` (and
1291
1331
  * `options.metaKey`) seeds the `Client`; subsequent callers reuse it. On
1292
- * `meta` rejection, the entry is evicted so the next call retries. Without a
1293
- * browser `window` nothing is cached and the client is asked for
1294
- * `metaStore: false`.
1332
+ * `meta` rejection, the entry is evicted so the next call retries. A hit
1333
+ * marks the URL most recently used; hold an entry you keep using with
1334
+ * {@link retainMetaEntry}. Without a browser `window` nothing is cached and
1335
+ * the client is asked for `metaStore: false`.
1295
1336
  */
1296
1337
  function getMetaEntry(url, factory, options) {
1297
1338
  const browser = typeof window !== "undefined";
1298
1339
  const existing = browser ? cache.get(url) : void 0;
1299
- if (existing) return existing;
1340
+ if (existing) {
1341
+ touch(url, existing);
1342
+ return existing;
1343
+ }
1300
1344
  const f = factory ?? getDefaultClientFactory();
1301
1345
  let client;
1302
1346
  if (!browser) client = f(url, { metaStore: false });
1303
1347
  else if (options?.metaKey) client = f(url, { metaKey: options.metaKey });
1304
1348
  else client = f(url);
1305
- if (browser) rememberStore(client);
1306
1349
  const meta = client.meta().catch((err) => {
1307
- if (cache.get(url) === entry) cache.delete(url);
1350
+ if (cache.get(url) === entry) evict(url, entry);
1308
1351
  throw err;
1309
1352
  });
1310
- const derived = meta.then((m) => derive(client, m, browser));
1353
+ const derived = meta.then((m) => derive(entry, client, m));
1311
1354
  const type = derived.then((d) => d.type);
1312
1355
  type.catch(() => {});
1313
1356
  const entry = {
@@ -1315,44 +1358,130 @@ function getMetaEntry(url, factory, options) {
1315
1358
  meta,
1316
1359
  type
1317
1360
  };
1318
- derivedOf.set(entry, derived);
1319
- if (browser) cache.set(url, entry);
1361
+ const slot = {
1362
+ url,
1363
+ derived,
1364
+ holds: 0
1365
+ };
1366
+ slots.set(entry, slot);
1367
+ if (browser) {
1368
+ slot.store = customStoreOf(client);
1369
+ if (slot.store) customStores.set(slot.store, (customStores.get(slot.store) ?? 0) + 1);
1370
+ cache.set(url, entry);
1371
+ trim(entry);
1372
+ }
1320
1373
  return entry;
1321
1374
  }
1322
1375
  /**
1376
+ * Keep `entry` in the cache while it is in use: a held entry is never
1377
+ * evicted by the size limit ({@link setMetaCacheMaxEntries}), so later
1378
+ * `getMetaEntry` / `resolveValueHelp` calls for its URL keep returning it.
1379
+ * Call the returned function (idempotent) once done — `useTable` and the
1380
+ * form value-help do this for their component's lifetime. A reset still
1381
+ * drops held entries. Since 0.1.154.
1382
+ */
1383
+ function retainMetaEntry(entry) {
1384
+ const slot = slots.get(entry);
1385
+ if (!slot) return () => {};
1386
+ slot.holds++;
1387
+ let released = false;
1388
+ return () => {
1389
+ if (released) return;
1390
+ released = true;
1391
+ slot.holds--;
1392
+ if (slot.holds === 0 && cache.get(slot.url) === entry) {
1393
+ touch(slot.url, entry);
1394
+ trim();
1395
+ }
1396
+ };
1397
+ }
1398
+ /**
1399
+ * How many URLs the meta cache keeps (default `100`). Least recently used
1400
+ * entries beyond it are dropped — entries held with {@link retainMetaEntry}
1401
+ * (every mounted table and form value-help) never are, and may exceed it.
1402
+ * At least `1`; `Infinity` turns the limit off; no argument restores the
1403
+ * default. Since 0.1.154.
1404
+ */
1405
+ function setMetaCacheMaxEntries(max) {
1406
+ maxEntries = max === void 0 ? DEFAULT_MAX_ENTRIES : max >= 1 ? max : 1;
1407
+ trim();
1408
+ }
1409
+ function touch(url, entry) {
1410
+ cache.delete(url);
1411
+ cache.set(url, entry);
1412
+ }
1413
+ /**
1414
+ * Drop least recently used entries nothing holds until the cache fits.
1415
+ * `spare` — the entry just handed out, about to be retained by its caller.
1416
+ */
1417
+ function trim(spare) {
1418
+ if (cache.size <= maxEntries) return;
1419
+ for (const [url, entry] of cache) {
1420
+ if (entry !== spare && slots.get(entry).holds === 0) evict(url, entry);
1421
+ if (cache.size <= maxEntries) return;
1422
+ }
1423
+ }
1424
+ /**
1425
+ * Remove `entry` and release what only it kept: its shared `Derived` and
1426
+ * custom store. A reset no longer reaches its client, so the client's memoized
1427
+ * `/meta` goes now — a factory that reuses clients per URL would otherwise
1428
+ * hand it to the next viewer.
1429
+ */
1430
+ function evict(url, entry) {
1431
+ cache.delete(url);
1432
+ entry.client.invalidateMeta?.();
1433
+ const slot = slots.get(entry);
1434
+ if (slot.etag !== void 0 && --derivedByEtag.get(slot.etag).refs === 0) derivedByEtag.delete(slot.etag);
1435
+ if (slot.store) {
1436
+ const refs = customStores.get(slot.store);
1437
+ if (refs > 1) customStores.set(slot.store, refs - 1);
1438
+ else {
1439
+ slot.store.clear();
1440
+ customStores.delete(slot.store);
1441
+ }
1442
+ }
1443
+ }
1444
+ /**
1323
1445
  * The `TableDef` for a cache entry, built once per entry — and once per
1324
1446
  * `/meta` `ETag` across entries. Since 0.1.153.
1325
1447
  */
1326
1448
  function getMetaTableDef(entry) {
1327
1449
  if (!entry.tableDef) {
1328
- const derived = derivedOf.get(entry);
1450
+ const derived = slots.get(entry)?.derived;
1329
1451
  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));
1330
1452
  }
1331
1453
  return entry.tableDef;
1332
1454
  }
1333
- function derive(client, meta, browser) {
1334
- const etag = browser ? client.metaEtag?.() : void 0;
1455
+ /**
1456
+ * Shares the `Derived` of one `ETag` among the cached entries that loaded it;
1457
+ * an entry no longer cached (evicted, reset, server render) keeps its own.
1458
+ */
1459
+ function derive(entry, client, meta) {
1460
+ const slot = slots.get(entry);
1461
+ const etag = cache.get(slot.url) === entry ? client.metaEtag?.() : void 0;
1335
1462
  if (etag === void 0) return { type: deserializeAnnotatedType(meta.type) };
1336
- const hit = derivedByEtag.get(etag);
1337
- if (hit) {
1338
- derivedByEtag.delete(etag);
1339
- derivedByEtag.set(etag, hit);
1340
- return hit;
1463
+ let shared = derivedByEtag.get(etag);
1464
+ if (shared) shared.refs++;
1465
+ else {
1466
+ shared = {
1467
+ derived: { type: deserializeAnnotatedType(meta.type) },
1468
+ refs: 1
1469
+ };
1470
+ derivedByEtag.set(etag, shared);
1341
1471
  }
1342
- const fresh = { type: deserializeAnnotatedType(meta.type) };
1343
- derivedByEtag.set(etag, fresh);
1344
- if (derivedByEtag.size > MAX_DERIVED) derivedByEtag.delete(derivedByEtag.keys().next().value);
1345
- return fresh;
1472
+ slot.etag = etag;
1473
+ return shared.derived;
1346
1474
  }
1347
1475
  /**
1348
- * Remember a custom `/meta` store a factory gave `client`, so a reset can
1349
- * clear it. The store is a private field of `Client`, read defensively: the
1350
- * default store is cleared through `clearMetaStore()`, and a store-less
1351
- * client or a test double is skipped.
1476
+ * The custom `/meta` store a factory gave `client`, so a reset (and the
1477
+ * eviction of its last cached client) can clear it. The shared
1478
+ * `defaultMetaStore` is skipped: a reset clears it through
1479
+ * `clearMetaStore()`, and an eviction must not drop the ETags of every
1480
+ * other URL. A store-less client (`metaStore: false`) is skipped too.
1352
1481
  */
1353
- function rememberStore(client) {
1354
- const store = client._metaStore;
1355
- if (typeof store?.clear === "function") customStores.add(store);
1482
+ function customStoreOf(client) {
1483
+ const store = client.metaStore;
1484
+ return store && store !== defaultMetaStore ? store : void 0;
1356
1485
  }
1357
1486
  /**
1358
1487
  * Drop every cached `/meta` — including the copy each cached `Client`
@@ -1368,7 +1497,7 @@ function resetMetaCache() {
1368
1497
  derivedByEtag.clear();
1369
1498
  for (const entry of entries) entry.client.invalidateMeta?.();
1370
1499
  clearMetaStore();
1371
- for (const store of customStores) store.clear();
1500
+ for (const store of customStores.keys()) store.clear();
1372
1501
  customStores.clear();
1373
1502
  invalidateValueHelpCache();
1374
1503
  for (const listener of resetListeners) listener();
@@ -1678,6 +1807,36 @@ const serverManagedPlugin = (ctx, def, value) => {
1678
1807
  if (value !== void 0 || def.metadata.has("db.rel.FK")) return void 0;
1679
1808
  return dbPlugin(Object.create(ctx, { context: { value: INSERT_CONTEXT } }), def, value);
1680
1809
  };
1810
+ /**
1811
+ * The props of the fields `createFormDef` marked `derived`, at any depth — a
1812
+ * computed view column (`metaFields`) or an edit form's `@db.onUpdate.now`
1813
+ * field carries no annotation the plugin above could read. The validator
1814
+ * matches by prop, so a prop that is also used where it is not derived (an
1815
+ * interface's stamp below a union of several types, too) stays validated.
1816
+ */
1817
+ function collectDerivedProps(def) {
1818
+ const derived = /* @__PURE__ */ new Set();
1819
+ const kept = /* @__PURE__ */ new Set();
1820
+ const walk = (fields) => {
1821
+ for (const field of fields) {
1822
+ if (field.derived) {
1823
+ derived.add(field.prop);
1824
+ continue;
1825
+ }
1826
+ kept.add(field.prop);
1827
+ if (isObjectField(field)) walk(field.objectDef.fields);
1828
+ else if (isArrayField(field)) walk([field.itemField]);
1829
+ else if (isTupleField(field)) walk(field.itemFields);
1830
+ else if (isUnionField(field)) for (const v of field.unionVariants) {
1831
+ if (v.def) walk(v.def.fields);
1832
+ if (v.itemField) walk([v.itemField]);
1833
+ }
1834
+ }
1835
+ };
1836
+ walk(def.fields);
1837
+ for (const prop of kept) derived.delete(prop);
1838
+ return derived;
1839
+ }
1681
1840
  let defaultValidatorPlugins = [];
1682
1841
  /** Replace the default validator plugins applied to every form/field validator. */
1683
1842
  function setDefaultValidatorPlugins(plugins) {
@@ -1692,14 +1851,17 @@ function getDefaultValidatorPlugins() {
1692
1851
  *
1693
1852
  * Validator is created once and reused on every call.
1694
1853
  * ATScript's @expect.* validation runs automatically; server-managed db
1695
- * fields (`@db.column.derived`, absent `@db.default*` / version) pass.
1854
+ * fields (every `derived` field, absent `@db.default*` / version) pass.
1696
1855
  * For custom `ui.fn.*` validators, install ui-fns and pass its plugin via `opts.plugins`.
1697
1856
  */
1698
1857
  function getFormValidator(def, opts) {
1858
+ const derived = collectDerivedProps(def);
1859
+ const derivedPlugin = (_ctx, prop) => derived.has(prop) ? true : void 0;
1699
1860
  const validator = new Validator(def.type, {
1700
1861
  unknownProps: "ignore",
1701
1862
  ...opts,
1702
1863
  plugins: [
1864
+ ...derived.size > 0 ? [derivedPlugin] : [],
1703
1865
  serverManagedPlugin,
1704
1866
  ...defaultValidatorPlugins,
1705
1867
  ...opts?.plugins ?? []
@@ -2994,4 +3156,4 @@ function resolvePath(model, table, view) {
2994
3156
  return path.length > 0 ? path : void 0;
2995
3157
  }
2996
3158
  //#endregion
2997
- 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, getMetaCacheIdentity, getMetaEntry, getMetaTableDef, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, invalidateValueHelpCache, isArrayField, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, onMetaCacheReset, 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 };
3159
+ 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, getMetaCacheIdentity, getMetaEntry, getMetaTableDef, getResolver, getSortableColumns, getThousandsSeparator, groupInteger, hasComputedAnnotations, hasFieldMeta, invalidateValueHelpCache, isArrayField, isFieldHidden, isObjectField, isPathDirty, isPickerDeclined, isPureLiteralUnion, isTupleField, isUnionField, iteratePathAncestors, joinDecimalString, joinPath, mergeErrorMaps, navigateHrefFor, omitPaths, onMetaCacheReset, optKey, optLabel, optionLabel, optionValue, parseColSpan, parseDecimalInput, parseRowSpan, parseStaticAttrs, parseStaticOptions, resetDefaultClientFactory, resetMetaCache, resetValueHelpCache, resolveAttrs, resolveFieldProp, resolveFormProp, resolveGridSpec, resolveOptions, resolveSingularLabel, resolveStatic, resolveValueHelp, retainMetaEntry, setByPath, setDefaultClientFactory, setDefaultValidatorPlugins, setMetaCacheIdentity, setMetaCacheMaxEntries, 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.153",
3
+ "version": "0.1.155",
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.153"
50
+ "@atscript/db-client": "^0.1.157"
51
51
  },
52
52
  "devDependencies": {
53
- "@atscript/core": "^0.1.103",
54
- "@atscript/db": "^0.1.153",
55
- "@atscript/typescript": "^0.1.103",
53
+ "@atscript/core": "^0.1.106",
54
+ "@atscript/db": "^0.1.157",
55
+ "@atscript/typescript": "^0.1.106",
56
56
  "@uniqu/core": "^0.1.15",
57
- "unplugin-atscript": "^0.1.103",
57
+ "unplugin-atscript": "^0.1.106",
58
58
  "vitest": "npm:@voidzero-dev/vite-plus-test@0.1.14"
59
59
  },
60
60
  "peerDependencies": {
61
- "@atscript/core": "^0.1.103",
62
- "@atscript/db": "^0.1.153",
63
- "@atscript/typescript": "^0.1.103"
61
+ "@atscript/core": "^0.1.106",
62
+ "@atscript/db": "^0.1.157",
63
+ "@atscript/typescript": "^0.1.106"
64
64
  },
65
65
  "scripts": {
66
66
  "build": "vp pack",