@atscript/ui 0.1.174 → 0.1.176

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.
@@ -15,10 +15,10 @@ const require_path_utils = require("./path-utils.cjs");
15
15
  *
16
16
  * - `kind: 'set'`:
17
17
  * - `change.after === undefined` → DELETE the own key at `change.path` (walk
18
- * to parent, `delete`). A cleared field must read as ABSENT, not as a
19
- * present `undefined` own-key — otherwise a re-diff sees a structural
20
- * mismatch where the form intends "no value". `setByPath(…, undefined)`
21
- * leaves an own key behind, so we use {@link deleteByPath} instead.
18
+ * to parent, `delete`). A cleared field reads as ABSENT, not as a present
19
+ * `undefined` own-key, so the data holds the same keys as data that never
20
+ * had the field. `setByPath(…, undefined)` leaves an own key behind, so we
21
+ * use {@link deleteByPath} instead.
22
22
  * - otherwise → `setByPath(data, change.path, change.after)`.
23
23
  * - `kind: 'array'`: whole-array set via `setByPath(data, change.path,
24
24
  * change.after)` (LOCKED Option A — no per-element merge; the diff already
@@ -17,10 +17,10 @@ import { FormFieldChange } from "./diff.cjs";
17
17
  *
18
18
  * - `kind: 'set'`:
19
19
  * - `change.after === undefined` → DELETE the own key at `change.path` (walk
20
- * to parent, `delete`). A cleared field must read as ABSENT, not as a
21
- * present `undefined` own-key — otherwise a re-diff sees a structural
22
- * mismatch where the form intends "no value". `setByPath(…, undefined)`
23
- * leaves an own key behind, so we use {@link deleteByPath} instead.
20
+ * to parent, `delete`). A cleared field reads as ABSENT, not as a present
21
+ * `undefined` own-key, so the data holds the same keys as data that never
22
+ * had the field. `setByPath(…, undefined)` leaves an own key behind, so we
23
+ * use {@link deleteByPath} instead.
24
24
  * - otherwise → `setByPath(data, change.path, change.after)`.
25
25
  * - `kind: 'array'`: whole-array set via `setByPath(data, change.path,
26
26
  * change.after)` (LOCKED Option A — no per-element merge; the diff already
@@ -17,10 +17,10 @@ import { FormFieldChange } from "./diff.mjs";
17
17
  *
18
18
  * - `kind: 'set'`:
19
19
  * - `change.after === undefined` → DELETE the own key at `change.path` (walk
20
- * to parent, `delete`). A cleared field must read as ABSENT, not as a
21
- * present `undefined` own-key — otherwise a re-diff sees a structural
22
- * mismatch where the form intends "no value". `setByPath(…, undefined)`
23
- * leaves an own key behind, so we use {@link deleteByPath} instead.
20
+ * to parent, `delete`). A cleared field reads as ABSENT, not as a present
21
+ * `undefined` own-key, so the data holds the same keys as data that never
22
+ * had the field. `setByPath(…, undefined)` leaves an own key behind, so we
23
+ * use {@link deleteByPath} instead.
24
24
  * - otherwise → `setByPath(data, change.path, change.after)`.
25
25
  * - `kind: 'array'`: whole-array set via `setByPath(data, change.path,
26
26
  * change.after)` (LOCKED Option A — no per-element merge; the diff already
@@ -15,10 +15,10 @@ import { deleteByPath, setByPath } from "./path-utils.mjs";
15
15
  *
16
16
  * - `kind: 'set'`:
17
17
  * - `change.after === undefined` → DELETE the own key at `change.path` (walk
18
- * to parent, `delete`). A cleared field must read as ABSENT, not as a
19
- * present `undefined` own-key — otherwise a re-diff sees a structural
20
- * mismatch where the form intends "no value". `setByPath(…, undefined)`
21
- * leaves an own key behind, so we use {@link deleteByPath} instead.
18
+ * to parent, `delete`). A cleared field reads as ABSENT, not as a present
19
+ * `undefined` own-key, so the data holds the same keys as data that never
20
+ * had the field. `setByPath(…, undefined)` leaves an own key behind, so we
21
+ * use {@link deleteByPath} instead.
22
22
  * - otherwise → `setByPath(data, change.path, change.after)`.
