@atscript/ui 0.1.151 → 0.1.153

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
@@ -1014,7 +1014,7 @@ async function fetchDistinctValues(client, field, opts = {}) {
1014
1014
  }
1015
1015
  //#endregion
1016
1016
  //#region src/client-factory.ts
1017
- const builtin = (url) => new _atscript_db_client.Client(url);
1017
+ const builtin = (url, options) => new _atscript_db_client.Client(url, options);
1018
1018
  let _default = builtin;
1019
1019
  /**
1020
1020
  * Override the app-wide default factory. Call once at startup (e.g. in
@@ -1024,7 +1024,7 @@ let _default = builtin;
1024
1024
  function setDefaultClientFactory(factory) {
1025
1025
  _default = factory;
1026
1026
  }
1027
- /** Current app-wide default factory. Falls back to `new Client(url)`. */
1027
+ /** Current app-wide default factory. Falls back to `new Client(url, options)`. */
1028
1028
  function getDefaultClientFactory() {
1029
1029
  return _default;
1030
1030
  }
@@ -1033,43 +1033,346 @@ function resetDefaultClientFactory() {
1033
1033
  _default = builtin;
1034
1034
  }
1035
1035
  //#endregion
1036
+ //#region src/form/measurement.ts
1037
+ /**
1038
+ * Read measurement annotations off a single field prop. Returns `undefined`
1039
+ * for any annotation that's absent — callers can spread the result into a
1040
+ * larger record.
1041
+ */
1042
+ function extractMeasurement(prop) {
1043
+ const precisionMeta = getFieldMeta(prop, DB_COLUMN_PRECISION);
1044
+ return {
1045
+ currencyCode: getFieldMeta(prop, DB_AMOUNT_CURRENCY),
1046
+ currencyRefField: getFieldMeta(prop, DB_AMOUNT_CURRENCY_REF),
1047
+ unitCode: getFieldMeta(prop, DB_UNIT),
1048
+ unitRefField: getFieldMeta(prop, DB_UNIT_REF),
1049
+ precisionScale: precisionMeta?.scale
1050
+ };
1051
+ }
1052
+ //#endregion
1053
+ //#region src/table/create-table-def.ts
1054
+ /**
1055
+ * Builds a TableDef from a moost-db MetaResponse.
1056
+ *
1057
+ * 1. Deserializes `meta.type` into a live TAtscriptAnnotatedType
1058
+ * 2. Flattens to discover all field paths
1059
+ * 3. Builds ColumnDef per field using annotations + meta.fields capabilities
1060
+ * 4. Sorts by @ui.table.order
1061
+ */
1062
+ function createTableDef(meta, preDeserializedType) {
1063
+ const type = preDeserializedType ?? (0, _atscript_typescript_utils.deserializeAnnotatedType)(meta.type);
1064
+ const flatMap = type.type.kind === "object" ? (0, _atscript_typescript_utils.flattenAnnotatedType)(type, { excludePhantomTypes: true }) : /* @__PURE__ */ new Map();
1065
+ const columns = [];
1066
+ for (const [path, prop] of flatMap.entries()) {
1067
+ if (path === "") continue;
1068
+ if (path === meta.versionColumn) continue;
1069
+ const fieldMeta = meta.fields[path];
1070
+ if (!isReadable(fieldMeta)) continue;
1071
+ if (getFieldMeta(prop, "ui.table.exclude") !== void 0) continue;
1072
+ const options = extractFieldLiteralOptions(prop);
1073
+ const valueHelpInfo = extractValueHelp(prop);
1074
+ let distinct;
1075
+ if (!valueHelpInfo && !options && fieldMeta.groupable && fieldMeta.filterable) {
1076
+ const url = type.metadata.get(DB_HTTP_PATH);
1077
+ if (url && getFieldMeta(prop, "ui.valueHelp.distinct") !== void 0) distinct = {
1078
+ url,
1079
+ field: path
1080
+ };
1081
+ }
1082
+ columns.push(buildColumn(path, prop, fieldMeta, {
1083
+ options,
1084
+ valueHelpInfo,
1085
+ distinct
1086
+ }));
1087
+ }
1088
+ if (meta.decorations) {
1089
+ const decoType = (0, _atscript_typescript_utils.deserializeAnnotatedType)(meta.decorations);
1090
+ if (decoType.type.kind === "object") for (const [path, prop] of decoType.type.props) {
1091
+ const fieldMeta = meta.fields[path];
1092
+ if (!fieldMeta?.decoration || flatMap.has(path)) continue;
1093
+ if (getFieldMeta(prop, "ui.table.exclude") !== void 0) continue;
1094
+ flatMap.set(path, prop);
1095
+ columns.push(buildColumn(path, prop, fieldMeta, { options: extractFieldLiteralOptions(prop) }));
1096
+ }
1097
+ }
1098
+ columns.sort((a, b) => a.order - b.order);
1099
+ const actions = groupActions(meta.actions ?? []);
1100
+ const crud = meta.crud ?? {};
1101
+ const preferredId = meta.preferredId ?? meta.primaryKeys;
1102
+ return {
1103
+ type,
1104
+ columns,
1105
+ flatMap,
1106
+ fetchableFields: new Set(Object.keys(meta.fields).filter((p) => isReadable(meta.fields[p]))),
1107
+ primaryKeys: meta.primaryKeys,
1108
+ preferredId,
1109
+ identifierFields: identifierFieldsOf(preferredId, meta.actions ?? []),
1110
+ versionColumn: meta.versionColumn,
1111
+ crud,
1112
+ canRemove: "remove" in crud,
1113
+ actions,
1114
+ searchable: meta.searchable,
1115
+ vectorSearchable: meta.vectorSearchable,
1116
+ searchIndexes: meta.searchIndexes,
1117
+ relations: meta.relations
1118
+ };
1119
+ }
1120
+ /**
1121
+ * One column. A server-declared display-only column (`fieldMeta.decoration`)
1122
+ * is never sortable, filterable or groupable and always nullable (a decoration
1123
+ * can be absent); an ordinary one takes its capabilities from `/meta`.
1124
+ */
1125
+ function buildColumn(path, prop, fieldMeta, resolved) {
1126
+ const { options, valueHelpInfo, distinct } = resolved;
1127
+ const maxLengthMeta = getFieldMeta(prop, EXPECT_MAX_LENGTH);
1128
+ const tableType = getFieldMeta(prop, UI_TABLE_TYPE);
1129
+ const sharedType = getFieldMeta(prop, UI_TYPE);
1130
+ const tableComponent = getFieldMeta(prop, UI_TABLE_COMPONENT);
1131
+ const decoration = fieldMeta.decoration === true;
1132
+ const filterOps = decoration ? void 0 : fieldMeta.filterOps;
1133
+ return {
1134
+ path,
1135
+ label: getFieldMeta(prop, "meta.label") ?? humanizePath(path),
1136
+ type: tableType ?? sharedType ?? (valueHelpInfo ? "ref" : inferDisplayType(prop, options)),
1137
+ valueKind: inferValueKind(prop),
1138
+ component: tableComponent,
1139
+ selectWith: getFieldMeta(prop, UI_TABLE_SELECT_WITH),
1140
+ sortable: !decoration && (fieldMeta.sortable ?? false),
1141
+ filterable: !decoration && (fieldMeta.filterable ?? false),
1142
+ ...filterOps && { filterOps: [...filterOps] },
1143
+ nullable: decoration || prop.optional === true,
1144
+ width: getFieldMeta(prop, UI_TABLE_WIDTH),
1145
+ maxLen: maxLengthMeta?.length,
1146
+ order: getFieldMeta(prop, "ui.table.order") ?? Infinity,
1147
+ options,
1148
+ valueHelpInfo,
1149
+ ...distinct && { distinct },
1150
+ ...extractMeasurement(prop)
1151
+ };
1152
+ }
1153
+ /**
1154
+ * `preferredId` ∪ every delegated action's `idMap` paths, in that order —
1155
+ * the same array when no action carries an `idMap`.
1156
+ */
1157
+ function identifierFieldsOf(preferredId, actions) {
1158
+ let out;
1159
+ for (const a of actions) {
1160
+ if (!a.idMap) continue;
1161
+ for (const path of Object.values(a.idMap)) {
1162
+ if (preferredId.includes(path) || out?.includes(path)) continue;
1163
+ (out ??= [...preferredId]).push(path);
1164
+ }
1165
+ }
1166
+ return out ?? preferredId;
1167
+ }
1168
+ /** A field the caller may read: listed in `meta.fields` and not write-only. */
1169
+ function isReadable(field) {
1170
+ return field !== void 0 && field.writeOnly !== true;
1171
+ }
1172
+ /** Sort by (order ?? 0). `toSorted` is stable per spec, so ties preserve declaration order. */
1173
+ function byOrder(xs) {
1174
+ return xs.toSorted((x, y) => (x.order ?? 0) - (y.order ?? 0));
1175
+ }
1176
+ /**
1177
+ * Partition actions by `level`, sort each group by `(order ?? 0)` then
1178
+ * declaration order, and pick the first `default: true` entry per level.
1179
+ * The synthesised `__remove` UI action lives outside this set and is never
1180
+ * a candidate for `default.row`.
1181
+ */
1182
+ function groupActions(actions) {
1183
+ const table = [];
1184
+ const row = [];
1185
+ const rows = [];
1186
+ for (const a of actions) if (a.level === "table") table.push(a);
1187
+ else if (a.level === "row") row.push(a);
1188
+ else if (a.level === "rows") rows.push(a);
1189
+ const tableSorted = byOrder(table);
1190
+ const rowSorted = byOrder(row);
1191
+ const rowsSorted = byOrder(rows);
1192
+ return {
1193
+ table: tableSorted,
1194
+ row: rowSorted,
1195
+ rows: rowsSorted,
1196
+ default: {
1197
+ table: tableSorted.find((a) => a.default === true),
1198
+ row: rowSorted.find((a) => a.default === true),
1199
+ rows: rowsSorted.find((a) => a.default === true)
1200
+ }
1201
+ };
1202
+ }
1203
+ /** Infers a display type string from the annotated type's kind and designType. */
1204
+ function inferDisplayType(prop, literalOpts) {
1205
+ const kind = prop.type.kind;
1206
+ if (kind === "array") return "array";
1207
+ if (kind === "object") return "object";
1208
+ if (kind === "union") return literalOpts !== void 0 ? "enum" : "union";
1209
+ if (kind === "") {
1210
+ const final = prop.type;
1211
+ const dt = final.designType;
1212
+ if (dt === "number") return final.tags?.has("timestamp") ? "datetime" : "number";
1213
+ if (dt === "decimal") return "number";
1214
+ if (dt === "boolean") return "boolean";
1215
+ return "text";
1216
+ }
1217
+ return "text";
1218
+ }
1219
+ /**
1220
+ * Number metadata that makes the server treat a plain `number` column as an
1221
+ * integer (mirrors the db layer's `valueTypeOf`), beside the `int` / `expect.int` tags.
1222
+ */
1223
+ const INTEGER_NUMBER_META = [
1224
+ "expect.int",
1225
+ "db.default.increment",
1226
+ "db.default.now",
1227
+ "db.agg.count",
1228
+ "db.agg.countDistinct"
1229
+ ];
1230
+ /** The kind of one scalar leaf, or `undefined` for a non-scalar / unknown design type. */
1231
+ function scalarValueKind(prop) {
1232
+ const final = prop.type;
1233
+ const tags = final.tags;
1234
+ switch (final.designType) {
1235
+ case "string": return tags?.has("isoDate") ? "isoDate" : tags?.has("date") ? "date" : "string";
1236
+ case "number":
1237
+ if (tags?.has("timestamp")) return "timestamp";
1238
+ if (tags?.has("int") || INTEGER_NUMBER_META.some((k) => prop.metadata.has(k))) return "integer";
1239
+ return "number";
1240
+ case "decimal": return "decimal";
1241
+ case "boolean": return "boolean";
1242
+ default: return;
1243
+ }
1244
+ }
1245
+ /** Kinds of every non-null leaf of a (possibly nested) union; `null` when one is not a scalar. */
1246
+ function collectUnionKinds(items, out) {
1247
+ for (const item of items) {
1248
+ if (item.type.kind === "union") {
1249
+ collectUnionKinds(item.type.items, out);
1250
+ continue;
1251
+ }
1252
+ if (item.type.kind === "") {
1253
+ const dt = item.type.designType;
1254
+ if (dt === "null" || dt === "undefined") continue;
1255
+ out.add(scalarValueKind(item));
1256
+ continue;
1257
+ }
1258
+ out.add(void 0);
1259
+ }
1260
+ }
1261
+ /**
1262
+ * Scalar storage kind of the column's value — what the server's filter guard
1263
+ * checks. A scalar maps to its kind; a union that agrees on one kind across
1264
+ * its non-null members (`'a' | 'b'`, `1 | 2`, `number.timestamp | null`)
1265
+ * takes it; arrays, objects, JSON and mixed unions have none (`undefined`),
1266
+ * which means no value coercion.
1267
+ */
1268
+ function inferValueKind(prop) {
1269
+ const kind = prop.type.kind;
1270
+ if (kind === "") return scalarValueKind(prop);
1271
+ if (kind !== "union") return void 0;
1272
+ const kinds = /* @__PURE__ */ new Set();
1273
+ collectUnionKinds(prop.type.items, kinds);
1274
+ if (kinds.size !== 1) return void 0;
1275
+ return [...kinds][0];
1276
+ }
1277
+ //#endregion
1036
1278
  //#region src/shared/meta-cache.ts
