@jskit-ai/http-web 0.2.20 → 0.2.22

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/CHANGELOG.md CHANGED
@@ -2,6 +2,9 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - A record's form keeps its null values: editing a record whose `type: "id"` link is null and saving it sends null back. `applyCrudPayloadToForm` put "" in the form for every null field except booleans and lookups, and `buildCrudFormPayload` sent that "" back, which the id cast refused with a raw "Value could not be cast…"; a nullable string or select also came back as "" instead of null. A nullable field now keeps null in the form, and an `id` field is saved like a lookup: trimmed, null when a nullable one is cleared, and not sent when a required one is empty, so the server names it as missing. Numbers, dates, times and booleans already round-tripped their nulls and are unchanged.
6
+ - A list record's overflow menu (`CrudListRecordActionMenu`, on cards and table rows) is exposed as a menu: its list has `role="menu"`, named after its button ("Actions for {title}"), and Open, Edit and each row action are `role="menuitem"`, with `aria-disabled="true"` on an unavailable action, as Material 3 menus and shell-web's page-actions menu are. Before, it was Vuetify's default list of links and list items, so assistive technology heard no menu and a browser test looking for its menu items found none. Nothing changes visually.
7
+ - CRUD screens take a CRUD contract from `@jskit-ai/resource-crud-core`'s `defineCrudContract`; the crud-screen-set pattern's pages use the books example's `bookCrud`.
5
8
  - The list's create FAB takes layout room (`<v-fab app layout>`), so shell-web's snackbar shows above it instead of over it, and the list's last card scrolls clear of it.
