wcz-layout 10.1.9 → 10.2.0

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.
Files changed (107) hide show
  1. package/dist/{Approval-DoD-GRRH.mjs → Approval-D1TfISUL.mjs} +11 -21
  2. package/dist/Approval-D1TfISUL.mjs.map +1 -0
  3. package/dist/{LayoutTable-CRo43iWr.d.mts → ChatLayout-BmLySLXy.d.mts} +11 -18
  4. package/dist/ChatLayout-Tpuwo8-b.mjs +1622 -0
  5. package/dist/ChatLayout-Tpuwo8-b.mjs.map +1 -0
  6. package/dist/{DialogsContext-DLqA8RJ_.mjs → DialogsContext-D23fJjYR.mjs} +2 -3
  7. package/dist/DialogsContext-D23fJjYR.mjs.map +1 -0
  8. package/dist/{Email-CKUxOURX.d.mts → Email-Dz5k0UWE.d.mts} +1 -3
  9. package/dist/{Email-BzQQkbe9.mjs → Email-rnz3H0x3.mjs} +3 -5
  10. package/dist/Email-rnz3H0x3.mjs.map +1 -0
  11. package/dist/{Employee-agVPiGrJ.d.mts → Employee-C8xIlBxY.d.mts} +1 -7
  12. package/dist/{FileMeta-Be9viU7D.d.mts → FileMeta-B39e2FLC.d.mts} +1 -3
  13. package/dist/{FileMeta-DDqUju1Y.mjs → FileMeta-CPBWI_jA.mjs} +2 -3
  14. package/dist/FileMeta-CPBWI_jA.mjs.map +1 -0
  15. package/dist/{QueryClientParam-JcH0mJWl.d.mts → QueryClientParam-CTV1vj76.d.mts} +1 -3
  16. package/dist/RouterListItemButton-CF-8w-08.mjs +62 -0
  17. package/dist/RouterListItemButton-CF-8w-08.mjs.map +1 -0
  18. package/dist/{User-D4__w1I1.d.mts → User-aJksXItw.d.mts} +1 -3
  19. package/dist/{approval-L09uPzTU.mjs → approval-HB2w5jzc.mjs} +4 -5
  20. package/dist/approval-HB2w5jzc.mjs.map +1 -0
  21. package/dist/auth.d.mts +0 -4
  22. package/dist/auth.mjs +5 -6
  23. package/dist/auth.mjs.map +1 -1
  24. package/dist/components.d.mts +63 -33
  25. package/dist/components.mjs +658 -748
  26. package/dist/components.mjs.map +1 -1
  27. package/dist/{createApi-BhNkG4jz.mjs → createApi-CKgFi53y.mjs} +4 -6
  28. package/dist/createApi-CKgFi53y.mjs.map +1 -0
  29. package/dist/data/client.d.mts +2 -8
  30. package/dist/data/client.mjs +6 -9
  31. package/dist/data/client.mjs.map +1 -1
  32. package/dist/data/server.d.mts +2 -4
  33. package/dist/data/server.mjs +6 -7
  34. package/dist/data/server.mjs.map +1 -1
  35. package/dist/env-BwFl7nWc.mjs +48 -0
  36. package/dist/env-BwFl7nWc.mjs.map +1 -0
  37. package/dist/{file-Chlljz3o.mjs → file-X1sK4ok6.mjs} +7 -8
  38. package/dist/file-X1sK4ok6.mjs.map +1 -0
  39. package/dist/{file-Dl8JCcqy.mjs → file-tkfsnk5F.mjs} +8 -8
  40. package/dist/file-tkfsnk5F.mjs.map +1 -0
  41. package/dist/generatedChart-k7NEdi5Z.mjs +211 -0
  42. package/dist/generatedChart-k7NEdi5Z.mjs.map +1 -0
  43. package/dist/hooks.d.mts +30 -30
  44. package/dist/hooks.mjs +1828 -1304
  45. package/dist/hooks.mjs.map +1 -1
  46. package/dist/index.d.mts +11 -14
  47. package/dist/index.mjs +1273 -1051
  48. package/dist/index.mjs.map +1 -1
  49. package/dist/middleware.d.mts +1 -7
  50. package/dist/middleware.mjs +5 -8
  51. package/dist/middleware.mjs.map +1 -1
  52. package/dist/models.d.mts +4 -32
  53. package/dist/models.mjs +7 -11
  54. package/dist/models.mjs.map +1 -1
  55. package/dist/{peoplesoft-D6q3cYsH.d.mts → peoplesoft-C-zPdRVj.d.mts} +3 -9
  56. package/dist/{peoplesoft-BhintHQz.mjs → peoplesoft-RnvfLbWH.mjs} +5 -25
  57. package/dist/peoplesoft-RnvfLbWH.mjs.map +1 -0
  58. package/dist/{providers-BvuZWkpD.mjs → providers-BfFg_3eo.mjs} +5 -23
  59. package/dist/providers-BfFg_3eo.mjs.map +1 -0
  60. package/dist/{tokens-XuFhVbh5.mjs → tokens-C4SErO-K.mjs} +12 -8
  61. package/dist/tokens-C4SErO-K.mjs.map +1 -0
  62. package/dist/{utils-CaeVFWF-.mjs → utils-C2MZoH9U.mjs} +8 -39
  63. package/dist/utils-C2MZoH9U.mjs.map +1 -0
  64. package/dist/{utils-Bhi0KiBx.d.mts → utils-CNYCSgip.d.mts} +3 -5
  65. package/dist/utils-DnMFybj3.mjs +27 -0
  66. package/dist/utils-DnMFybj3.mjs.map +1 -0
  67. package/dist/utils.d.mts +11 -2
  68. package/dist/utils.mjs +3 -5
  69. package/dist/vite.d.mts +0 -2
  70. package/dist/vite.mjs +2 -4
  71. package/dist/vite.mjs.map +1 -1
  72. package/package.json +131 -131
  73. package/skills/ai/SKILL.md +136 -39
  74. package/skills/client-db/SKILL.md +104 -90
  75. package/skills/db-schema/SKILL.md +28 -20
  76. package/skills/dialogs/SKILL.md +26 -38
  77. package/skills/forms/SKILL.md +133 -73
  78. package/skills/general/SKILL.md +99 -105
  79. package/skills/general/references/auth.md +70 -0
  80. package/skills/migrations/versions/migrate-v10-to-v11.md +30 -4
  81. package/skills/routing/SKILL.md +60 -58
  82. package/skills/scanning/SKILL.md +67 -0
  83. package/skills/server-functions/SKILL.md +71 -26
  84. package/skills/services/SKILL.md +4 -4
  85. package/skills/services/docs/approval.md +70 -24
  86. package/skills/services/docs/email.md +24 -3
  87. package/skills/services/docs/file.md +69 -27
  88. package/skills/services/docs/peoplesoft.md +55 -39
  89. package/skills/start/steps/03-apm-setup.md +9 -9
  90. package/skills/table/SKILL.md +250 -267
  91. package/dist/AggregatedCell-oGcwbetF.mjs +0 -559
  92. package/dist/AggregatedCell-oGcwbetF.mjs.map +0 -1
  93. package/dist/Approval-DoD-GRRH.mjs.map +0 -1
  94. package/dist/DialogsContext-DLqA8RJ_.mjs.map +0 -1
  95. package/dist/Email-BzQQkbe9.mjs.map +0 -1
  96. package/dist/FileMeta-DDqUju1Y.mjs.map +0 -1
  97. package/dist/RouterListItemButton-ULMlaQh6.mjs +0 -80
  98. package/dist/RouterListItemButton-ULMlaQh6.mjs.map +0 -1
  99. package/dist/approval-L09uPzTU.mjs.map +0 -1
  100. package/dist/createApi-BhNkG4jz.mjs.map +0 -1
  101. package/dist/file-Chlljz3o.mjs.map +0 -1
  102. package/dist/file-Dl8JCcqy.mjs.map +0 -1
  103. package/dist/peoplesoft-BhintHQz.mjs.map +0 -1
  104. package/dist/providers-BvuZWkpD.mjs.map +0 -1
  105. package/dist/tokens-XuFhVbh5.mjs.map +0 -1
  106. package/dist/utils-CaeVFWF-.mjs.map +0 -1
  107. package/skills/general/references/exports.md +0 -114