1037
1279
  const cache = /* @__PURE__ */ new Map();
1280
+ /** Derived shapes per `ETag`, least recently used first. Browser only. */
1281
+ 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();
1038
1287
  /** `undefined` until the first `setMetaCacheIdentity` call; `null` = anonymous. */
1039
1288
  let identity;
1289
+ const resetListeners = /* @__PURE__ */ new Set();
1040
1290
  /**
1041
- * Get or create the cache entry for `url`. First caller's `factory` seeds the
1042
- * `Client`; subsequent callers reuse it. On `meta` rejection, the entry is
1043
- * evicted so the next call retries. Without a browser `window` nothing is
1044
- * cached.
1291
+ * Get or create the cache entry for `url`. First caller's `factory` (and
1292
+ * `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`.
1045
1296
  */
1046
- function getMetaEntry(url, factory) {
1297
+ function getMetaEntry(url, factory, options) {
1047
1298
  const browser = typeof window !== "undefined";
1048
1299
  const existing = browser ? cache.get(url) : void 0;
1049
1300
  if (existing) return existing;
1050
- const client = (factory ?? getDefaultClientFactory())(url);
1301
+ const f = factory ?? getDefaultClientFactory();
1302
+ let client;
1303
+ if (!browser) client = f(url, { metaStore: false });
1304
+ else if (options?.metaKey) client = f(url, { metaKey: options.metaKey });
1305
+ else client = f(url);
1306
+ if (browser) rememberStore(client);
1051
1307
  const meta = client.meta().catch((err) => {
1052
1308
  if (cache.get(url) === entry) cache.delete(url);
1053
1309
  throw err;
1054
1310
  });
1311
+ const derived = meta.then((m) => derive(client, m, browser));
1312
+ const type = derived.then((d) => d.type);
1313
+ type.catch(() => {});
1055
1314
  const entry = {
1056
1315
  client,
1057
1316
  meta,
1058
- type: meta.then((m) => (0, _atscript_typescript_utils.deserializeAnnotatedType)(m.type))
1317
+ type
1059
1318
  };
1319
+ derivedOf.set(entry, derived);
1060
1320
  if (browser) cache.set(url, entry);
1061
1321
  return entry;
1062
1322
  }
1063
1323
  /**
1324
+ * The `TableDef` for a cache entry, built once per entry — and once per
1325
+ * `/meta` `ETag` across entries. Since 0.1.153.
1326
+ */
1327
+ function getMetaTableDef(entry) {
1328
+ if (!entry.tableDef) {
1329
+ const derived = derivedOf.get(entry);
1330
+ 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
+ }
1332
+ return entry.tableDef;
1333
+ }
1334
+ function derive(client, meta, browser) {
1335
+ const etag = browser ? client.metaEtag?.() : void 0;
1336
+ 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;
1342
+ }
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;
1347
+ }
1348
+ /**
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.
1353
+ */
1354
+ function rememberStore(client) {
1355
+ const store = client._metaStore;
1356
+ if (typeof store?.clear === "function") customStores.add(store);
1357
+ }
1358
+ /**
1064
1359
  * Drop every cached `/meta` — including the copy each cached `Client`
1065
- * memoizes — and the value-help searches shared under them. Entries already
1360
+ * memoizes and the `@atscript/db-client` meta stores used to revalidate it
1361
+ * (the shared default one and any custom one a factory supplied) — the
1362
+ * value-help searches shared under them, and everything registered through
1363
+ * {@link onMetaCacheReset} (e.g. the table-presets cache). Entries already
1066
1364
  * handed out keep working; the next `getMetaEntry` refetches.
1067
1365
  */