6
9
  - The CRUD screens are exact Material 3. The list is a search bar and one row of filter chips (the Filters chip opens every control in a bottom sheet on compact windows and a dialog on wider ones), then cards or, when the list is at least 720px wide, a table; cards and rows open their record when tapped and keep their other actions in a trailing overflow menu (a table row's Open is a trailing chevron, its Edit a pencil); cards no longer show the record's id; the create action is an extended FAB on compact and medium windows and the app bar's primary action on wider ones; empty and error states have an icon. The view is a header and value-first details, its Edit and Delete in the app bar; new and edit pages have Cancel and Save in the app bar.
7
10
  - Save, Cancel and delete replace the form's history entry through shell-web's `useShellNavigation().finish()`, so Back no longer reopens a finished form; `useCrudDeleteAction()` no longer takes `router`. A view whose record is not found, or whose load is refused with 403, tells the shell (`pageUnavailable()`), so Up returning to it goes on to its parent. `useView()` (and `useViewCore()`) expose the failed load's HTTP status as `errorStatus`.
@@ -12,7 +12,7 @@ export default defineConfig({
12
12
  // The crud-screen-set pattern's pages import the app's shared book resource from here.
13
13
  "@local/books/shared": path.resolve(
14
14
  fixtureRoot,
15
- "../../../resource-crud-core/patterns/resource-contract/example/bookResource.js"
15
+ "../../../resource-crud-core/patterns/crud-contract/example/bookResource.js"
16
16
  )
17
17
  }
18
18
  },
@@ -0,0 +1,37 @@
1
+ <script setup>
2
+ import { ref } from "vue";
3
+ import CrudListRecordActionMenu from "../../src/client/components/CrudListRecordActionMenu.vue";
4
+
5
+ const record = { id: "2", title: "Kindred" };
6
+ const ran = ref([]);
7
+ // A list's row actions as useCrudListRowActions() exposes them: one available, one unavailable for this record.
8
+ const rowActions = {
9
+ visibleActionsFor: () => [
10
+ { key: "lend", label: "Lend", icon: "$send" },
11
+ { key: "archive", label: "Archive", icon: "$delete" }
12
+ ],
13
+ isActionLoading: () => false,
14
+ isActionDisabled: (action) => action.key === "archive",
15
+ execute: (action) => {
16
+ ran.value = [...ran.value, action.key];
17
+ }
18
+ };
19
+ </script>
20
+
21
+ <template>
22
+ <v-app>
23
+ <v-main class="pa-4">
24
+ <CrudListRecordActionMenu
25
+ :record="record"
26
+ :index="0"
27
+ :title="record.title"
28
+ :row-actions="rowActions"
29
+ show-view
30
+ :view-location="{ path: '/books/2' }"
31
+ show-edit
32
+ :edit-location="{ path: '/books/2/edit' }"
33
+ />
34
+ <output data-testid="record-action-menu-ran">{{ ran.join(",") }}</output>
35
+ </v-main>
36
+ </v-app>
37
+ </template>
@@ -0,0 +1,12 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Record action menu semantics</title>
7
+ </head>
8
+ <body>
9
+ <div id="app"></div>
10
+ <script type="module" src="/main.js"></script>
11
+ </body>
12
+ </html>
@@ -0,0 +1,31 @@
1
+ import { createApp } from "vue";
2
+ import { createMemoryHistory, createRouter } from "vue-router";
3
+ import "vuetify/styles";
4
+ import "@jskit-ai/material-web/client/material.css";
5
+ import { createVuetify } from "vuetify";
6
+ import * as components from "vuetify/components";
7
+ import * as directives from "vuetify/directives";
8
+ import { createMaterialVuetifyOptions } from "@jskit-ai/material-web/client";
9
+ import App from "./App.vue";
10
+
11
+ const page = { render: () => null };
12
+ const router = createRouter({
13
+ history: createMemoryHistory(),
14
+ routes: [
15
+ { path: "/", component: page },
16
+ { path: "/books/:bookId", component: page },
17
+ { path: "/books/:bookId/edit", component: page }
18
+ ]
19
+ });
20
+
21
+ const vuetify = createVuetify({
22
+ components,
23
+ directives,
24
+ ...createMaterialVuetifyOptions()
25
+ });
26
+
27
+ await router.push("/");
28
+ createApp(App)
29
+ .use(router)
30
+ .use(vuetify)
31
+ .mount("#app");
@@ -0,0 +1,15 @@
1
+ import path from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ import { defineConfig } from "vite";
4
+ import vue from "@vitejs/plugin-vue";
5
+
6
+ const fixtureRoot = path.dirname(fileURLToPath(import.meta.url));
7
+
8
+ export default defineConfig({
9
+ root: fixtureRoot,
10
+ plugins: [vue()],
11
+ server: {
12
+ host: "127.0.0.1",
13
+ strictPort: true
14
+ }
15
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/http-web",
3
- "version": "0.2.20",
3
+ "version": "0.2.22",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -47,13 +47,13 @@
47
47
  "./locales/en.json": "./locales/en.json"
48
48
  },
49
49
  "dependencies": {
50
- "@jskit-ai/resource-crud-core": "0.1.203"
50
+ "@jskit-ai/resource-crud-core": "0.1.205"
51
51
  },
52
52
  "peerDependencies": {
53
- "@jskit-ai/http-runtime": "0.2.12",
54
- "@jskit-ai/kernel": "0.2.12",
55
- "@jskit-ai/realtime": "0.2.18",
56
- "@jskit-ai/shell-web": "0.2.15",
53
+ "@jskit-ai/http-runtime": "0.2.14",
54
+ "@jskit-ai/kernel": "0.2.14",
55
+ "@jskit-ai/realtime": "0.2.20",
56
+ "@jskit-ai/shell-web": "0.2.17",
57
57
  "@tanstack/vue-query": "^5.90.5",
58
58
  "vue": "^3.5.13",
59
59
  "vue-router": "^5.0.4",
@@ -3,7 +3,7 @@ id: crud/crud-screen-set
3
3
  title: CRUD list, view, create, and edit screens
4
4
  summary: Build a routed CRUD user interface as thin application pages over JSKIT's shared screen components and composables.
5
5
  keywords: actions, add, crud, delete, edit, filters, list, material, routes, view, vue
6
- requires: @jskit-ai/http-web, @jskit-ai/resource-crud-core
6
+ requires: @jskit-ai/http-web, @jskit-ai/resource-crud-core, @jskit-ai/resource-core
7
7
  ---
8
8
 
9
9
  # CRUD list, view, create, and edit screens
@@ -27,7 +27,7 @@ supporting detail content; those are public extension seams.
27
27
 
28
28
  Decide which operations exist, the route hierarchy, record title, visible
29
29
  fields, create/edit participation, destructive confirmation language, access
30
- surface, filters, and domain actions. The resource contract and product intent
30
+ surface, filters, and domain actions. The CRUD contract and product intent
31
31
  are authoritative. Do not derive these decisions from a live table or a field
32
32
  questionnaire.
33
33
 
@@ -49,7 +49,7 @@ questionnaire.
49
49
  history entry, so neither Up nor Back reopens it.
50
50
  - View fields are two-line list items with the value first:
51
51
  `<v-list-item :title="record.author" subtitle="Author" />`.
52
- - Transport and validators come from the shared resource contract.
52
+ - Transport and validators come from the shared CRUD contract.
53
53
  - Initial visible loading uses structure-matching skeletons; pending buttons use
54
54
  stable disabled labels, never spinners.
55
55
  - Resource-load errors stay inside the screen with retry. Command success and
@@ -71,15 +71,18 @@ questionnaire.
71
71
  Use `CrudListScreen`, `CrudViewScreen`, `CrudAddEditScreen`, and
72
72
  `CrudDeleteAction` with their matching composables from `@jskit-ai/http-web`.
73
73
  Use `defineCrudListFilters()`, `defineCrudListRowActions()`, and
74
- `defineCrudListBulkActions()` for optional list extensions. The resource comes
75
- from `defineCrudResource()` in `@jskit-ai/resource-crud-core`.
74
+ `defineCrudListBulkActions()` for optional list extensions. Screens take the
75
+ CRUD contract from `defineCrudContract()` in `@jskit-ai/resource-crud-core`,
76
+ built on the table resource from `defineTableResource()` in
77
+ `@jskit-ai/resource-core`.
76
78
 
77
79
  ## Example files
78
80
 
79
81
  `example/books/` contains concrete list, view, new, and edit pages for the
80
- owner-scoped `bookResource` pattern. `BookFormFields.vue` and `formFields.js`
81
- show the small product-owned form seam. `listExtensions.js` makes optional
82
- filters and actions explicit without adding empty screen machinery elsewhere.
82
+ owner-scoped `bookResource` table resource and its `bookCrud` contract.
83
+ `BookFormFields.vue` and `formFields.js` show the small product-owned form
84
+ seam. `listExtensions.js` makes optional filters and actions explicit without
85
+ adding empty screen machinery elsewhere.
83
86
 
84
87
  ## Variation points
85
88
 
@@ -166,6 +169,21 @@ through to Vuetify.
166
169
  Here `lookups` is the page's `createCrudLookupFieldRuntime()` result for the
167
170
  same form fields.
168
171
 
172
+ ### Linked records in a list
173
+
174
+ A list that shows a field of a linked record asks for it by relationship name
175
+ in `useCrudListScreen({ ..., requestQueryParams: { include: "service" } })`,
176
+ and each row reads it from its `lookups`: `record.lookups.service.name`. The
177
+ contract decides which of the linked record's fields arrive: its id, its
178
+ relation's `labelKey`, and what `fields.serviceId.output.includeFields` names.
179
+
180
+ ```vue
181
+ <template #table-row="{ record }">
182
+ <td>{{ record.title }}</td>
183
+ <td>{{ record.lookups?.service?.name }}</td>
184
+ </template>
185
+ ```
186
+
169
187
  ## Verification
170
188
 
171
189
  - Mount each route with a representative resource response.
@@ -3,7 +3,7 @@ import { computed } from "vue";
3
3
  import { useRoute } from "vue-router";
4
4
  import CrudAddEditScreen from "@jskit-ai/http-web/client/components/CrudAddEditScreen";
5
5
  import { useCrudAddEditScreen } from "@jskit-ai/http-web/client/composables/useCrudAddEditScreen";
6
- import { bookResource } from "@local/books/shared";
6
+ import { bookCrud } from "@local/books/shared";
7
7
  import BookFormFields from "./BookFormFields.vue";
8
8
  import { bookFormFields } from "./formFields.js";
9
9
 
@@ -17,7 +17,7 @@ const screen = useCrudAddEditScreen({
17
17
  saveLabel: "Save changes",
18
18
  cancelTo: "/books/:bookId",
19
19
  preserveCancelQuery: true,
20
- resource: bookResource,
20
+ resource: bookCrud,
21
21
  operationName: "patch",
22
22
  formFields: bookFormFields,
23
23
  addEditOptions: {
@@ -1,14 +1,14 @@
1
1
  <script setup>
2
2
  import CrudListScreen from "@jskit-ai/http-web/client/components/CrudListScreen";
3
3
  import { useCrudListScreen } from "@jskit-ai/http-web/client/composables/useCrudListScreen";
4
- import { bookResource } from "@local/books/shared";
4
+ import { bookCrud } from "@local/books/shared";
5
5
  import { listBulkActions, listFilters, listRowActions } from "./listExtensions.js";
6
6
 
7
7
  // A main menu destination: the app bar shows its title and no Up arrow.
8
8
  definePage({ meta: { jskit: { title: "Books" } } });
9
9
 
10
10
  const screen = useCrudListScreen({
11
- resource: bookResource,
11
+ resource: bookCrud,
12
12
  resourceNamespace: "books",
13
13
  apiSuffix: "/books",
14
14
  recordIdParam: "bookId",
@@ -1,7 +1,7 @@
1
1
  <script setup>
2
2
  import CrudAddEditScreen from "@jskit-ai/http-web/client/components/CrudAddEditScreen";
3
3
  import { useCrudAddEditScreen } from "@jskit-ai/http-web/client/composables/useCrudAddEditScreen";
4
- import { bookResource } from "@local/books/shared";
4
+ import { bookCrud } from "@local/books/shared";
5
5
  import BookFormFields from "./BookFormFields.vue";
6
6
  import { bookFormFields } from "./formFields.js";
7
7
 
@@ -11,7 +11,7 @@ const screen = useCrudAddEditScreen({
11
11
  mode: "new",
12
12
  saveLabel: "Save book",
13
13
  cancelTo: "/books",
14
- resource: bookResource,
14
+ resource: bookCrud,
15
15
  operationName: "create",
16
16
  formFields: bookFormFields,
17
17
  addEditOptions: {
@@ -3,13 +3,13 @@ import CrudDeleteAction from "@jskit-ai/http-web/client/components/CrudDeleteAct
3
3
  import CrudViewScreen from "@jskit-ai/http-web/client/components/CrudViewScreen";
4
4
  import { useCrudDeleteAction } from "@jskit-ai/http-web/client/composables/useCrudDeleteAction";
5
5
  import { useCrudViewScreen } from "@jskit-ai/http-web/client/composables/useCrudViewScreen";
6
- import { bookResource } from "@local/books/shared";
6
+ import { bookCrud } from "@local/books/shared";
7
7
 
8
8
  // Up returns to the page the book was opened from, or else to the list.
9
9
  definePage({ meta: { jskit: { title: "Book", parent: "/books" } } });
10
10
 
11
11
  const screen = useCrudViewScreen({
12
- resource: bookResource,
12
+ resource: bookCrud,
13
13
  resourceNamespace: "books",
14
14
  apiUrlTemplate: "/books/:bookId",
15
15
  recordIdParam: "bookId",
@@ -22,7 +22,7 @@ const screen = useCrudViewScreen({
22
22
 
23
23
  const deleteAction = useCrudDeleteAction({
24
24
  screen,
25
- resource: bookResource,
25
+ resource: bookCrud,
26
26
  resourceNamespace: "books",
27
27
  apiUrlTemplate: "/books/:bookId"
28
28
  });
@@ -81,15 +81,18 @@ function runRowAction(action) {
81
81
  :aria-label="buttonLabel"
82
82
  />
83
83
  </template>
84
- <v-list min-width="160">
84
+ <!-- A menu of menu items, as Material 3 menus are exposed (Vuetify's list is otherwise a list of links). -->
85
+ <v-list role="menu" :aria-label="buttonLabel" min-width="160">
85
86
  <v-list-item
86
87
  v-if="hasViewAction"
88
+ role="menuitem"
87
89
  prepend-icon="$visibility"
88
90
  :title="t('jskit.http.actions.open')"
89
91
  :to="viewLocation"
90
92
  />
91
93
  <v-list-item
92
94
  v-if="hasEditAction"
95
+ role="menuitem"
93
96
  prepend-icon="$edit"
94
97
  :title="t('jskit.http.actions.edit')"
95
98
  :to="editLocation"
@@ -98,9 +101,11 @@ function runRowAction(action) {
98
101
  <v-list-item
99
102
  v-for="action in visibleRowActions"
100
103
  :key="action.key"
104
+ role="menuitem"
101
105
  :title="rowActionLabel(action)"
102
106
  :base-color="action.color"
103
107
  :disabled="isRowActionDisabled(action)"
108
+ :aria-disabled="isRowActionDisabled(action) ? 'true' : undefined"
104
109
  @click="runRowAction(action)"
105
110
  >
106
111
  <template v-if="action.icon" #prepend>
@@ -244,6 +244,7 @@ function shouldSerializeClearedFieldAsNull(field = {}) {
244
244
  const fieldFormat = resolveFormFieldFormat(field);
245
245
 
246
246
  return (
247
+ fieldType === "id" ||
247
248
  fieldType === "integer" ||
248
249
  fieldType === "number" ||
249
250
  fieldFormat === "date" ||
@@ -302,7 +303,8 @@ function buildCrudFormPayload(fields = [], model = {}) {
302
303
  continue;
303
304
  }
304
305
 
305
- if (isLookupFormField(field)) {
306
+ // An id, a lookup's or a plain link's, is a value or nothing: a cleared one is null, never "".
307
+ if (isLookupFormField(field) || fieldType === "id") {
306
308
  const normalizedLookupValue = String(rawValue).trim();
307
309
  if (!normalizedLookupValue) {
308
310
  if (clearAsNull) {
@@ -401,7 +403,8 @@ function applyCrudPayloadToForm(fields = [], model = {}, payload = {}) {
401
403
  continue;
402
404
  }
403
405
 
404
- targetModel[fieldKey] = rawValue == null ? "" : String(rawValue);
406
+ // A nullable field keeps its null, so saving the form unchanged sends null back, not "".
407
+ targetModel[fieldKey] = rawValue == null ? (isNullableFormField(field) ? null : "") : String(rawValue);
405
408
  }
406
409
  }
407
410
 
@@ -0,0 +1,47 @@
1
+ import process from "node:process";
2
+ import test from "node:test";
3
+ import { fileURLToPath } from "node:url";
4
+ import { expect } from "@playwright/test";
5
+ import { sharedBrowserFixture } from "../../../tooling/testUtils/browserFixture.mjs";
6
+
7
+ const openFixture = sharedBrowserFixture({
8
+ fixtureRoot: fileURLToPath(new URL("../fixtures/record-action-menu/", import.meta.url))
9
+ });
10
+
11
+ // A list's phone cards and a wider window's table rows show the same menu.
12
+ for (const viewport of [{ width: 390, height: 844 }, { width: 820, height: 1180 }]) {
13
+ test(`a list record's action menu is a menu of menu items at ${viewport.width}px`, {
14
+ skip: process.env.JSKIT_HTTP_WEB_RECORD_ACTION_MENU_BROWSER === "1"
15
+ ? false
16
+ : "set JSKIT_HTTP_WEB_RECORD_ACTION_MENU_BROWSER=1 to run the record action menu browser regression",
17
+ timeout: 120_000
18
+ }, async (t) => {
19
+ const { vite: runtime, browser } = await openFixture(t);
20
+ const page = await browser.newPage({ baseURL: runtime.baseURL, viewport });
21
+ const errors = [];
22
+ page.on("pageerror", (error) => errors.push(error.message));
23
+ await page.goto("/", { waitUntil: "networkidle" });
24
+
25
+ const button = page.getByRole("button", { name: "Actions for Kindred" });
26
+ await expect(button).toHaveAttribute("aria-haspopup", "menu");
27
+
28
+ // The keyboard opens the menu on its first item, as a menu button does.
29
+ await button.focus();
30
+ await page.keyboard.press("ArrowDown");
31
+ const menu = page.getByRole("menu", { name: "Actions for Kindred" });
32
+ await expect(menu).toBeVisible();
33
+ await expect(menu.getByRole("menuitem", { name: "Open" })).toBeFocused();
34
+ await expect(menu.getByRole("menuitem")).toHaveText(["Open", "Edit", "Lend", "Archive"]);
35
+ await expect(menu.getByRole("menuitem", { name: "Open" })).toHaveAttribute("href", "/books/2");
36
+ await expect(menu.getByRole("menuitem", { name: "Edit" })).toHaveAttribute("href", "/books/2/edit");
37
+ await expect(menu.getByRole("menuitem", { name: "Archive", disabled: true })).toBeVisible();
38
+ await expect(menu.getByRole("menuitem", { name: "Lend", disabled: false })).toBeVisible();
39
+ await expect(menu.getByRole("separator")).toHaveCount(1);
40
+
41
+ await menu.getByRole("menuitem", { name: "Lend" }).click();
42
+ await expect(page.getByTestId("record-action-menu-ran")).toHaveText("lend");
43
+ await expect(menu).toBeHidden();
44
+ await expect(page.getByRole("menuitem")).toHaveCount(0);
45
+ expect(errors).toEqual([]);
46
+ });
47
+ }
@@ -12,7 +12,8 @@ import { createSSRApp, h } from "vue";
12
12
  import { renderToString } from "vue/server-renderer";
13
13
  import { createMemoryHistory, createRouter } from "vue-router";
14
14
  import { QueryClient, VueQueryPlugin } from "@tanstack/vue-query";
15
- import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
15
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
16
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
16
17
  import { useCrudAddEditScreen } from "../src/client/composables/useCrudAddEditScreen.js";
17
18
  import { useCrudListScreen } from "../src/client/composables/useCrudListScreen.js";
18
19
 
@@ -29,7 +30,7 @@ globalThis.definePage = () => {};
29
30
  const hooks = registerHooks({
30
31
  resolve(specifier, context, nextResolve) {
31
32
  if (specifier === "@local/books/shared") {
32
- return { shortCircuit: true, url: new URL("../../resource-crud-core/patterns/resource-contract/example/bookResource.js", import.meta.url).href };
33
+ return { shortCircuit: true, url: new URL("../../resource-crud-core/patterns/crud-contract/example/bookResource.js", import.meta.url).href };
33
34
  }
34
35
  return nextResolve(specifier, context);
35
36
  },
@@ -43,7 +44,11 @@ const hooks = registerHooks({
43
44
  test("the human guide's public create/list configuration works without bootstrap permissions", async () => {
44
45
  const guide = await readFile(new URL("../../agent-docs/site/guide/framework/crud-operations.md", import.meta.url), "utf8");
45
46
  const snippets = Array.from(guide.matchAll(/```js\n([\s\S]*?)\n```/gu), (match) => match[1]);
46
- const resource = new Function("defineCrudResource", `${snippets.find((source) => source.startsWith("const bookResource"))}\nreturn bookResource;`)(defineCrudResource);
47
+ const resource = new Function(
48
+ "defineTableResource",
49
+ "defineCrudContract",
50
+ `${snippets.find((source) => source.startsWith("const bookResource"))}\nreturn bookCrud;`
51
+ )(defineTableResource, defineCrudContract);
47
52
  const options = new Function(`return ({${snippets.find((source) => source.startsWith("addEditOptions:"))}});`)();
48
53
  const router = createRouter({ history: createMemoryHistory(), routes: [{ path: "/books/:bookId?", component: { render: () => h("div") } }] });
49
54
  await router.push("/books/new");
@@ -95,7 +100,7 @@ test("the human guide's public create/list configuration works without bootstrap
95
100
  await list.records.reload();
96
101
  assert.deepEqual(list.records.items, [{ id: "1", title: "Public book" }]);
97
102
  assert.deepEqual(Object.keys(resource.operations), ["list", "view", "create"]);
98
- assert.equal(Object.hasOwn(resource.schema, "userId"), false);
103
+ assert.equal(Object.hasOwn(resource.resource.schema, "userId"), false);
99
104
  } finally {
100
105
  queryClient.clear();
101
106
  }
@@ -0,0 +1,91 @@
1
+ import assert from "node:assert/strict";
2
+ import { setImmediate as nextTurn } from "node:timers/promises";
3
+ import test from "node:test";
4
+ import { QueryClient, QueryObserver } from "@tanstack/vue-query";
5
+ import { shouldRetryTransientQueryFailure, transientQueryRetryDelay } from "@jskit-ai/kernel/shared/support";
6
+
7
+ import { configureHttpWebClient } from "../src/client/lib/httpClient.js";
8
+
9
+ // The QueryClient defaults every JSKIT app installs (agent-docs patterns/*-foundation/example/src/main.js).
10
+ function appQueryClient() {
11
+ return new QueryClient({
12
+ defaultOptions: {
13
+ queries: {
14
+ refetchOnWindowFocus: false,
15
+ refetchOnReconnect: true,
16
+ retry: shouldRetryTransientQueryFailure,
17
+ retryDelay: transientQueryRetryDelay
18
+ }
19
+ }
20
+ });
21
+ }
22
+
23
+ /**
24
+ * Observes one read as a screen does and moves the mocked clock until it fails the way shell-web's request recovery
25
+ * reports it (error, no fetch in flight): the moment the recovery banner appears.
26
+ */
27
+ async function timeToRecoveryBanner(t, queryClient, queryFn) {
28
+ t.mock.timers.enable({ apis: ["setTimeout", "Date"] });
29
+ const startedAt = Date.now();
30
+ const observer = new QueryObserver(queryClient, { queryKey: ["unreachable-read"], queryFn });
31
+ let failed = null;
32
+ const unsubscribe = observer.subscribe((result) => {
33
+ if (result.status === "error" && result.fetchStatus === "idle") failed ??= Date.now() - startedAt;
34
+ });
35
+ try {
36
+ while (failed === null) {
37
+ for (let turn = 0; turn < 4; turn += 1) await nextTurn();
38
+ if (failed !== null) break;
39
+ assert.ok(Date.now() - startedAt < 60_000, "The read never failed");
40
+ t.mock.timers.tick(50);
41
+ }
42
+ } finally {
43
+ unsubscribe();
44
+ queryClient.clear();
45
+ }
46
+ return failed;
47
+ }
48
+
49
+ test("one unreachable safe read makes three requests and reaches request recovery in three seconds", async (t) => {
50
+ let requests = 0;
51
+ const client = configureHttpWebClient({
52
+ fetchImpl: async () => {
53
+ requests += 1;
54
+ throw new TypeError("Failed to fetch");
55
+ }
56
+ });
57
+ t.after(() => configureHttpWebClient());
58
+
59
+ const elapsedMs = await timeToRecoveryBanner(t, appQueryClient(), () => client.request("/api/projects"));
60
+
61
+ // The HTTP client retries the safe read twice, one and two seconds apart; the query does not retry it again.
62
+ const outcome = `${requests} requests, request recovery after ${elapsedMs} ms`;
63
+ assert.equal(requests, 3, outcome);
64
+ assert.ok(elapsedMs >= 3_000 && elapsedMs < 3_100, outcome);
65
+ });
66
+
67
+ test("a query read the HTTP client does not retry keeps the query's own transient retries", async (t) => {
68
+ let requests = 0;
69
+ const client = configureHttpWebClient({
70
+ fetchImpl: async (url) => {
71
+ if (url === "/api/session") {
72
+ return new Response(JSON.stringify({ csrfToken: "csrf" }), { headers: { "content-type": "application/json" } });
73
+ }
74
+ requests += 1;
75
+ return new Response(JSON.stringify({ error: "Temporarily unavailable." }), {
76
+ status: 503,
77
+ headers: { "content-type": "application/json" }
78
+ });
79
+ }
80
+ });
81
+ t.after(() => configureHttpWebClient());
82
+
83
+ const elapsedMs = await timeToRecoveryBanner(t, appQueryClient(), () =>
84
+ client.request("/api/search", { method: "POST", body: { text: "query" } }));
85
+
86
+ // The client never repeats a POST, so the query's two retries are the only ones. TanStack Query counts failures
87
+ // from zero, so transientQueryRetryDelay gives each of them one second.
88
+ const outcome = `${requests} requests, failed after ${elapsedMs} ms`;
89
+ assert.equal(requests, 3, outcome);
90
+ assert.ok(elapsedMs >= 2_000 && elapsedMs < 2_100, outcome);
91
+ });
@@ -392,6 +392,50 @@ test("applyCrudPayloadToForm preserves null lookup payload values", () => {
392
392
  assert.equal(form.serviceId, "42");
393
393
  });
394
394
 
395
+ test("editing a record with a null id link saves it as null, and every nullable field keeps its null", () => {
396
+ const fields = [
397
+ { key: "title", type: "string" },
398
+ { key: "ownerId", type: "id", nullable: true },
399
+ { key: "shelfId", type: "id" },
400
+ { key: "nickname", type: "string", nullable: true },
401
+ { key: "status", type: "string", nullable: true, component: "select" },
402
+ { key: "rank", type: "integer", nullable: true },
403
+ { key: "dueOn", type: "string", format: "date", nullable: true }
404
+ ];
405
+ const form = reactive(createCrudFormModel(fields));
406
+ applyCrudPayloadToForm(fields, form, {
407
+ title: "Kindred",
408
+ ownerId: null,
409
+ shelfId: 7,
410
+ nickname: null,
411
+ status: null,
412
+ rank: null,
413
+ dueOn: null
414
+ });
415
+ assert.equal(form.ownerId, null);
416
+ assert.equal(form.shelfId, "7");
417
+
418
+ // Saved unchanged, the record's nulls go back as nulls.
419
+ assert.deepEqual(buildCrudFormPayload(fields, form), {
420
+ title: "Kindred",
421
+ ownerId: null,
422
+ shelfId: "7",
423
+ nickname: null,
424
+ status: null,
425
+ rank: null,
426
+ dueOn: null
427
+ });
428
+
429
+ // A link typed and cleared again is null; one typed is its id. A required link left empty is not sent, so the
430
+ // server names it as missing instead of refusing "" as an id.
431
+ form.ownerId = " 12 ";
432
+ assert.equal(buildCrudFormPayload(fields, form).ownerId, "12");
433
+ form.ownerId = "";
434
+ assert.equal(buildCrudFormPayload(fields, form).ownerId, null);
435
+ form.shelfId = "";
436
+ assert.equal(Object.hasOwn(buildCrudFormPayload(fields, form), "shelfId"), false);
437
+ });
438
+
395
439
  test("resolveCrudRouteBoundFieldValues maps route params for route-bound form fields", () => {
396
440
  const values = resolveCrudRouteBoundFieldValues(
397
441
  [