@@ -11,49 +11,146 @@ metadata:
11
11
 
12
12
  ## Rules
13
13
 
14
- - The gateway needs three server-side inputs:
15
- - Ensure that required env are present: `AI_BASE_URL` (`z.url()`) and `AI_SUBSCRIPTION_KEY` (`z.string()`) in `src/env.ts`.
16
- - Ensure that `cognitiveServices: "https://cognitiveservices.azure.com/.default"` is added to
17
- `src/lib/auth/scopes.ts` and pass `getAppToken("cognitiveServices")` as the API key.
18
- - The subscription key sent as the `Ocp-Apim-Subscription-Key` header.
19
- - Build the adapter in one place, `src/server/ai.ts`, and call it per request. `getAppToken`
20
- caches and refreshes the token.
21
- - Use server functions, not `/api/chat` routes (overrides the upstream examples). `useChat` and the
22
- generation hooks take `fetcher` instead of `connection`; the server function returns
23
- `toServerSentEventsResponse(...)`. Add an `api/` route only when a public API is required.
24
- - Stream everything a user waits on. Use `useChat` for conversations and generation hooks for
25
- media. For a typed result, combine `outputSchema` and `stream: true` with
26
- `useChat({ fetcher, outputSchema })`, render `partial` as it fills in.
27
- - Render chat text with `@tanstack/markdown` (install if missing): `<Markdown>` from
28
- `@tanstack/markdown/react` with `extensions={[streamingMarkdownExtension()]}` from
29
- `@tanstack/markdown/extensions/streaming`.
14
+ - Install `@tanstack/ai` in the app (if missing); the server function imports it directly.
15
+ `@tanstack/charts` is a peer of wcz-layout, which npm installs with it; the chat loads it with
16
+ the first chart the model draws, so an app never defines a chart tool of its own.
17
+ - Require the gateway env in the app's `src/env.ts` `server` block, so a missing value fails at
18
+ startup: `AI_BASE_URL: z.url()` and `AI_SUBSCRIPTION_KEY: z.string()`. The gateway token also
19
+ uses the Entra app registration: `ENTRA_TENANT_ID`, `ENTRA_CLIENT_ID`, `ENTRA_CLIENT_SECRET`.
20
+ Values come from `.env.local` or Vault.
21
+ - Import the adapter from `wcz-layout/utils`: `adapter: await chatAdapter("gpt-5.5")`, created
22
+ per request inside the server function. It sends the app token and the subscription key itself.
23
+ Never build an OpenAI adapter in the app: `createOpenaiChat` (Responses API) fails on follow-ups
24
+ with `400 invalid_encrypted_content`, because the gateway load-balances Azure deployments.
25
+ - Call `chatAdapter` only in server functions (`src/server/...`): it reads server env and tokens.
26
+ - Build every chat with `createLayoutChatHook(chatFn)` from `wcz-layout/hooks`. Its labels are
27
+ `Layout.Chat.*` keys: copy the `Layout.Chat` object from wcz-layout's `src/lib/locales/*.json`
28
+ into each of the app's locale files, or the chat shows raw keys.
29
+ - An app-wide assistant is one chat on every page: a component rendering
30
+ `<LayoutChat chat={useLayoutChat({ threadId })} />`, passed as `LayoutProvider`'s
31
+ `options.chat`. It shows for a signed-in user, opens from the app bar and mounts on the first
32
+ open. From `lg` up it docks beside the page and remembers its width and whether it is open;
33
+ below `lg` it covers the page right of the navigation rail, opens only from the button and
34
+ closes when a page opens, so a link, `navigate` or the rail shows the page. A chat page of its own sits in a
35
+ parent with a height (e.g. `Fullscreen`). `LayoutChat` takes `sx` for its root, e.g. a background;
36
+ it has none of its own.
37
+ - Every chat has these client tools built in: `show_ui` (the model renders MUI components, and
38
+ charts: a `Chart` node with TanStack Charts marks as children, their official options as
39
+ props), `ask_user` (asks with an MUI form), `get_user` (the signed-in user), `set_app_theme` (light,
40
+ dark or system), `navigate` (opens one of the app's pages, listed from its route tree, and
41
+ leaves a page whose record was just deleted), `get_time` (the user's current time and zone,
42
+ so the prompt never states it), and `read_page`, `click`, `fill` and `press_key` (the model
43
+ uses the page the user is on as they would: it reads the text and numbered controls, clicks,
44
+ types and presses keys, and never answers a `useDialogs` confirmation). Never define them
45
+ again. The client sends its tools with every request, so the
46
+ server function only merges them: `tools: mergeAgentTools(serverTools, tools)`. It must also
47
+ forward `parentRunId` and `resume`, or tool results and approvals never continue the run.
48
+ - The chat sends the page the user is on as AG-UI context. Put it in the prompt: each
49
+ `aguiContext` item becomes a `"<description>: <value>"` line in `systemPrompts` (see the example).
50
+ - Data and writes are server tools (`toolDefinition(...).server(...)`) in `serverTools` that
51
+ call the app's own server functions, `deleteOrder({ data: id })`: called on the server they run
52
+ in the same request, with the screens' middleware, validation and permission checks. Never
53
+ reimplement a server function for a tool. After a write,
54
+ `context?.emitCustomEvent("invalidate", { queryKey })` makes the chat invalidate that query, so
55
+ open screens refetch.
56
+ - Only tools that delete get `needsApproval: true`: the chat asks "Are you sure?" (Cancel /
57
+ Confirm) before they run, so the prompt tells the model to say first what it will delete.
58
+ Creating and changing run straight away, and the model says what it did.
59
+ - Give feature tools `lazy: true` and pass `lazyToolsConfig: { includeDescription:
60
+ "first-sentence" }` to `chat()`: the model sees names and first sentences, and loads a feature's
61
+ schemas only when a request needs them. Write each description's first sentence to stand alone.
62
+ Pass `agentLoopStrategy: maxIterations(20)` too: the default 5 turns end a run without a reply
63
+ once discovering, looking up and saving add up.
64
+ - The page tools read what a screen reader would, so a page the model can use has a name on
65
+ every control: a `Tooltip` title or `aria-label` on each icon button, a label on each field,
66
+ and a button, link or `CardActionArea` for anything clickable. Deletes confirm through
67
+ `useDialogs`, which the model never clicks.
68
+ - Other browser actions are client tools:
69
+ `useLayoutChat({ threadId, tools: [def.client(run)] })`, with `run` using the screen's hooks.
70
+ - The chat renders markdown links to the app's own pages (`/...`) through the router; tell the
71
+ model the page paths so it links the records it mentions.
72
+ - Structured output (one typed object, e.g. a generated document) stays raw `useChat` with
73
+ `outputSchema` and `partial`, not the chat.
74
+ - Render streamed text outside the chat with `@tanstack/markdown` (install if missing):
75
+ `<Markdown>` from `@tanstack/markdown/react`.
30
76
 