1068
1366
  function resetMetaCache() {
1069
1367
  const entries = [...cache.values()];
1070
1368
  cache.clear();
1369
+ derivedByEtag.clear();
1071
1370
  for (const entry of entries) entry.client.invalidateMeta?.();
1371
+ (0, _atscript_db_client.clearMetaStore)();
1372
+ for (const store of customStores) store.clear();
1373
+ customStores.clear();
1072
1374
  invalidateValueHelpCache();
1375
+ for (const listener of resetListeners) listener();
1073
1376
  }
1074
1377
  /**
1075
1378
  * Bind the meta cache to the current viewer. Call it whenever the signed-in
@@ -1077,6 +1380,9 @@ function resetMetaCache() {
1077
1380
  * every reload of the current user. A key that differs from the previous
1078
1381
  * one resets the cache (`resetMetaCache`); the same key keeps it. `null` /
1079
1382
  * `undefined` = anonymous.
1383
+ *
1384
+ * Binding an identity also turns on caches that are only safe when the app
1385
+ * reports sign-in changes, such as the table-presets cache.
1080
1386
  */
1081
1387
  function setMetaCacheIdentity(key) {
1082
1388
  const next = key ?? null;
@@ -1084,6 +1390,24 @@ function setMetaCacheIdentity(key) {
1084
1390
  identity = next;
1085
1391
  resetMetaCache();
1086
1392
  }
1393
+ /**
1394
+ * The identity last passed to {@link setMetaCacheIdentity}: `undefined` when
1395
+ * the app never bound one, `null` for anonymous. Since 0.1.153.
1396
+ */
1397
+ function getMetaCacheIdentity() {
1398
+ return identity;
1399
+ }
1400
+ /**
1401
+ * Run `listener` on every {@link resetMetaCache} (and so on every identity
1402
+ * change). For caches that belong to the signed-in viewer. Returns an
1403
+ * unsubscribe function. Since 0.1.153.
1404
+ */
1405
+ function onMetaCacheReset(listener) {
1406
+ resetListeners.add(listener);
1407
+ return () => {
1408
+ resetListeners.delete(listener);
1409
+ };
1410
+ }
1087
1411
  //#endregion
1088
1412
  //#region src/value-help/resolve.ts
1089
1413
  /**
@@ -2227,23 +2551,6 @@ function resolveSingularLabel(meta) {
2227
2551
  return getFieldMeta(meta, "ui.form.label.singular") || "item";
2228
2552
  }
2229
2553
  //#endregion
2230
- //#region src/form/measurement.ts
2231
- /**
2232
- * Read measurement annotations off a single field prop. Returns `undefined`
2233
- * for any annotation that's absent — callers can spread the result into a
2234
- * larger record.
2235
- */
2236
- function extractMeasurement(prop) {
2237
- const precisionMeta = getFieldMeta(prop, DB_COLUMN_PRECISION);
2238
- return {
2239
- currencyCode: getFieldMeta(prop, DB_AMOUNT_CURRENCY),
2240
- currencyRefField: getFieldMeta(prop, DB_AMOUNT_CURRENCY_REF),
2241
- unitCode: getFieldMeta(prop, DB_UNIT),
2242
- unitRefField: getFieldMeta(prop, DB_UNIT_REF),
2243
- precisionScale: precisionMeta?.scale
2244
- };
2245
- }
2246
- //#endregion
2247
2554
  //#region src/form/decimal-format.ts
2248
2555
  const WHITESPACE_GROUP_RE = /[   ]/g;
2249
2556
  const numberFormatCache = /* @__PURE__ */ new Map();
@@ -2558,231 +2865,6 @@ function groupInteger(integer, locale) {
2558
2865
  return out.join(sep);
2559
2866
  }
2560
2867
  //#endregion
2561
- //#region src/table/create-table-def.ts
2562
- /**
2563
- * Builds a TableDef from a moost-db MetaResponse.
2564
- *
2565
- * 1. Deserializes `meta.type` into a live TAtscriptAnnotatedType
2566
- * 2. Flattens to discover all field paths
2567
- * 3. Builds ColumnDef per field using annotations + meta.fields capabilities
2568
- * 4. Sorts by @ui.table.order
2569
- */
2570
- function createTableDef(meta, preDeserializedType) {
2571
- const type = preDeserializedType ?? (0, _atscript_typescript_utils.deserializeAnnotatedType)(meta.type);
2572
- const flatMap = type.type.kind === "object" ? (0, _atscript_typescript_utils.flattenAnnotatedType)(type, { excludePhantomTypes: true }) : /* @__PURE__ */ new Map();
2573
- const columns = [];
2574
- for (const [path, prop] of flatMap.entries()) {
2575
- if (path === "") continue;
2576
- if (path === meta.versionColumn) continue;
2577
- const fieldMeta = meta.fields[path];
2578
- if (!isReadable(fieldMeta)) continue;
2579
- if (getFieldMeta(prop, "ui.table.exclude") !== void 0) continue;
2580
- const options = extractFieldLiteralOptions(prop);
2581
- const valueHelpInfo = extractValueHelp(prop);
2582
- let distinct;
2583
- if (!valueHelpInfo && !options && fieldMeta.groupable && fieldMeta.filterable) {
2584
- const url = type.metadata.get(DB_HTTP_PATH);
2585
- if (url && getFieldMeta(prop, "ui.valueHelp.distinct") !== void 0) distinct = {
2586
- url,
2587
- field: path
2588
- };
2589
- }
2590
- columns.push(buildColumn(path, prop, fieldMeta, {
2591
- options,
2592
- valueHelpInfo,
2593
- distinct
2594
- }));
2595
- }
2596
- if (meta.decorations) {
2597
- const decoType = (0, _atscript_typescript_utils.deserializeAnnotatedType)(meta.decorations);
2598
- if (decoType.type.kind === "object") for (const [path, prop] of decoType.type.props) {
2599
- const fieldMeta = meta.fields[path];
2600
- if (!fieldMeta?.decoration || flatMap.has(path)) continue;
2601
- if (getFieldMeta(prop, "ui.table.exclude") !== void 0) continue;
2602
- flatMap.set(path, prop);
2603
- columns.push(buildColumn(path, prop, fieldMeta, { options: extractFieldLiteralOptions(prop) }));
2604
- }
2605
- }
2606
- columns.sort((a, b) => a.order - b.order);
2607
- const actions = groupActions(meta.actions ?? []);
2608
- const crud = meta.crud ?? {};
2609
- const preferredId = meta.preferredId ?? meta.primaryKeys;
2610
- return {
2611
- type,
2612
- columns,
2613
- flatMap,
2614
- fetchableFields: new Set(Object.keys(meta.fields).filter((p) => isReadable(meta.fields[p]))),
2615
- primaryKeys: meta.primaryKeys,
2616
- preferredId,
2617
- identifierFields: identifierFieldsOf(preferredId, meta.actions ?? []),
2618
- versionColumn: meta.versionColumn,
2619
- crud,
2620
- canRemove: "remove" in crud,
2621
- actions,
2622
- searchable: meta.searchable,
2623
- vectorSearchable: meta.vectorSearchable,
2624
- searchIndexes: meta.searchIndexes,
2625
- relations: meta.relations
2626
- };
2627
- }
2628
- /**
2629
- * One column. A server-declared display-only column (`fieldMeta.decoration`)
2630
- * is never sortable, filterable or groupable and always nullable (a decoration
2631
- * can be absent); an ordinary one takes its capabilities from `/meta`.
2632
- */
2633
- function buildColumn(path, prop, fieldMeta, resolved) {
2634
- const { options, valueHelpInfo, distinct } = resolved;
2635
- const maxLengthMeta = getFieldMeta(prop, EXPECT_MAX_LENGTH);
2636
- const tableType = getFieldMeta(prop, UI_TABLE_TYPE);
2637
- const sharedType = getFieldMeta(prop, UI_TYPE);
2638
- const tableComponent = getFieldMeta(prop, UI_TABLE_COMPONENT);
2639
- const decoration = fieldMeta.decoration === true;
2640
- const filterOps = decoration ? void 0 : fieldMeta.filterOps;
2641
- return {
2642
- path,
2643
- label: getFieldMeta(prop, "meta.label") ?? humanizePath(path),
2644
- type: tableType ?? sharedType ?? (valueHelpInfo ? "ref" : inferDisplayType(prop, options)),
2645
- valueKind: inferValueKind(prop),
2646
- component: tableComponent,
2647
- selectWith: getFieldMeta(prop, UI_TABLE_SELECT_WITH),
2648
- sortable: !decoration && (fieldMeta.sortable ?? false),
2649
- filterable: !decoration && (fieldMeta.filterable ?? false),
2650
- ...filterOps && { filterOps: [...filterOps] },
2651
- nullable: decoration || prop.optional === true,
2652
- width: getFieldMeta(prop, UI_TABLE_WIDTH),
2653
- maxLen: maxLengthMeta?.length,
2654
- order: getFieldMeta(prop, "ui.table.order") ?? Infinity,
2655
- options,
2656
- valueHelpInfo,
2657
- ...distinct && { distinct },
2658
- ...extractMeasurement(prop)
2659
- };
2660
- }
2661
- /**
2662
- * `preferredId` ∪ every delegated action's `idMap` paths, in that order —
2663
- * the same array when no action carries an `idMap`.
2664
- */
2665
- function identifierFieldsOf(preferredId, actions) {
2666
- let out;
2667
- for (const a of actions) {
2668
- if (!a.idMap) continue;
2669
- for (const path of Object.values(a.idMap)) {
2670
- if (preferredId.includes(path) || out?.includes(path)) continue;
2671
- (out ??= [...preferredId]).push(path);
2672
- }
2673
- }
2674
- return out ?? preferredId;
2675
- }
2676
- /** A field the caller may read: listed in `meta.fields` and not write-only. */
2677
- function isReadable(field) {
2678
- return field !== void 0 && field.writeOnly !== true;
2679
- }
2680
- /** Sort by (order ?? 0). `toSorted` is stable per spec, so ties preserve declaration order. */
2681
- function byOrder(xs) {
2682
- return xs.toSorted((x, y) => (x.order ?? 0) - (y.order ?? 0));
2683
- }
2684
- /**
2685
- * Partition actions by `level`, sort each group by `(order ?? 0)` then
2686
- * declaration order, and pick the first `default: true` entry per level.
2687
- * The synthesised `__remove` UI action lives outside this set and is never
2688
- * a candidate for `default.row`.
2689
- */
2690
- function groupActions(actions) {
2691
- const table = [];
2692
- const row = [];
2693
- const rows = [];
2694
- for (const a of actions) if (a.level === "table") table.push(a);
2695
- else if (a.level === "row") row.push(a);
2696
- else if (a.level === "rows") rows.push(a);
2697
- const tableSorted = byOrder(table);
2698
- const rowSorted = byOrder(row);
2699
- const rowsSorted = byOrder(rows);
2700
- return {
2701
- table: tableSorted,
2702
- row: rowSorted,
2703
- rows: rowsSorted,
2704
- default: {
2705
- table: tableSorted.find((a) => a.default === true),
2706
- row: rowSorted.find((a) => a.default === true),
2707
- rows: rowsSorted.find((a) => a.default === true)
2708
- }
2709
- };
2710
- }
2711
- /** Infers a display type string from the annotated type's kind and designType. */
2712
- function inferDisplayType(prop, literalOpts) {
2713
- const kind = prop.type.kind;
2714
- if (kind === "array") return "array";
2715
- if (kind === "object") return "object";
2716
- if (kind === "union") return literalOpts !== void 0 ? "enum" : "union";
2717
- if (kind === "") {
2718
- const final = prop.type;
2719
- const dt = final.designType;
2720
- if (dt === "number") return final.tags?.has("timestamp") ? "datetime" : "number";
2721
- if (dt === "decimal") return "number";
2722
- if (dt === "boolean") return "boolean";
2723
- return "text";
2724
- }
2725
- return "text";
2726
- }
2727
- /**
2728
- * Number metadata that makes the server treat a plain `number` column as an
2729
- * integer (mirrors the db layer's `valueTypeOf`), beside the `int` / `expect.int` tags.
2730
- */
2731
- const INTEGER_NUMBER_META = [
2732
- "expect.int",
2733
- "db.default.increment",
2734
- "db.default.now",
2735
- "db.agg.count",
2736
- "db.agg.countDistinct"
2737
- ];
2738
- /** The kind of one scalar leaf, or `undefined` for a non-scalar / unknown design type. */
2739
- function scalarValueKind(prop) {
2740
- const final = prop.type;
2741
- const tags = final.tags;
2742
- switch (final.designType) {
2743
- case "string": return tags?.has("isoDate") ? "isoDate" : tags?.has("date") ? "date" : "string";
2744
- case "number":
2745
- if (tags?.has("timestamp")) return "timestamp";
2746
- if (tags?.has("int") || INTEGER_NUMBER_META.some((k) => prop.metadata.has(k))) return "integer";
2747
- return "number";
2748
- case "decimal": return "decimal";
2749
- case "boolean": return "boolean";
2750
- default: return;
2751
- }
2752
- }
2753
- /** Kinds of every non-null leaf of a (possibly nested) union; `null` when one is not a scalar. */
2754
- function collectUnionKinds(items, out) {
2755
- for (const item of items) {
2756
- if (item.type.kind === "union") {
2757
- collectUnionKinds(item.type.items, out);
2758
- continue;
2759
- }
2760
- if (item.type.kind === "") {
2761
- const dt = item.type.designType;
2762
- if (dt === "null" || dt === "undefined") continue;
2763
- out.add(scalarValueKind(item));
2764
- continue;
2765
- }
2766
- out.add(void 0);
2767
- }
2768
- }
2769
- /**
2770
- * Scalar storage kind of the column's value — what the server's filter guard
2771
- * checks. A scalar maps to its kind; a union that agrees on one kind across
2772
- * its non-null members (`'a' | 'b'`, `1 | 2`, `number.timestamp | null`)
2773
- * takes it; arrays, objects, JSON and mixed unions have none (`undefined`),
2774
- * which means no value coercion.
2775
- */
2776
- function inferValueKind(prop) {
2777
- const kind = prop.type.kind;
2778
- if (kind === "") return scalarValueKind(prop);
2779
- if (kind !== "union") return void 0;
2780
- const kinds = /* @__PURE__ */ new Set();
2781
- collectUnionKinds(prop.type.items, kinds);
2782
- if (kinds.size !== 1) return void 0;
2783
- return [...kinds][0];
2784
- }
2785
- //#endregion
2786
2868
  //#region src/table/value-kind.ts
2787
2869
  /** Storage kinds that hold plain numbers (a `timestamp` is epoch ms, but filters treat it as a date). */
2788
2870
  const NUMERIC_VALUE_KINDS = new Set([
@@ -3035,7 +3117,9 @@ exports.getDefaultValidatorPlugins = getDefaultValidatorPlugins;
3035
3117
  exports.getFieldMeta = getFieldMeta;
3036
3118
  exports.getFilterableColumns = getFilterableColumns;
3037
3119
  exports.getFormValidator = getFormValidator;
3120
+ exports.getMetaCacheIdentity = getMetaCacheIdentity;
3038
3121
  exports.getMetaEntry = getMetaEntry;
3122
+ exports.getMetaTableDef = getMetaTableDef;
3039
3123
  exports.getResolver = getResolver;
3040
3124
  exports.getSortableColumns = getSortableColumns;
3041
3125
  exports.getThousandsSeparator = getThousandsSeparator;
@@ -3057,6 +3141,7 @@ exports.joinPath = joinPath;
3057
3141
  exports.mergeErrorMaps = mergeErrorMaps;
3058
3142
  exports.navigateHrefFor = navigateHrefFor;
3059
3143
  exports.omitPaths = omitPaths;
3144
+ exports.onMetaCacheReset = onMetaCacheReset;
3060
3145
  exports.optKey = optKey;
3061
3146
  exports.optLabel = optLabel;
3062
3147
  exports.optionLabel = optionLabel;