23
23
  * - `kind: 'array'`: whole-array set via `setByPath(data, change.path,
24
24
  * change.after)` (LOCKED Option A — no per-element merge; the diff already
@@ -182,8 +182,15 @@ function diffObjectField(field, fullPath, baseline, current, changes, patch) {
182
182
  const afterObj = require_path_utils.getByPath(current, fullPath);
183
183
  if (!require_path_utils.isPlainObject(beforeObj) && !require_path_utils.isPlainObject(afterObj)) return;
184
184
  const nested = {};
185
+ const changesBefore = changes.length;
185
186
  diffFields(field.objectDef.fields, fullPath, baseline, current, changes, nested, void 0, field.objectDef.flatMap);
186
187
  if ((afterObj === void 0 || afterObj === null) && require_path_utils.isPlainObject(beforeObj)) {
188
+ if (changes.length === changesBefore) changes.push({
189
+ path: fullPath,
190
+ kind: "set",
191
+ before: beforeObj,
192
+ after: afterObj
193
+ });
187
194
  setPatchLeaf(patch, field.path, null);
188
195
  return;
189
196
  }
@@ -192,9 +199,10 @@ function diffObjectField(field, fullPath, baseline, current, changes, patch) {
192
199
  else setPatchLeaf(patch, field.path, afterObj === void 0 ? null : afterObj);
193
200
  }
194
201
  /**
195
- * Whether an object's patch may carry only its changed leaves: a
196
- * `@db.patch.strategy 'merge'` object that is not `@db.json` (a JSON value is
197
- * stored, and so replaced, whole).
202
+ * Whether a field's patch may carry only its changed leaves: a
203
+ * `@db.patch.strategy 'merge'` field that is not `@db.json` (a JSON value is
204
+ * stored, and so replaced, whole). For an object field this decides the nested
205
+ * partial; for a keyed array field, the shape of its `$update` items.
198
206
  */
199
207
  function isMergePatched(prop) {
200
208
  return require_field_resolver.getFieldMeta(prop, "db.patch.strategy") === "merge" && require_field_resolver.getFieldMeta(prop, "db.json") === void 0;
@@ -225,12 +233,9 @@ function diffArrayField(field, fullPath, baseline, current, changes, patch, inli
225
233
  * Produces a `TArrayPatch` value for one array field, or `undefined` when no
226
234
  * real op results (the caller then skips the field entirely).
227
235
  *
228
- * - Keyed arrays (item object has `@expect.array.key`): emit `$update`
229
- * (key + changed leaves), `$insert` (wholly-new items, whole), `$remove`
230
- * (key only). Reorder-only (same key membership, same content, different
231
- * order) → `$replace` (key-ops can't express a pure reorder).
232
- * Ambiguous keys (duplicate or missing key values) → `$replace` (the only
233
- * faithful op when key identity is unreliable).
236
+ * - Keyed arrays (item object has `@expect.array.key`): `$update` / `$insert`
237
+ * / `$remove` when those operators reproduce the form's array, else
238
+ * `$replace` — see {@link diffKeyedArray}.
234
239
  * - Unkeyed object arrays / primitive arrays: `$replace` with the whole array.
235
240
  * Primitive arrays with `@expect.array.uniqueItems` use by-value
236
241
  * `$insert` / `$remove` (set semantics).
@@ -244,7 +249,7 @@ function diffArray(field, before, after) {
244
249
  const beforeArr = Array.isArray(before) ? before : [];
245
250
  const afterArr = Array.isArray(after) ? after : [];
246
251
  const keyProps = getArrayKeyProps(field.itemType);
247
- if (keyProps.length > 0) return diffKeyedArray(beforeArr, afterArr, keyProps);
252
+ if (keyProps.length > 0) return diffKeyedArray(beforeArr, afterArr, keyProps, isMergePatched(field.prop));
248
253
  if (require_field_resolver.getFieldMeta(field.prop, "expect.array.uniqueItems") !== void 0 && isPrimitiveItem(field)) {
249
254
  const setPatch = diffUniqueArray(beforeArr, afterArr);
250
255
  if (setPatch) return setPatch;
@@ -252,51 +257,81 @@ function diffArray(field, before, after) {
252
257
  return { $replace: afterArr };
253
258
  }
254
259
  /**
255
- * Keyed array diff. Reorder-only (same membership) falls back to $replace.
260
+ * Keyed array diff: `$update` / `$insert` / `$remove` when those operators
261
+ * reproduce the form's array, else `{ $replace: after }`. Returns `undefined`
262
+ * when nothing changed (same order, no op), so the caller skips the field
263
+ * rather than emitting a malformed empty `{}`.
264
+ *
265
+ * Order: the db applies the operators remove → update (in place) → insert
266
+ * (appended, in item order), so the array it ends with holds the baseline
267
+ * elements whose key is still present, in baseline order, followed by the
268
+ * `$insert` items. When that key sequence differs from the form's, the
269
+ * operators cannot express the form state and `$replace` is the only faithful
270
+ * patch — a reorder, a new row placed before an existing one, an edited key on
271
+ * a row that is not last (its remove + insert would move it to the end), a row
272
+ * removed and re-added under the same key elsewhere. A new row appended at the
273
+ * end and an edited key on the last row stay key operators.
256
274
  *
257
- * Returns `undefined` when no $update/$insert/$remove op is produced (so the
258
- * caller skips the field rather than emitting a malformed empty `{}`).
275
+ * A `$update` item follows the array field's `@db.patch.strategy` (`merge` is
276
+ * whether it is `'merge'`), which the db applies to it: by default (replace)
277
+ * the db replaces the matched element, so the item is the whole current
278
+ * element minus its `undefined`-valued props; under `merge` the db shallow-
279
+ * merges the item in, so it is the key + the changed top-level leaves (a
280
+ * changed nested object whole), a cleared leaf as `null`
281
+ * ({@link buildKeyedUpdate}). Either way an item is emitted only when some
282
+ * leaf changed.
259
283
  *
260
- * Ambiguity fallback: if either side has DUPLICATE key buckets, or ANY element
261
- * is missing all of its key values, key identity is unreliable — fall back to
262
- * `{ $replace: after }`, the only faithful op (last-write-wins collapse would
263
- * silently drop items, and a key-less `$update` is unmatchable by the DB).
284
+ * Fallbacks to `{ $replace: after }`, the only faithful op, when:
285
+ * - key identity is ambiguous — an element that is not an object or lacks ALL
286
+ * of its key values, or a key shared by two elements on one side (a
287
+ * last-write-wins collapse would silently drop items);
288
+ * - an element a key operator would name (a `$update`, `$remove` or `$insert`
289
+ * item) lacks ANY of its key values (`undefined` / `null`): the db refuses
290
+ * such an item (`PATCH_KEY_REQUIRED` for `$update` / `$remove`), while under
291
+ * `$replace` it validates the array and reports the missing field on its
292
+ * own path. An untouched row with an incomplete key names no operator, so
293
+ * it does not turn an unrelated edit into a `$replace`.
264
294
  */
265
- function diffKeyedArray(before, after, keyProps) {
266
- if (hasKeylessItem(before, keyProps) || hasKeylessItem(after, keyProps)) return { $replace: after };
267
- const beforeByKey = /* @__PURE__ */ new Map();
268
- for (const el of before) if (require_path_utils.isPlainObject(el)) beforeByKey.set(keyOf(el, keyProps), el);
269
- const afterByKey = /* @__PURE__ */ new Map();
270
- for (const el of after) if (require_path_utils.isPlainObject(el)) afterByKey.set(keyOf(el, keyProps), el);
271
- if (beforeByKey.size !== before.length || afterByKey.size !== after.length) return { $replace: after };
272
- const $insert = [];
295
+ function diffKeyedArray(before, after, keyProps, merge) {
296
+ const beforeByKey = byKey(before, keyProps);
297
+ const afterByKey = byKey(after, keyProps);
298
+ if (!beforeByKey || !afterByKey) return { $replace: after };
299
+ const incomplete = (el) => keyProps.some((k) => el[k] === void 0 || el[k] === null);
300
+ const afterKeys = [...afterByKey.keys()];
273
301
  const $update = [];
274
302
  const $remove = [];
275
- let contentChanged = false;
276
- for (const [k, el] of afterByKey) {
277
- const prev = beforeByKey.get(k);
278
- if (prev === void 0) {
279
- $insert.push(el);
303
+ let kept = 0;
304
+ for (const [k, prev] of beforeByKey) {
305
+ const el = afterByKey.get(k);
306
+ if (el === void 0) {
307
+ if (incomplete(prev)) return { $replace: after };
308
+ $remove.push(pickKeys(prev, keyProps));
280
309
  continue;
281
310
  }
282
- if (!deepEqual(prev, el)) {
283
- contentChanged = true;
284
- const partial = buildKeyedUpdate(prev, el, keyProps);
285
- if (partial) $update.push(partial);
286
- }
311
+ if (afterKeys[kept++] !== k) return { $replace: after };
312
+ if (deepEqual(prev, el)) continue;
313
+ const partial = buildKeyedUpdate(prev, el, keyProps);
314
+ if (!partial) continue;
315
+ if (incomplete(el)) return { $replace: after };
316
+ $update.push(merge ? partial : definedProps(el));
287
317
  }
288
- if (beforeByKey.size === afterByKey.size && $insert.length === 0 && !contentChanged) return { $replace: after };
289
- for (const [k, el] of beforeByKey) if (!afterByKey.has(k)) $remove.push(pickKeys(el, keyProps));
318
+ const $insert = afterKeys.slice(kept).map((k) => afterByKey.get(k));
319
+ if ($insert.some(incomplete)) return { $replace: after };
290
320
  return arrayOps({
291
321
  $update,
292
322
  $insert,
293
323
  $remove
294
324
  });
295
325
  }
296
- /** Builds a `$update` partial: key fields + changed leaves only. */
326
+ /**
327
+ * Builds a `$update` partial: key fields + changed leaves only (a cleared leaf
328
+ * as `null`), or `undefined` when no leaf changed. A leaf is a top-level prop
329
+ * of the element, compared by value: an explicit `undefined`-valued prop
330
+ * equals an absent one, and a changed nested object is sent whole (the db
331
+ * merges an item one level deep).
332
+ */
297
333
  function buildKeyedUpdate(prev, next, keyProps) {
298
- const partial = {};
299
- for (const k of keyProps) partial[k] = next[k];
334
+ const partial = pickKeys(next, keyProps);
300
335
  let changed = false;
301
336
  const allKeys = new Set([...Object.keys(prev), ...Object.keys(next)]);
302
337
  for (const k of allKeys) {
@@ -310,6 +345,15 @@ function buildKeyedUpdate(prev, next, keyProps) {
310
345
  }
311
346
  return changed ? partial : void 0;
312
347
  }
348
+ /**
349
+ * Shallow copy of `el` without its `undefined`-valued own props (top level
350
+ * only; nested values are kept by reference).
351
+ */
352
+ function definedProps(el) {
353
+ const out = {};
354
+ for (const k of Object.keys(el)) if (el[k] !== void 0) out[k] = el[k];
355
+ return out;
356
+ }
313
357
  /** Primitive uniqueItems set diff. Returns undefined if neither side differs. */
314
358
  function diffUniqueArray(before, after) {
315
359
  const beforeSet = new Set(before.map((v) => stableKey(v)));
@@ -359,26 +403,29 @@ function getArrayKeyProps(itemType) {
359
403
  function isPrimitiveItem(field) {
360
404
  return field.itemType.type.kind === "";
361
405
  }
362
- /** True when any element lacks ALL of its key values (un-keyable identity). */
363
- function hasKeylessItem(arr, keyProps) {
406
+ /**
407
+ * The elements by {@link keyOf} bucket, or `undefined` when key identity is
408
+ * ambiguous: an element is not an object or lacks ALL of its key values
409
+ * (`undefined` / `null`), or two elements share a key (a Map collapse would
410
+ * silently lose one).
411
+ */
412
+ function byKey(arr, keyProps) {
413
+ const map = /* @__PURE__ */ new Map();
364
414
  for (const el of arr) {
365
- if (!require_path_utils.isPlainObject(el)) return true;
366
- let hasAnyKey = false;
367
- for (const k of keyProps) {
368
- const v = el[k];
369
- if (v !== void 0 && v !== null) {
370
- hasAnyKey = true;
371
- break;
372
- }
373
- }
374
- if (!hasAnyKey) return true;
415
+ if (!require_path_utils.isPlainObject(el) || keyProps.every((k) => el[k] === void 0 || el[k] === null)) return;
416
+ map.set(keyOf(el, keyProps), el);
375
417
  }
376
- return false;
418
+ return map.size === arr.length ? map : void 0;
377
419
  }
378
- /** Composite key string for a keyed-array element. */
420
+ /**
421
+ * Bucket string for a keyed-array element's key values, type-strict like
422
+ * {@link stableKey}. A composite key is the JSON array of its tagged values,
423
+ * so no two different key tuples share a bucket (a joined string would: the
424
+ * values may contain the separator).
425
+ */
379
426
  function keyOf(el, keyProps) {
380
427
  if (keyProps.length === 1) return stableKey(el[keyProps[0]]);
381
- return keyProps.map((k) => stableKey(el[k])).join(" ");
428
+ return JSON.stringify(keyProps.map((k) => stableKey(el[k])));
382
429
  }
383
430
  /** Picks only the key fields from an element (for $remove). */
384
431
  function pickKeys(el, keyProps) {
@@ -425,14 +472,20 @@ function stableKey(v) {
425
472
  * (revert-aware for NaN scalars) while `0` / `-0` stay equal (matches DB
426
473
  * intent — `===` treats them equal, only NaN is special-cased).
427
474
  *
475
+ * Unset is one value: `null`, `undefined` and an absent object prop are equal
476
+ * at any depth — a field loaded as `null` (SQL `NULL`) that the form holds as
477
+ * `undefined`, or an optional prop emptied to `undefined` in an array row, is
478
+ * unchanged. The patch cannot tell them apart either: it sends a cleared value
479
+ * as `null`.
480
+ *
428
481
  * The single comparator shared across the form engine: diff, conflict
429
482
  * detection ({@link buildFormRebase}), and apply all route through this — never
430
483
  * reimplement equality elsewhere.
431
484
  */
432
485
  function deepEqual(a, b) {
433
486
  if (a === b) return true;
487
+ if (a === null || a === void 0 || b === null || b === void 0) return (a === null || a === void 0) && (b === null || b === void 0);
434
488
  if (typeof a === "number" && typeof b === "number") return Number.isNaN(a) && Number.isNaN(b);
435
- if (a === null || b === null || a === void 0 || b === void 0) return false;
436
489
  if (typeof a !== "object" || typeof b !== "object") return false;
437
490
  const aIsArr = Array.isArray(a);
438
491
  const bIsArr = Array.isArray(b);
@@ -444,13 +497,8 @@ function deepEqual(a, b) {
444
497
  }
445
498
  const ao = a;
446
499
  const bo = b;
447
- const aKeys = Object.keys(ao);
448
- const bKeys = Object.keys(bo);
449
- if (aKeys.length !== bKeys.length) return false;
450
- for (const k of aKeys) {
451
- if (!Object.prototype.hasOwnProperty.call(bo, k)) return false;
452
- if (!deepEqual(ao[k], bo[k])) return false;
453
- }
500
+ for (const k of Object.keys(ao)) if (!deepEqual(ao[k], Object.hasOwn(bo, k) ? bo[k] : void 0)) return false;
501
+ for (const k of Object.keys(bo)) if (!Object.hasOwn(ao, k) && bo[k] !== void 0 && bo[k] !== null) return false;
454
502
  return true;
455
503
  }
456
504
  //#endregion
@@ -71,6 +71,12 @@ declare function buildFormDiff(def: FormDef, baseline: Record<string, unknown>,
71
71
  * (revert-aware for NaN scalars) while `0` / `-0` stay equal (matches DB
72
72
  * intent — `===` treats them equal, only NaN is special-cased).
73
73
  *
74
+ * Unset is one value: `null`, `undefined` and an absent object prop are equal
75
+ * at any depth — a field loaded as `null` (SQL `NULL`) that the form holds as
76
+ * `undefined`, or an optional prop emptied to `undefined` in an array row, is
77
+ * unchanged. The patch cannot tell them apart either: it sends a cleared value
78
+ * as `null`.
79
+ *
74
80
  * The single comparator shared across the form engine: diff, conflict
75
81
  * detection ({@link buildFormRebase}), and apply all route through this — never
76
82
  * reimplement equality elsewhere.
@@ -71,6 +71,12 @@ declare function buildFormDiff(def: FormDef, baseline: Record<string, unknown>,
71
71
  * (revert-aware for NaN scalars) while `0` / `-0` stay equal (matches DB
72
72
  * intent — `===` treats them equal, only NaN is special-cased).
73
73
  *
74
+ * Unset is one value: `null`, `undefined` and an absent object prop are equal
75
+ * at any depth — a field loaded as `null` (SQL `NULL`) that the form holds as
76
+ * `undefined`, or an optional prop emptied to `undefined` in an array row, is
77
+ * unchanged. The patch cannot tell them apart either: it sends a cleared value
78
+ * as `null`.
79
+ *
74
80
  * The single comparator shared across the form engine: diff, conflict
75
81
  * detection ({@link buildFormRebase}), and apply all route through this — never
76
82
  * reimplement equality elsewhere.
@@ -182,8 +182,15 @@ function diffObjectField(field, fullPath, baseline, current, changes, patch) {
182
182
  const afterObj = getByPath(current, fullPath);
183
183
  if (!isPlainObject(beforeObj) && !isPlainObject(afterObj)) return;
184
184
  const nested = {};
185
+ const changesBefore = changes.length;
185
186
  diffFields(field.objectDef.fields, fullPath, baseline, current, changes, nested, void 0, field.objectDef.flatMap);
186
187
  if ((afterObj === void 0 || afterObj === null) && isPlainObject(beforeObj)) {
188
+ if (changes.length === changesBefore) changes.push({
189
+ path: fullPath,
190
+ kind: "set",
191
+ before: beforeObj,
192
+ after: afterObj
193
+ });
187
194
  setPatchLeaf(patch, field.path, null);
188
195
  return;
189
196
  }
@@ -192,9 +199,10 @@ function diffObjectField(field, fullPath, baseline, current, changes, patch) {
192
199
  else setPatchLeaf(patch, field.path, afterObj === void 0 ? null : afterObj);
193
200
  }
194
201
  /**
195
- * Whether an object's patch may carry only its changed leaves: a
196
- * `@db.patch.strategy 'merge'` object that is not `@db.json` (a JSON value is
197
- * stored, and so replaced, whole).
202
+ * Whether a field's patch may carry only its changed leaves: a
203
+ * `@db.patch.strategy 'merge'` field that is not `@db.json` (a JSON value is
204
+ * stored, and so replaced, whole). For an object field this decides the nested
205
+ * partial; for a keyed array field, the shape of its `$update` items.
198
206
  */
199
207
  function isMergePatched(prop) {
200
208
  return getFieldMeta(prop, "db.patch.strategy") === "merge" && getFieldMeta(prop, "db.json") === void 0;
@@ -225,12 +233,9 @@ function diffArrayField(field, fullPath, baseline, current, changes, patch, inli
225
233
  * Produces a `TArrayPatch` value for one array field, or `undefined` when no
226
234
  * real op results (the caller then skips the field entirely).
227
235
  *
228
- * - Keyed arrays (item object has `@expect.array.key`): emit `$update`
229
- * (key + changed leaves), `$insert` (wholly-new items, whole), `$remove`
230
- * (key only). Reorder-only (same key membership, same content, different
231
- * order) → `$replace` (key-ops can't express a pure reorder).
232
- * Ambiguous keys (duplicate or missing key values) → `$replace` (the only
233
- * faithful op when key identity is unreliable).
236
+ * - Keyed arrays (item object has `@expect.array.key`): `$update` / `$insert`
237
+ * / `$remove` when those operators reproduce the form's array, else
238
+ * `$replace` — see {@link diffKeyedArray}.
234
239
  * - Unkeyed object arrays / primitive arrays: `$replace` with the whole array.
235
240
  * Primitive arrays with `@expect.array.uniqueItems` use by-value
236
241
  * `$insert` / `$remove` (set semantics).
@@ -244,7 +249,7 @@ function diffArray(field, before, after) {
244
249
  const beforeArr = Array.isArray(before) ? before : [];
245
250
  const afterArr = Array.isArray(after) ? after : [];
246
251
  const keyProps = getArrayKeyProps(field.itemType);
247
- if (keyProps.length > 0) return diffKeyedArray(beforeArr, afterArr, keyProps);
252
+ if (keyProps.length > 0) return diffKeyedArray(beforeArr, afterArr, keyProps, isMergePatched(field.prop));
248
253
  if (getFieldMeta(field.prop, "expect.array.uniqueItems") !== void 0 && isPrimitiveItem(field)) {
249
254
  const setPatch = diffUniqueArray(beforeArr, afterArr);
250
255
  if (setPatch) return setPatch;
@@ -252,51 +257,81 @@ function diffArray(field, before, after) {
252
257
  return { $replace: afterArr };
253
258
  }
254
259
  /**
255
- * Keyed array diff. Reorder-only (same membership) falls back to $replace.
260
+ * Keyed array diff: `$update` / `$insert` / `$remove` when those operators
261
+ * reproduce the form's array, else `{ $replace: after }`. Returns `undefined`
262
+ * when nothing changed (same order, no op), so the caller skips the field
263
+ * rather than emitting a malformed empty `{}`.
264
+ *
265
+ * Order: the db applies the operators remove → update (in place) → insert
266
+ * (appended, in item order), so the array it ends with holds the baseline
267
+ * elements whose key is still present, in baseline order, followed by the
268
+ * `$insert` items. When that key sequence differs from the form's, the
269
+ * operators cannot express the form state and `$replace` is the only faithful
270
+ * patch — a reorder, a new row placed before an existing one, an edited key on
271
+ * a row that is not last (its remove + insert would move it to the end), a row
272
+ * removed and re-added under the same key elsewhere. A new row appended at the
273
+ * end and an edited key on the last row stay key operators.
256
274
  *
257
- * Returns `undefined` when no $update/$insert/$remove op is produced (so the
258
- * caller skips the field rather than emitting a malformed empty `{}`).
275
+ * A `$update` item follows the array field's `@db.patch.strategy` (`merge` is
276
+ * whether it is `'merge'`), which the db applies to it: by default (replace)
277
+ * the db replaces the matched element, so the item is the whole current
278
+ * element minus its `undefined`-valued props; under `merge` the db shallow-
279
+ * merges the item in, so it is the key + the changed top-level leaves (a
280
+ * changed nested object whole), a cleared leaf as `null`
281
+ * ({@link buildKeyedUpdate}). Either way an item is emitted only when some
282
+ * leaf changed.
259
283
  *
260
- * Ambiguity fallback: if either side has DUPLICATE key buckets, or ANY element
261
- * is missing all of its key values, key identity is unreliable — fall back to
262
- * `{ $replace: after }`, the only faithful op (last-write-wins collapse would
263
- * silently drop items, and a key-less `$update` is unmatchable by the DB).
284
+ * Fallbacks to `{ $replace: after }`, the only faithful op, when:
285
+ * - key identity is ambiguous — an element that is not an object or lacks ALL
286
+ * of its key values, or a key shared by two elements on one side (a
287
+ * last-write-wins collapse would silently drop items);
288
+ * - an element a key operator would name (a `$update`, `$remove` or `$insert`
289
+ * item) lacks ANY of its key values (`undefined` / `null`): the db refuses
290
+ * such an item (`PATCH_KEY_REQUIRED` for `$update` / `$remove`), while under
291
+ * `$replace` it validates the array and reports the missing field on its
292
+ * own path. An untouched row with an incomplete key names no operator, so
293
+ * it does not turn an unrelated edit into a `$replace`.
264
294
  */
265
- function diffKeyedArray(before, after, keyProps) {
266
- if (hasKeylessItem(before, keyProps) || hasKeylessItem(after, keyProps)) return { $replace: after };
267
- const beforeByKey = /* @__PURE__ */ new Map();
268
- for (const el of before) if (isPlainObject(el)) beforeByKey.set(keyOf(el, keyProps), el);
269
- const afterByKey = /* @__PURE__ */ new Map();
270
- for (const el of after) if (isPlainObject(el)) afterByKey.set(keyOf(el, keyProps), el);
271
- if (beforeByKey.size !== before.length || afterByKey.size !== after.length) return { $replace: after };
272
- const $insert = [];
295
+ function diffKeyedArray(before, after, keyProps, merge) {
296
+ const beforeByKey = byKey(before, keyProps);
297
+ const afterByKey = byKey(after, keyProps);
298
+ if (!beforeByKey || !afterByKey) return { $replace: after };
299
+ const incomplete = (el) => keyProps.some((k) => el[k] === void 0 || el[k] === null);
300
+ const afterKeys = [...afterByKey.keys()];
273
301
  const $update = [];
274
302
  const $remove = [];
275
- let contentChanged = false;
276
- for (const [k, el] of afterByKey) {
277
- const prev = beforeByKey.get(k);
278
- if (prev === void 0) {
279
- $insert.push(el);
303
+ let kept = 0;
304
+ for (const [k, prev] of beforeByKey) {
305
+ const el = afterByKey.get(k);
306
+ if (el === void 0) {
307
+ if (incomplete(prev)) return { $replace: after };
308
+ $remove.push(pickKeys(prev, keyProps));
280
309
  continue;
281
310
  }
282
- if (!deepEqual(prev, el)) {
283
- contentChanged = true;
284
- const partial = buildKeyedUpdate(prev, el, keyProps);
285
- if (partial) $update.push(partial);
286
- }
311
+ if (afterKeys[kept++] !== k) return { $replace: after };
312
+ if (deepEqual(prev, el)) continue;
313
+ const partial = buildKeyedUpdate(prev, el, keyProps);
314
+ if (!partial) continue;
315
+ if (incomplete(el)) return { $replace: after };
316
+ $update.push(merge ? partial : definedProps(el));
287
317
  }
288
- if (beforeByKey.size === afterByKey.size && $insert.length === 0 && !contentChanged) return { $replace: after };
289
- for (const [k, el] of beforeByKey) if (!afterByKey.has(k)) $remove.push(pickKeys(el, keyProps));
318
+ const $insert = afterKeys.slice(kept).map((k) => afterByKey.get(k));
319
+ if ($insert.some(incomplete)) return { $replace: after };
290
320
  return arrayOps({
291
321
  $update,
292
322
  $insert,
293
323
  $remove
294
324
  });
295
325
  }
296
- /** Builds a `$update` partial: key fields + changed leaves only. */
326
+ /**
327
+ * Builds a `$update` partial: key fields + changed leaves only (a cleared leaf
328
+ * as `null`), or `undefined` when no leaf changed. A leaf is a top-level prop
329
+ * of the element, compared by value: an explicit `undefined`-valued prop
330
+ * equals an absent one, and a changed nested object is sent whole (the db
331
+ * merges an item one level deep).
332
+ */
297
333
  function buildKeyedUpdate(prev, next, keyProps) {
298
- const partial = {};
299
- for (const k of keyProps) partial[k] = next[k];
334
+ const partial = pickKeys(next, keyProps);
300
335
  let changed = false;
301
336
  const allKeys = new Set([...Object.keys(prev), ...Object.keys(next)]);
302
337
  for (const k of allKeys) {
@@ -310,6 +345,15 @@ function buildKeyedUpdate(prev, next, keyProps) {
310
345
  }
311
346
  return changed ? partial : void 0;
312
347
  }
348
+ /**
349
+ * Shallow copy of `el` without its `undefined`-valued own props (top level
350
+ * only; nested values are kept by reference).
351
+ */
352
+ function definedProps(el) {
353
+ const out = {};
354
+ for (const k of Object.keys(el)) if (el[k] !== void 0) out[k] = el[k];
355
+ return out;
356
+ }
313
357
  /** Primitive uniqueItems set diff. Returns undefined if neither side differs. */
314
358
  function diffUniqueArray(before, after) {
315
359
  const beforeSet = new Set(before.map((v) => stableKey(v)));
@@ -359,26 +403,29 @@ function getArrayKeyProps(itemType) {
359
403
  function isPrimitiveItem(field) {
360
404
  return field.itemType.type.kind === "";
361
405
  }
362
- /** True when any element lacks ALL of its key values (un-keyable identity). */
363
- function hasKeylessItem(arr, keyProps) {
406
+ /**
407
+ * The elements by {@link keyOf} bucket, or `undefined` when key identity is
408
+ * ambiguous: an element is not an object or lacks ALL of its key values
409
+ * (`undefined` / `null`), or two elements share a key (a Map collapse would
410
+ * silently lose one).
411
+ */
412
+ function byKey(arr, keyProps) {
413
+ const map = /* @__PURE__ */ new Map();
364
414
  for (const el of arr) {
365
- if (!isPlainObject(el)) return true;
366
- let hasAnyKey = false;
367
- for (const k of keyProps) {
368
- const v = el[k];
369
- if (v !== void 0 && v !== null) {
370
- hasAnyKey = true;
371
- break;
372
- }
373
- }
374
- if (!hasAnyKey) return true;
415
+ if (!isPlainObject(el) || keyProps.every((k) => el[k] === void 0 || el[k] === null)) return;
416
+ map.set(keyOf(el, keyProps), el);
375
417
  }
376
- return false;
418
+ return map.size === arr.length ? map : void 0;
377
419
  }
378
- /** Composite key string for a keyed-array element. */
420
+ /**
421
+ * Bucket string for a keyed-array element's key values, type-strict like
422
+ * {@link stableKey}. A composite key is the JSON array of its tagged values,
423
+ * so no two different key tuples share a bucket (a joined string would: the
424
+ * values may contain the separator).
425
+ */
379
426
  function keyOf(el, keyProps) {
380
427
  if (keyProps.length === 1) return stableKey(el[keyProps[0]]);
381
- return keyProps.map((k) => stableKey(el[k])).join(" ");
428
+ return JSON.stringify(keyProps.map((k) => stableKey(el[k])));
382
429
  }
383
430
  /** Picks only the key fields from an element (for $remove). */
384
431
  function pickKeys(el, keyProps) {
@@ -425,14 +472,20 @@ function stableKey(v) {
425
472
  * (revert-aware for NaN scalars) while `0` / `-0` stay equal (matches DB
426
473
  * intent — `===` treats them equal, only NaN is special-cased).
427
474
  *
475
+ * Unset is one value: `null`, `undefined` and an absent object prop are equal
476
+ * at any depth — a field loaded as `null` (SQL `NULL`) that the form holds as
477
+ * `undefined`, or an optional prop emptied to `undefined` in an array row, is
478
+ * unchanged. The patch cannot tell them apart either: it sends a cleared value
479
+ * as `null`.
480
+ *
428
481
  * The single comparator shared across the form engine: diff, conflict
429
482
  * detection ({@link buildFormRebase}), and apply all route through this — never
430
483
  * reimplement equality elsewhere.
431
484
  */
432
485
  function deepEqual(a, b) {
433
486
  if (a === b) return true;
487
+ if (a === null || a === void 0 || b === null || b === void 0) return (a === null || a === void 0) && (b === null || b === void 0);
434
488
  if (typeof a === "number" && typeof b === "number") return Number.isNaN(a) && Number.isNaN(b);
435
- if (a === null || b === null || a === void 0 || b === void 0) return false;
436
489
  if (typeof a !== "object" || typeof b !== "object") return false;
437
490
  const aIsArr = Array.isArray(a);
438
491
  const bIsArr = Array.isArray(b);
@@ -444,13 +497,8 @@ function deepEqual(a, b) {
444
497
  }
445
498
  const ao = a;
446
499
  const bo = b;
447
- const aKeys = Object.keys(ao);
448
- const bKeys = Object.keys(bo);
449
- if (aKeys.length !== bKeys.length) return false;
450
- for (const k of aKeys) {
451
- if (!Object.prototype.hasOwnProperty.call(bo, k)) return false;
452
- if (!deepEqual(ao[k], bo[k])) return false;
453
- }
500
+ for (const k of Object.keys(ao)) if (!deepEqual(ao[k], Object.hasOwn(bo, k) ? bo[k] : void 0)) return false;
501
+ for (const k of Object.keys(bo)) if (!Object.hasOwn(ao, k) && bo[k] !== void 0 && bo[k] !== null) return false;
454
502
  return true;
455
503
  }
456
504
  //#endregion
@@ -64,9 +64,8 @@ function setByPath(obj, path, value) {
64
64
  * if any ancestor is missing, the call is a no-op (nothing to delete).
65
65
  *
66
66
  * Unlike `setByPath(obj, path, undefined)`, this leaves NO own key behind — the
67
- * leaf reads as absent (`'k' in parent === false`), which keeps `deepEqual`
68
- * structural comparisons in sync (a present `undefined` own-key and an absent
69
- * key are NOT structurally equal under the own-key walk). Used by
67
+ * leaf reads as absent (`'k' in parent === false`), so the cleared data holds
68
+ * the same keys as data that never had the field. Used by
70
69
  * {@link applyFormChanges} to apply a clear-to-`undefined` change as a delete.
71
70
  *
72
71
  * Empty path clears the root domain value (`obj.value = undefined`).
@@ -28,9 +28,8 @@ declare function setByPath(obj: Record<string, unknown>, path: string, value: un
28
28
  * if any ancestor is missing, the call is a no-op (nothing to delete).
29
29
  *
30
30
  * Unlike `setByPath(obj, path, undefined)`, this leaves NO own key behind — the
31
- * leaf reads as absent (`'k' in parent === false`), which keeps `deepEqual`
32
- * structural comparisons in sync (a present `undefined` own-key and an absent
33
- * key are NOT structurally equal under the own-key walk). Used by
31
+ * leaf reads as absent (`'k' in parent === false`), so the cleared data holds
32
+ * the same keys as data that never had the field. Used by
34
33
  * {@link applyFormChanges} to apply a clear-to-`undefined` change as a delete.
35
34
  *
36
35
  * Empty path clears the root domain value (`obj.value = undefined`).
@@ -28,9 +28,8 @@ declare function setByPath(obj: Record<string, unknown>, path: string, value: un
28
28
  * if any ancestor is missing, the call is a no-op (nothing to delete).
29
29
  *
30
30
  * Unlike `setByPath(obj, path, undefined)`, this leaves NO own key behind — the
31
- * leaf reads as absent (`'k' in parent === false`), which keeps `deepEqual`
32
- * structural comparisons in sync (a present `undefined` own-key and an absent
33
- * key are NOT structurally equal under the own-key walk). Used by
31
+ * leaf reads as absent (`'k' in parent === false`), so the cleared data holds
32
+ * the same keys as data that never had the field. Used by
34
33
  * {@link applyFormChanges} to apply a clear-to-`undefined` change as a delete.
35
34
  *
36
35
  * Empty path clears the root domain value (`obj.value = undefined`).
@@ -64,9 +64,8 @@ function setByPath(obj, path, value) {
64
64
  * if any ancestor is missing, the call is a no-op (nothing to delete).
65
65
  *
66
66
  * Unlike `setByPath(obj, path, undefined)`, this leaves NO own key behind — the
67
- * leaf reads as absent (`'k' in parent === false`), which keeps `deepEqual`
68
- * structural comparisons in sync (a present `undefined` own-key and an absent
69
- * key are NOT structurally equal under the own-key walk). Used by
67
+ * leaf reads as absent (`'k' in parent === false`), so the cleared data holds
68
+ * the same keys as data that never had the field. Used by
70
69
  * {@link applyFormChanges} to apply a clear-to-`undefined` change as a delete.
71
70
  *
72
71
  * Empty path clears the root domain value (`obj.value = undefined`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/ui",
3
- "version": "0.1.174",
3
+ "version": "0.1.176",
4
4
  "description": "Framework-agnostic runtime for form and table definitions from atscript annotated types",
5
5
  "keywords": [
6
6
  "annotations",
@@ -52,20 +52,20 @@
52
52
  "access": "public"
53
53
  },
54
54
  "dependencies": {
55
- "@atscript/db-client": "^0.1.179"
55
+ "@atscript/db-client": "^0.1.182"
56
56
  },
57
57
  "devDependencies": {
58
- "@atscript/core": "^0.2.12",
59
- "@atscript/db": "^0.1.179",
60
- "@atscript/typescript": "^0.2.12",
58
+ "@atscript/core": "^0.2.13",
59
+ "@atscript/db": "^0.1.182",
60
+ "@atscript/typescript": "^0.2.13",
61
61
  "@uniqu/core": "^0.2.2",
62
- "unplugin-atscript": "^0.2.12",
62
+ "unplugin-atscript": "^0.2.13",
63
63
  "vitest": "npm:@voidzero-dev/vite-plus-test@0.1.14"
64
64
  },
65
65
  "peerDependencies": {
66
- "@atscript/core": "^0.2.12",
67
- "@atscript/db": "^0.1.179",
68
- "@atscript/typescript": "^0.2.12"
66
+ "@atscript/core": "^0.2.13",
67
+ "@atscript/db": "^0.1.182",
68
+ "@atscript/typescript": "^0.2.13"
69
69
  },
70
70
  "scripts": {
71
71
  "build": "vp pack",