31
77
  ## Example
32
78
 
33
79
  ```ts
34
- // src/server/ai.ts
35
- import { createOpenaiChat } from "@tanstack/ai-openai";
36
- import { getAppToken } from "wcz-layout/auth";
37
- import { serverEnv } from "~/env";
38
-
39
- export const aiText = async () =>
40
- createOpenaiChat("gpt-5.5", await getAppToken("cognitiveServices"), {
41
- baseURL: serverEnv.AI_BASE_URL,
42
- defaultHeaders: { "Ocp-Apim-Subscription-Key": serverEnv.AI_SUBSCRIPTION_KEY },
43
- });
80
+ // src/env.ts (server block)
81
+ AI_BASE_URL: z.url(),
82
+ AI_SUBSCRIPTION_KEY: z.string(),
83
+
84
+ // src/server/actions/assistant.ts
85
+ import {
86
+ chat,
87
+ chatParamsFromRequestBody,
88
+ maxIterations,
89
+ mergeAgentTools,
90
+ toServerSentEventsResponse,
91
+ toolDefinition,
92
+ } from "@tanstack/ai";
93
+ import type { RunAgentInput } from "@tanstack/ai/client";
94
+ import { createServerFn } from "@tanstack/react-start";
95
+ import { authMiddleware } from "wcz-layout/middleware";
96
+ import { chatAdapter } from "wcz-layout/utils";
97
+ import z from "zod";
98
+ import { deleteOrder } from "./order"; // the server function the screens call
99
+
100
+ const orderTools = () => [
101
+ toolDefinition({
102
+ name: "delete_order",
103
+ description: "Delete one of the user's orders.",
104
+ inputSchema: z.object({ id: z.uuid() }),
105
+ needsApproval: true,
106
+ lazy: true,
107
+ }).server(async ({ id }, context) => {
108
+ await deleteOrder({ data: id });
109
+ context?.emitCustomEvent("invalidate", { queryKey: ["orders"] });
110
+ return { deleted: id };
111
+ }),
112
+ ];
44
113
 
45
- // src/server/actions/chat.ts
46
- export const chatFn = createServerFn({ method: "POST" })
47
- .validator(z.object({ messages: z.array(z.custom<UIMessage>()) }))
114
+ export const assistant = createServerFn({ method: "POST" })
115
+ .validator(z.custom<RunAgentInput>())
48
116
  .middleware([authMiddleware()])
49
- .handler(async ({ data }) =>
50
- toServerSentEventsResponse(
51
- chat({ adapter: await aiText(), messages: data.messages, systemPrompts: [SYSTEM_PROMPT] }),
52
- ),
53
- );
54
-
55
- // component
56
- const { messages, sendMessage, isLoading, stop } = useChat({
57
- fetcher: ({ messages }, { signal }) => chatFn({ data: { messages }, signal }),
58
- });
117
+ .handler(async ({ data }) => {
118
+ const { messages, threadId, runId, parentRunId, resume, tools, aguiContext } =
119
+ await chatParamsFromRequestBody(data);
120
+ const abortController = new AbortController();
121
+ const stream = chat({
122
+ adapter: await chatAdapter("gpt-5.5"),
123
+ threadId,
124
+ runId,
125
+ parentRunId,
126
+ resume,
127
+ systemPrompts: [
128
+ SYSTEM_PROMPT,
129
+ ...aguiContext.map(({ description, value }) => `${description}: ${value}`),
130
+ ],
131
+ messages,
132
+ tools: mergeAgentTools(orderTools(), tools),
133
+ lazyToolsConfig: { includeDescription: "first-sentence" },
134
+ agentLoopStrategy: maxIterations(20),
135
+ abortController,
136
+ });
137
+ return toServerSentEventsResponse(stream, { abortController });
138
+ });
139
+ ```
140
+
141
+ ```tsx
142
+ // src/components/Assistant.tsx
143
+ import { createLayoutChatHook } from "wcz-layout/hooks";
144
+ import { assistant } from "~/server/actions/assistant";
145
+
146
+ const { useLayoutChat, LayoutChat } = createLayoutChatHook(assistant);
147
+
148
+ export function Assistant() {
149
+ const chat = useLayoutChat({ threadId: "assistant" });
150
+
151
+ return <LayoutChat chat={chat} />;
152
+ }
153
+
154
+ // src/routes/__root.tsx
155
+ <LayoutProvider navigation={navigation} theme={theme} options={{ chat: <Assistant /> }}>
59
156
  ```
@@ -1,136 +1,150 @@
1
1
  ---
2
2
  name: client-db
3
- description: "Use when reading or writing client data with TanStack DB: collections, live queries, route preloading, optimistic writes, eager/on-demand sync, or browser SQLite persistence."
3
+ description: "Use when routes or components read/write application-owned records with TanStack DB: collection descriptors, shared live query options, useLiveQuery/useLiveSuspenseQuery, loader preloading and SSR hydration, optimistic CRUD, joins, on-demand sync and paging, or data that is empty, fetched too broadly, stale or rolled back."
4
4
  metadata:
5
5
  type: convention
6
6
  library: wcz-layout
7
7
  ---
8
8
 
9
- > Mechanics (the live-query builder, `createOptimisticAction`, collection adapters,
10
- > browser persistence) are covered by TanStack's own skills. List the skills shipped by
11
- > `@tanstack/db` and `@tanstack/react-db` and load whichever cover the task at hand.
12
- > This skill adds the wcz-layout conventions on top, and overrides upstream where noted.
9
+ Query builder, operators, hooks and the transaction API: load `@tanstack/db#db-core` with its
10
+ `live-queries` and `mutations-optimistic` sub-skills, and `@tanstack/react-db#react-db`.
13
11
 
14
12
  ## Rules
15
13
 
16
- - One `DbClient` per request, built in `src/router.tsx` and put on the router context
17
- next to `queryClient`. Components reach it with `useDbClient()`, loaders with
18
- `context.dbClient`.
19
- - Declare collections as descriptors: `collectionOptions(id, (client) => ...)`. Take the
20
- query client from the factory with `client.requireDependency<QueryClient>("queryClient")`,
21
- never a module-scope one — it is built per request and a singleton leaks across SSR.
22
- - Export a `use<Table>Collection` hook next to each collection. It is the only way components
23
- get a live collection to write to.
24
- - Define every live query once in `src/db/queries/<table>.ts` as
25
- `{ query: (q: InitialQueryBuilder) => ... }`. Reuse that definition in loaders and
26
- components.
27
- - Preload in the route loader and return the promise:
28
- `loader: ({ context }) => context.dbClient.preloadLiveQuery(<x>QueryOptions)`.
29
- This transports the query result, so `useLiveQuery` has rows on the first render. Never
30
- fire it with `void`: the server then renders an empty table and the browser fetches
31
- again. Explicit collection preload transports source rows and is a no-op for on-demand
32
- collections.
33
- - A detail route awaits the preload, then throws `notFound()` when the row is missing,
34
- and shows a skeleton `pendingComponent` meanwhile (see the example).
35
- - `useLiveQuery` for list pages, `useLiveSuspenseQuery` for detail components under
36
- suspense. `.findOne()` still returns `T | undefined` after the loader's check, so keep
37
- an `if (!data) return null` guard.
38
- - Shape data in the query: filter, order, group and aggregate only the fields the
39
- consumer needs. Do not load broad results and transform them in component code.
40
- - Mutations go through `createOptimisticAction`: mirror the server write in `onMutate`,
41
- call the server function in `mutationFn`, then
42
- `await utils.refetch({ throwOnError: true })` on every collection that function writes.
43
- Await `transaction.isPersisted.promise` at the call site and surface failures with
44
- `alert()`.
45
- - `syncMode: "eager"` for top-level collections, `"on-demand"` for child data and anything expected past ~10k rows.
14
+ - `src/router.tsx` creates one `DbClient({ queryClient })` per request,
15
+ puts both on the router context and returns `routerWithDbClient(router, dbClient)`.
16
+ - A collection is a `collectionOptions` descriptor, never `createCollection` or a
17
+ module-scope `QueryClient`: both leak between SSR requests. `use<Entity>Collection`, next to
18
+ it, is how components get the collection to write to. `queryFn` calls the entity's select
19
+ server function with its Query `signal`, `schema` is its row schema. Include dynamic
20
+ collection scope in both `id` and `queryKey`; one client reuses the first descriptor per id.
21
+ - Each live query is defined once in `src/db/queries/<entity>.ts` and shared by loader and
22
+ component as the same config form, not just its `.query` callback. Business filters,
23
+ ordering, joins and aggregates belong there.
24
+ - Loaders preload and return the promise:
25
+ `loader: ({ context }) => context.dbClient.preloadLiveQuery(featuresQueryOptions)`, or
26
+ `Promise.all([...])` of every live query the page reads (a form's picker options too). SSR
27
+ then ships those queries' rows and the first render has data. Never `void` it (empty SSR),
28
+ never `collection.preload()` (a no-op on-demand), never `dbClient.collection()` in a loader
29
+ (it ships the collection's rows a second time).
30
+ - `setupRouterSsrQueryIntegration` also ships every query in the `QueryClient`: an eager
31
+ collection's whole table goes out even when the page preloads one row; on-demand collections
32
+ ship only the subsets they loaded. The browser still refetches after hydration.
33
+ - Lists read `useLiveQuery(options)` (`data`, `isLoading`). Detail and edit pages read
34
+ `useLiveSuspenseQuery(byIdOptions(id))` under the route's `pendingComponent`. `.findOne()`
35
+ still yields `T | undefined`: render `<RouterNotFound />` for a missing row, which also
36
+ covers one deleted while the page is open.
37
+ - Every write is a `createOptimisticAction`: `onMutate` mirrors the change on the collection;
38
+ `mutationFn` awaits the server function, then `utils.refetch({ throwOnError: true })` on
39
+ every collection it changed. The caller awaits `when("settled")` in `try`; `catch` alerts
40
+ `error.message` (the optimistic change has already rolled back).
41
+ - Serialize writes that can overlap on one collection (scanner input, repeated Enter): each
42
+ `utils.refetch` cancels the one in flight, and with three or more overlapping writes all but
43
+ the last two actions roll back with `CancelledError` although the server saved. Queue them
44
+ with `usePacedMutations` + `queueStrategy` or a promise chain.
45
+ - One query per parent, never `useLiveQuery` per row: `DbClient` queries don't pool, so 50 rows
46
+ make 50 queries and requests. Load children with `inArray(child.parentId, ids)` and split
47
+ them in the component.
48
+ - `groupBy` selects grouped columns, expressions over them (`coalesce(a, b)`) and aggregates.
49
+ A grouped row has no `id`; select one when `LayoutTable` shows it (table).
50
+
51
+ ## Sync mode
52
+
53
+ - **eager** (default): the collection loads whole. Small reference data/top-level tables;
54
+ ~10k rows is a sizing heuristic, not a safe payload or memory limit.
55
+ - **on-demand**: each live query loads only its subset, with `where`, `orderBy` and `limit`
56
+ eligible for server push-down, not a guarantee for every query plan. Bigger tables and child
57
+ rows read per parent. agnostic-query carries
58
+ the subset to Drizzle (`agnostic-query#adapters`; server function in server-functions). The
59
+ collection adds:
60
+
61
+ ```ts
62
+ // fromTanDb from agnostic-query/tanstack-db, BasicIndex from @tanstack/react-db
63
+ syncMode: "on-demand",
64
+ queryFn: ({ meta, signal }) =>
65
+ selectFeatures({ data: fromTanDb(meta?.loadSubsetOptions), signal }),
66
+ autoIndex: "eager",
67
+ defaultIndexType: BasicIndex,
68
+ defaultStringCollation: { stringSort: "lexical" },
69
+ ```
70
+
71
+ Without the index, an ordered `limit` query warns and can load the whole table; with the
72
+ default locale string sort, ordering by any text field (uuid ids included) does. Lexical
73
+ order matches Postgres for uuid, number and date columns; a text sort column needs
74
+ `COLLATE "C"` on the server.
75
+
76
+ - Joining two on-demand collections: `leftJoin` from the side the `where` narrows. `innerJoin`
77
+ loads the smaller side first and, on a tie (both still empty), the joined collection whole.
78
+ - Collections don't page on the server: page N's first request reads rows 0 to N × size (no
79
+ offset reaches `queryFn`), and nothing counts the server's rows for the pager. Tables over
80
+ more rows than the browser should hold page with TanStack Query (table).
46
81
 
47
82
  ## Examples
48
83
 
49
84
  ```ts
50
- // src/db/collections/<table>.ts
85
+ // src/db/collections/feature.ts
51
86
  import { queryCollectionOptions } from "@tanstack/query-db-collection";
52
87
  import { collectionOptions, useDbClient } from "@tanstack/react-db";
53
88
  import type { QueryClient } from "@tanstack/react-query";
54
- import { TodoSchema } from "~/lib/schemas/todo";
55
- import { selectTodos } from "~/server/actions/todo";
89
+ import { FeatureSchema } from "~/lib/schemas/feature";
90
+ import { selectFeatures } from "~/server/actions/feature";
56
91
 
57
- const TODOS_ID = "todos";
92
+ const FEATURES_ID = "features";
58
93
 
59
- export const todoCollection = collectionOptions(TODOS_ID, (client) =>
94
+ export const featureCollection = collectionOptions(FEATURES_ID, (client) =>
60
95
  queryCollectionOptions({
61
- id: TODOS_ID,
62
- queryKey: [TODOS_ID],
63
- queryFn: () => selectTodos(),
96
+ id: FEATURES_ID,
97
+ queryKey: [FEATURES_ID],
98
+ queryFn: ({ signal }) => selectFeatures({ signal }),
64
99
  getKey: ({ id }) => id,
65
- schema: TodoSchema,
100
+ schema: FeatureSchema,
66
101
  queryClient: client.requireDependency<QueryClient>("queryClient"),
67
- syncMode: "eager",
68
102
  }),
69
103
  );
70
104
 
71
- export const useTodoCollection = () => useDbClient().collection(todoCollection);
105
+ export const useFeatureCollection = () => useDbClient().collection(featureCollection);
72
106
  ```
73
107
 
74
108
  ```ts
75
- // src/db/queries/<table>.ts
109
+ // src/db/queries/feature.ts
76
110
  import type { InitialQueryBuilder } from "@tanstack/react-db";
77
111
  import { eq } from "@tanstack/react-db";
78
- import { todoCollection } from "../collections/todo";
112
+ import { featureCollection } from "../collections/feature";
79
113
 
80
- export const todosQueryOptions = {
114
+ // uuidv7 sorts client creation time, not database insertion order.
115
+ export const featuresQueryOptions = {
81
116
  query: (q: InitialQueryBuilder) =>
82
- q.from({ todo: todoCollection }).orderBy(({ todo }) => todo.id, "desc"),
117
+ q.from({ feature: featureCollection }).orderBy(({ feature }) => feature.id, "desc"),
83
118
  };
84
119
 
85
- export const todoByIdQueryOptions = (id: string) => ({
120
+ export const featureByIdQueryOptions = (id: string) => ({
86
121
  query: (q: InitialQueryBuilder) =>
87
122
  q
88
- .from({ todo: todoCollection })
89
- .where(({ todo }) => eq(todo.id, id))
123
+ .from({ feature: featureCollection })
124
+ .where(({ feature }) => eq(feature.id, id))
90
125
  .findOne(),
91
126
  });
92
127
  ```
93
128
 
94
129
  ```tsx
95
- // detail route: src/routes/todos/$id.tsx
96
- export const Route = createFileRoute("/todos/$id")({
97
- component: RouteComponent,
98
- pendingComponent: TodoSkeleton,
99
- beforeLoad: requireAuth("admin"),
100
- loader: async ({ context, params }) => {
101
- await context.dbClient.preloadLiveQuery(todoByIdQueryOptions(params.id));
102
- if (!context.dbClient.collection(todoCollection).has(params.id)) throw notFound();
130
+ // a write in a component. update: features.update(id, (draft) => Object.assign(draft, value));
131
+ // delete: ids.forEach((id) => features.delete(id)) with deleteFeatures({ data: ids })
132
+ const features = useFeatureCollection();
133
+
134
+ const handleOnSubmit = createOptimisticAction<Feature>({
135
+ onMutate: (value) => {
136
+ features.insert(value);
137
+ },
138
+ mutationFn: async (value) => {
139
+ await insertFeature({ data: value });
140
+ await features.utils.refetch({ throwOnError: true });
103
141
  },
104
142
  });
105
143
 
106
- function RouteComponent() {
107
- const { id } = Route.useParams();
108
- const { alert } = useDialogs();
109
- const navigate = useNavigate();
110
- const todos = useTodoCollection();
111
- const { data } = useLiveSuspenseQuery(todoByIdQueryOptions(id));
112
-
113
- const handleOnDelete = createOptimisticAction<string>({
114
- onMutate: (id) => {
115
- todos.delete(id);
116
- },
117
- mutationFn: async (id) => {
118
- await deleteTodos({ data: [id] });
119
- await todos.utils.refetch({ throwOnError: true });
120
- },
121
- });
122
-
123
- const handleDelete = async () => {
124
- try {
125
- const transaction = handleOnDelete(id);
126
- await transaction.isPersisted.promise;
127
- await navigate({ to: "/todos" });
128
- } catch (error) {
129
- if (error instanceof Error) await alert(error.message);
130
- }
131
- };
132
-
133
- if (!data) return null;
134
- // render data; call handleDelete from the delete button...
144
+ try {
145
+ await handleOnSubmit(value).when("settled");
146
+ await navigate({ to: "/features" });
147
+ } catch (error) {
148
+ if (error instanceof Error) await alert(error.message);
135
149
  }
136
150
  ```
@@ -1,27 +1,38 @@
1
1
  ---
2
2
  name: db-schema
3
- description: "Use when changing PostgreSQL tables, columns, constraints, indexes, enums, foreign keys, relations, migrations, or Drizzle-derived Zod schemas in a wcz-layout app."
3
+ description: "Use when adding or changing PostgreSQL tables, columns, constraints, indexes, enums, foreign keys or relations with Drizzle, the Zod schema and type derived from a table, validation messages, or when a migration is asked for."
4
4
  metadata:
5
5
  type: convention
6
6
  library: wcz-layout
7
7
  ---
8
8
 
9
- # Database schema patterns
9
+ Migration commands and drizzle-kit output: load `drizzle-kit#drizzle-migrations` and
10
+ `drizzle-kit#drizzle-generate`.
10
11
 
11
12
  ## Rules
12
13
 
13
- - One table per file, named after the table (e.g. `bookTable` lives in `book.ts`). Never put multiple tables in one file, even when they are related — a parent and its children each get their own file.
14
- - Use `uuid` for application-table primary keys and `snakeCase` for generating tables.
15
- - For `uuid` columns, do not generate random values in the schema. The client generates the id with `uuidv7()` from `wcz-layout/utils` when creating the record.
16
- - Always add `withTimezone: true` to timestamp columns.
17
- - Always declare `onDelete` explicitly on every foreign key — never rely on the default. Pick the behavior from the business rule: `"cascade"` when the child is meaningless without its parent, `"restrict"` when the parent must not be deleted while children exist, `"set null"` for optional references.
18
- - Index every foreign key column. Postgres does not create one for you.
19
- - Define relations in a central `relations.ts` file.
20
- - Declare enums with `pgEnum` in the table's own file, export them, and reference `enumValues` everywhere else — never re-declare the values.
21
- - Generate the full client record schema with `createSelectSchema` from `drizzle-orm/zod`. Use `createInsertSchema`; override fields with stricter rules (trim, min/max) where needed.
22
- - The second argument of `createSelectSchema` refines **existing columns only**. Adding a key
23
- that is not a column is a type error. Attach related data with `.extend()` after it.
24
- - Do not auto-generate migrations unless the user explicitly asks. When asked, run `npm run db:generate`; migrations apply automatically at app startup while `DATABASE_AUTO_MIGRATE=true`.
14
+ - One table per file in `src/server/db/schemas/`, named after it (`bookTable` in `book.ts`),
15
+ even for a parent and its children. Tables use `snakeCase.table("<plural>", …)`.
16
+ - Primary key `id: uuid().primaryKey()` with no default: the client creates the id with
17
+ `uuidv7()`.
18
+ - Timestamps: `timestamp({ withTimezone: true })`.
19
+ - Foreign keys declare `onDelete` from the business rule: `"cascade"` when the child is
20
+ meaningless without the parent, `"restrict"` when the parent must outlive its children,
21
+ `"set null"` for optional references. Index every foreign key column; Postgres does not.
22
+ - Enums: `pgEnum` in the table's file, exported; everything else reads `.enumValues`, never
23
+ a second list.
24
+ - Relations live in the one `relations.ts` (`defineRelations`), never in table files.
25
+ - The entity's Zod schema is `createSelectSchema(table, refinements)` from `drizzle-orm/zod`
26
+ in `src/lib/schemas/<entity>.ts`, with `export type <Entity> = z.infer<…>`. The client builds
27
+ whole rows, id included, so this one schema validates the form, the collection and the
28
+ server function input.
29
+ - Refinements tighten existing columns only (an unknown key is a type error): text gets
30
+ `.trim()`, `.min(1)` when required, `.max(n)`. Add related or derived fields with `.extend()`.
31
+ - Messages are lazy: `{ error: () => t("Validation.Required") }`. A plain `t(...)` runs once at
32
+ import, before the user's language is known, and never follows a language switch.
33
+ - Every table is audited: startup runs `attach_audit_triggers_all()` and `databaseMiddleware`
34
+ sets the acting user. Never add history tables or audit triggers.
35
+ - Migrations apply at startup.
25
36
 
26
37
  ## Examples
27
38
 
@@ -77,21 +88,18 @@ export const relations = defineRelations(
77
88
  ```
78
89
 
79
90
  ```ts
80
- // src/lib/schemas/<table>.ts
91
+ // src/lib/schemas/<entity>.ts
81
92
  import { createSelectSchema } from "drizzle-orm/zod";
82
93
  import { t } from "wcz-layout/utils";
83
94
  import type { z } from "zod";
84
95
  import { bookTable } from "~/server/db/schemas/book";
85
- import { PageSchema } from "./page";
86
96
 
87
97
  export const BookSchema = createSelectSchema(bookTable, {
88
98
  title: (schema) =>
89
99
  schema
90
100
  .trim()
91
- .min(1, t("Validation.Required"))
92
- .max(255, t("Validation.MaxLength", { length: 255 })),
93
- }).extend({
94
- pages: PageSchema.array().min(1, t("Validation.Required")),
101
+ .min(1, { error: () => t("Validation.Required") })
102
+ .max(255, { error: () => t("Validation.MaxLength", { length: 255 }) }),
95
103
  });
96
104
 
97
105
  export type Book = z.infer<typeof BookSchema>;
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: dialogs
3
- description: "Use for acknowledgement alerts, confirmation prompts, or custom MUI Dialogs opened through useDialogs."
3
+ description: "Use when app needs an alert, a confirmation before a destructive or irreversible action, an error message to acknowledge, or a custom MUI Dialog (create/edit dialog, picker, scanner) opened from code with useDialogs and awaited for its result."
4
4
  metadata:
5
5
  type: convention
6
6
  library: wcz-layout
@@ -8,51 +8,39 @@ metadata:
8
8
 
9
9
  ## Rules
10
10
 
11
- - Use `useDialogs()` instead of mounting another provider. It returns `{ alert, confirm, open, close }`.
12
- - Use `confirm()` for destructive or user-confirmed actions.
13
- - Use `alert()` for informational or error messages that require acknowledgement.
14
- - Use `open()` for feature-specific custom dialogs with typed payloads.
15
- - Custom dialogs receive `DialogProps<TPayload, TResult>`. `open()` resolves with
16
- whatever the dialog passes to `onClose(result)`, so a dialog that answers a
17
- question declares its result type and the caller awaits it. Leave `TResult` off
18
- only for dialogs that return nothing.
19
- - Use `close(dialog, result)` only to close outside the dialog component, passing the
20
- promise returned by `open()`. Custom dialogs normally call their injected `onClose(result)`.
21
- - Colocate feature-specific dialogs in `routes/<feature>s/-components`; put dialogs used by more than one route in `src/components`.
11
+ - `useDialogs()` from `wcz-layout/hooks` returns `{ alert, confirm, open, close }`;
12
+ `LayoutProvider` already mounts the provider.
13
+ - `confirm(message)` resolves `true`/`false`; ask it before every delete and other
14
+ irreversible action. Delete prompts use `t("DeleteConfirmation", { count })`.
15
+ - `alert(message)` for anything the user must acknowledge, first of all a failed action:
16
+ `if (error instanceof Error) await alert(error.message)`.
17
+ - `open(Component, payload)` renders a custom dialog and resolves with what it passes to
18
+ `onClose(result)`. Type it `DialogProps<TPayload, TResult>`; leave `TResult` off only for
19
+ dialogs that return nothing. Never keep dialog open-state in the caller.
20
+ - `close(dialogPromise, result)` closes a dialog from outside, with the promise `open()`
21
+ returned; inside, call the injected `onClose`.
22
+ - Save inside the dialog: await persistence, then `onClose(success)`. The optional
23
+ `open(..., { onClose })` callback is not a veto: the provider closes even if it rejects.
24
+ Do not put a fallible save there and expect the form to stay open.
25
+ - A feature's dialogs live in `routes/<entities>/-components`, shared ones in `src/components`.
22
26
 
23
27
  ## Examples
24
28
 
25
29
  ```tsx
26
- // confirmation dialog
27
- const { confirm } = useDialogs();
28
- const { t } = useTranslation();
29
-
30
- const confirmed = await confirm(t("DeleteConfirmation", { count: selectedIds.length }));
31
- if (confirmed) await deleteFeatures({ data: selectedIds });
32
- ```
33
-
34
- ```tsx
35
- // alert dialog
36
- const { alert } = useDialogs();
37
- const { t } = useTranslation();
38
-
39
- try {
40
- await saveFeature(values);
41
- } catch (error) {
42
- await alert(error instanceof Error ? error.message : t("UnknownError"));
30
+ const { confirm, alert, open } = useDialogs();
31
+
32
+ if (await confirm(t("DeleteConfirmation", { count: ids.length }))) {
33
+ try {
34
+ await handleOnDelete(ids).when("settled");
35
+ } catch (error) {
36
+ if (error instanceof Error) await alert(error.message);
37
+ }
43
38
  }
44
- ```
45
-
46
- ```tsx
47
- // custom dialog that returns a result
48
- const { open } = useDialogs();
49
39
 
50
40
  const saved = await open(EditFeatureDialog, { id });
51
- if (saved) await features.utils.refetch({ throwOnError: true });
52
41
  ```
53
42
 
54
43
  ```tsx
55
- // custom dialog component
56
44
  interface Payload {
57
45
  id: string;
58
46
  }
@@ -62,11 +50,11 @@ export const EditFeatureDialog = ({ payload, open, onClose }: DialogProps<Payloa
62
50
 
63
51
  return (
64
52
  <Dialog fullWidth open={open} onClose={() => onClose(false)}>
65
- <DialogTitle>{t("EditFeature")}</DialogTitle>
53
+ <DialogTitle>{t("Feature.Confirm")}</DialogTitle>
66
54
  <DialogContent>{payload.id}</DialogContent>
67
55
  <DialogActions>
68
56
  <Button onClick={() => onClose(false)}>{t("Cancel")}</Button>
69
- <Button onClick={() => onClose(true)}>{t("Save")}</Button>
57
+ <Button onClick={() => onClose(true)}>{t("Confirm")}</Button>
70
58
  </DialogActions>
71
59
  </Dialog>
72
60
  );