@umituz/web-hono 1.2.0 → 1.3.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.
package/README.md CHANGED
@@ -1,16 +1,28 @@
1
1
  # @umituz/web-hono
2
2
 
3
- The Hono backend contract for single-Worker apps on Cloudflare (SPA assets + `/api/*` Hono) with Neon Postgres via drizzle. It packages the cross-cutting API skeleton proven in production by the pilot app [foodora](https://foodora.umituz998.workers.dev): the `crudRoutes` factory, `pickPatch`/`uid`, `getDb`, the JSON-404 and SPA-fallback handlers, the zod body-validation contract, the same-origin API client, the fetch-backed reactive store (+React hooks), and the shared-Neon database lifecycle scripts.
3
+ The API backend platform for single-Worker apps on Cloudflare (SPA assets + `/api/*` Hono) with Neon Postgres via drizzle. It packages the cross-cutting skeleton proven across the fleet (pilot: [foodora](https://foodora.umituz998.workers.dev)): the `createApi` app factory, the `{ error, details? }` error layer, the full-CRUD resource factory, the schema→client **type bridge**, the same-origin API client, the fetch-backed reactive store (+React hooks), and the shared-Neon database lifecycle scripts.
4
4
 
5
5
  The package is **source-distributed** (published as raw TypeScript in `src/`). Wrangler, Vite, and tsc all compile it alongside your app; no prebuilt bundle ships.
6
6
 
7
+ **1.3 is strictly additive**: every new capability is opt-in — omit the option and you get the exact 1.2 behavior.
8
+
7
9
  ## Design philosophy
8
10
 
9
- - **Contract, not framework.** The package owns cross-cutting conventions only — the error envelope (`{ error, details? }`), the soft-delete list read, the setting-patch idiom, literal status codes. Your schema, `TABLE_PREFIX`, zod schemas, domain routers, and business rules stay in your app.
10
- - **The factory has a hard scope.** `crudRoutes` covers list + setting-patch ONLY: "does this PATCH merely change a column value?" Entities with business rules (transitions, restock, overlap guards) stay hand-written in their area router — writing factory-covered code by hand and stuffing out-of-scope behavior into the factory are both contract violations.
11
- - **Store-agnostic client, batteries-included store.** `apiFetch`/`apiWrite` never import your store — but `createStore` gives you the whole client cache machine (hydrate-once, targeted refresh, pub/sub, store-bound `apiWrite`) in one call. Your app supplies only what IS the app: the `Database` shape, the collection→endpoint map, the empty state.
11
+ - **Contract, not framework.** The package owns cross-cutting conventions only — the error envelope, the soft-delete list read, the setting-patch idiom, literal status codes. Your schema, `TABLE_PREFIX`, zod schemas, domain routers, and business rules stay in your app.
12
+ - **The factory has a hard scope.** `crudRoutes` covers list + create + setting-patch + soft-delete for PLAIN rows only: "does this request merely change a column value?" Entities with business rules (transitions, restock, overlap guards) stay hand-written in their area router.
13
+ - **The schema is the single source of truth.** Client types DERIVE from the drizzle schema (`ClientRow<typeof products>`) — no hand-mirrored interface files that silently drift.
12
14
  - **Shared-Neon safety.** The lifecycle scripts drop only tables carrying your project's `TABLE_PREFIX` and refuse to run the moment they see a prefix-less table — one Neon project hosts a whole fleet of products.
13
15
 
16
+ ## The five pillars
17
+
18
+ | Pillar | What it replaces | Entry |
19
+ |---|---|---|
20
+ | `createApi({ service, build, routers, middleware })` | the per-app `api/index.ts` skeleton, `routes/health.ts`, hand-mounted 404/SPA handlers | `.` |
21
+ | `ApiError` + `apiOnError` | unhandled 500s, inconsistent error bodies; maps zod→400, pg unique→409 | `.` |
22
+ | `crudRoutes` with opt-in `create`/`remove` + `?limit&offset&order` | every hand-written POST/DELETE/list-pagination route for plain rows | `.` |
23
+ | `Row<T>` / `ClientRow<T>` type bridge | hand-mirrored client interfaces (foodora: 1215 lines) | `/types` |
24
+ | store `read`/`view`/`http`/`immutable` + `useCollection`/`useHydration` | repo prologues, tenant-view hand-rolls, boot-gate providers | `/store`, `/store/react` |
25
+
14
26
  ## Installation
15
27
 
16
28
  ```bash
@@ -19,50 +31,81 @@ npm install @umituz/web-hono
19
31
 
20
32
  Peer dependencies (install alongside): `hono ^4`, `drizzle-orm ^0.45`, `@neondatabase/serverless ^1`, `zod ^4`.
21
33
 
22
- ## Entry points
23
-
24
- | Entry point | Exports | Used by |
25
- |---|---|---|
26
- | `@umituz/web-hono` | `crudRoutes`, `CrudSpec`/`CrudTable`, `getDb`, `uid`, `pickPatch`, `apiNotFound`, `spaFallback`, `ApiEnv` | `api/index.ts`, area routers, `api/db.ts` |
27
- | `@umituz/web-hono/validator` | `validateJson(schema, message?)` | every hand-written POST/PATCH route |
28
- | `@umituz/web-hono/client` | `apiFetch<T>`, `apiWrite<T>` | `src/data/http.ts`, repositories |
29
- | `@umituz/web-hono/store` | `createStore`, `StoreConfig`, `REFETCH_ALL` | `src/data/store.ts` (the app's whole cache layer) |
30
- | `@umituz/web-hono/store/react` | `makeStoreHooks(store)` → `useQuery`, `useDbValue`, `QueryResult` | `src/core/useQuery.ts` (react is an optional peer) |
31
- | `@umituz/web-hono/lifecycle` | `resetTables`, `snapshotToSeed`, `seedFromSnapshot`, `TableSpec`, `SeedSnapshot` | `scripts/reset.ts` / `snapshot.ts` / `seed.ts` wrappers |
32
-
33
34
  ## Quick start
34
35
 
35
- **1. Worker entry** (`api/index.ts`) — mount list, then close the chain:
36
+ **1. Worker entry** (`api/index.ts`) — the whole skeleton in one call:
36
37
 
37
38
  ```ts
38
- import { Hono } from 'hono';
39
- import { apiNotFound, spaFallback } from '@umituz/web-hono';
40
- import type { ApiEnv } from '@umituz/web-hono';
41
- import { healthRouter } from './routes/health';
39
+ import { createApi } from '@umituz/web-hono';
42
40
  import { orgRouter } from './routes/org';
41
+ import { cateringRouter } from './routes/catering';
42
+
43
+ export default createApi({
44
+ service: 'foodora-api',
45
+ build: BUILD_MARKER, // CI-injected deploy canary
46
+ routers: [['/suppliers', suppliersRouter], ['/', orgRouter]],
47
+ middleware: [/* auth, logging — /api only */],
48
+ });
49
+ ```
43
50
 
44
- const app = new Hono<{ Bindings: ApiEnv }>();
51
+ The chain: `/api/health` (canary, deliberately before middleware so uptime probes stay open) → your middleware → your routers → `onError` (the envelope) → unmatched `/api/*` stays JSON 404 → everything else resolves via the ASSETS binding (SPA). Hand-mounted apps keep working: `app.onError(apiOnError)` is exported standalone.
45
52
 
46
- app.route('/api/health', healthRouter);
47
- app.route('/api', orgRouter);
53
+ **2. Error layer** — throw `ApiError`, get the envelope:
48
54
 
49
- app.all('/api/*', apiNotFound); // unmatched API stays JSON — never the SPA's index.html
50
- app.get('*', spaFallback); // client-side routes resolve via the ASSETS binding
55
+ ```ts
56
+ import { ApiError } from '@umituz/web-hono';
51
57
 
52
- export default app;
58
+ throw ApiError.notFound('Product'); // → 404 { error: 'Product not found' }
59
+ throw ApiError.badRequest('Bad input', details); // → 400 { error, details }
53
60
  ```
54
61
 
55
- **2. Factory mounts** (area routers) — plain settings/catalog entities:
62
+ `apiOnError` maps: `ApiError` → its own status · `ZodError` → `400 { error, details: fieldErrors }` · postgres `23505` unique violation (direct or driver-nested) → `409 { error: 'Already exists' }` · anything else → generic `500` with `console.error` server-side — internals never leak.
63
+
64
+ **3. Resource factory** (area routers) — plain settings/catalog entities:
56
65
 
57
66
  ```ts
58
67
  import { crudRoutes } from '@umituz/web-hono';
68
+ import { CreateBranchSchema } from '../schemas';
69
+
70
+ orgRouter.route('/', crudRoutes({
71
+ path: '/branches',
72
+ table: branches,
73
+ label: 'Branch',
74
+ orderBy: { col: branches.name },
75
+ create: { schema: CreateBranchSchema, prefix: 'brn' }, // opt-in POST → 201
76
+ remove: true, // opt-in DELETE → soft-delete
77
+ }));
78
+ ```
79
+
80
+ Generates:
81
+
82
+ - `GET /api/branches` — visible rows, ordered; optional `?limit=&offset=&order=name` / `order=-name` (columns whitelisted; limit capped at 500)
83
+ - `POST /api/branches` — zod-validated body, server `uid('brn')` id (client ids never land), `defaults(c)` server stamps UNDER the body → `201`
84
+ - `PATCH /api/branches/:id` — pickPatch-filtered body, `updatedAt` stamp, `404 'Branch not found'`
85
+ - `DELETE /api/branches/:id` — soft delete → `{ ok: true }` / `404`
86
+
87
+ Omit `create`/`remove` and exactly GET + PATCH register — the 1.x surface. `listRoutes` is the GET-only sibling for append-only collections (event logs, users). `db` is injectable (`db: (c) => myDb`) — the default builds a per-request neon-http instance as before.
59
88
 
60
- orgRouter.route('/', crudRoutes({ path: '/branches', table: branches, label: 'Branch', orderBy: { col: branches.name } }));
89
+ **4. Schema helpers + type bridge** — one encoding of the fleet conventions:
90
+
91
+ ```ts
92
+ // api/schema.ts
93
+ import { trio } from '@umituz/web-hono';
94
+ export const branches = pgTable(`${TABLE_PREFIX}branches`, {
95
+ id: text('id').primaryKey(),
96
+ name: text('name'),
97
+ ...trio(), // createdAt/updatedAt/deletedAt timestamptz, fleet-standard
98
+ });
61
99
  ```
62
100
 
63
- Generates `GET /api/branches` (visible rows, ordered) + `PATCH /api/branches/:id` (pickPatch-filtered body, `updatedAt` stamp, `404 'Branch not found'`).
101
+ ```ts
102
+ // src/domain — client types DERIVE, they don't drift
103
+ import type { ClientRow, NewRow } from '@umituz/web-hono/types';
104
+ export type Branch = ClientRow<typeof branches>; // Date→string mapped: the wire shape
105
+ export type NewBranch = NewRow<typeof branches>;
106
+ ```
64
107
 
65
- **3. Validated writes** — the single definition of the body contract:
108
+ **5. Validated writes** — the single definition of the body contract:
66
109
 
67
110
  ```ts
68
111
  import { validator } from 'hono/validator';
@@ -77,49 +120,42 @@ app.post(
77
120
 
78
121
  Failures answer `400 { error: <message>, details: <fieldErrors> }` — the envelope every client toast surfaces.
79
122
 
80
- **4. App db wrapper** (`api/db.ts`) — bind your schema once:
81
-
82
- ```ts
83
- import { getDb } from '@umituz/web-hono';
84
- import * as schema from './schema';
85
-
86
- export const getDbBound = (env: { DATABASE_URL: string }) => getDb(env, schema);
87
- ```
88
-
89
- **5. Frontend data layer** — the app owns its shape, the package owns the machine:
123
+ **6. Frontend data layer** — the app owns its shape, the package owns the machine:
90
124
 
91
125
  ```ts
92
126
  // src/data/store.ts — this file IS the app's data layer now
93
127
  import { createStore } from '@umituz/web-hono/store';
94
128
 
95
129
  export interface Database { orders: Order[]; loyalty: LoyaltyProgram; /* … */ }
96
- export type CollectionKey = keyof Database;
97
130
 
98
- const ENDPOINTS: Record<CollectionKey, string> = { orders: '/api/orders', loyalty: '/api/loyalty', /* … */ };
99
- const emptyDatabase = (): Database => ({ orders: [], loyalty: EMPTY_LOYALTY });
131
+ export const store = createStore<Database>({
132
+ endpoints: { orders: '/api/orders', loyalty: '/api/loyalty' },
133
+ empty: (): Database => ({ orders: [], loyalty: EMPTY_LOYALTY }),
134
+ immutable: true, // opt-in: fresh array refs per load — React memo-safe
135
+ });
100
136
 
101
- export const store = createStore<Database>({ endpoints: ENDPOINTS, empty: emptyDatabase });
102
- export const { ensureHydrated, refresh, getDb, subscribe, apiWrite } = store;
103
- ```
137
+ // Repos drop the prologue and the http.ts re-export file:
138
+ const findOrder = (id: string) => store.read((db) => db.orders.find((o) => o.id === id));
139
+ await store.http.write('/api/orders', { method: 'POST', json: payload }, ['orders']);
104
140
 
105
- ```ts
106
- // src/data/http.ts — two re-exports, nothing else
107
- export { apiFetch } from '@umituz/web-hono/client';
108
- export { apiWrite } from './store';
141
+ // Tenant/derived views stop being hand-rolled:
142
+ const activeOrg = store.view(['organizations'], (db) => db.organizations.find((o) => o.id === orgId));
109
143
  ```
110
144
 
111
145
  ```ts
112
- // src/core/useQuery.ts — hooks bound to the store (react: optional peer)
146
+ // src/core/hooks.ts — bound to the store (react: optional peer)
113
147
  import { makeStoreHooks } from '@umituz/web-hono/store/react';
114
- import { store } from '@/data/store';
115
148
 
116
- export const { useQuery, useDbValue } = makeStoreHooks(store);
117
- export type { QueryResult } from '@umituz/web-hono/store/react';
149
+ export const { useQuery, useDbValue, useCollection, useHydration } = makeStoreHooks(store);
150
+
151
+ // App boot gate — replaces hand-rolled hydration providers:
152
+ const { status, error, retry } = useHydration();
153
+ const orders = useCollection('orders'); // typed, re-renders on its channel
118
154
  ```
119
155
 
120
- The machine: first read hydrates every collection in parallel (deduped, retried on failure); repositories read synchronously via `getDb()`; writes go through `store.apiWrite(path, init, keys)` which refreshes only the touched collections on success and leaves the cache untouched on failure; per-collection pub/sub (plus the `__refetch_all__` wildcard) drives the hooks. Singleton collections (org-per-row settings like `loyalty`) load with the same call — no special-casing.
156
+ The machine: first read hydrates every collection in parallel (deduped, retried on failure); repositories read synchronously via `getDb()` or `store.read(fn)`; writes go through `store.apiWrite(path, init, keys)` / `store.http.write` which refresh only the touched collections on success and leave the cache untouched on failure; per-collection pub/sub (plus the `__refetch_all__` wildcard) drives the hooks; `view(keys, selector)` gives change-detected derived reads.
121
157
 
122
- **6. Lifecycle scripts** (`scripts/`) — keep only your `TABLE_SPECS` registry and thin wrappers:
158
+ **7. Lifecycle scripts** (`scripts/`) — keep only your `TABLE_SPECS` registry and thin wrappers:
123
159
 
124
160
  ```ts
125
161
  // scripts/snapshot.ts
@@ -132,16 +168,37 @@ if (!url) throw new Error('DATABASE_URL is required (.env)');
132
168
  await snapshotToSeed({ specs: TABLE_SPECS, url, outPath: new URL('./seed-data.json.gz', import.meta.url) });
133
169
  ```
134
170
 
135
- `resetTables({ specs, prefix, url })` drops only `prefix*` tables (in reverse registry order, CASCADE); `seedFromSnapshot({ specs, url, inPath })` replays idempotently (ON CONFLICT DO NOTHING, 200-row chunks, per-column-type revival of timestamps/dates).
171
+ `resetTables({ specs, prefix, url })` drops only `prefix*` tables (reverse registry order, CASCADE, safety-stopped); `seedFromSnapshot({ specs, url, inPath })` replays idempotently (ON CONFLICT DO NOTHING, 200-row chunks, per-column-type revival of timestamps/dates).
172
+
173
+ ## Entry points
174
+
175
+ | Entry point | Exports |
176
+ |---|---|
177
+ | `@umituz/web-hono` | `createApi`, `ApiConfig`, `healthRouter`, `ApiError`, `apiOnError`, `crudRoutes`, `listRoutes`, `CrudSpec`/`CrudTable`/`CreateSpec`/`ListSpec`/`CrudDb`, `getDb`, `uid`, `pickPatch`, `stampUpdate`, `trio`, `apiNotFound`, `spaFallback`, `ApiEnv` |
178
+ | `@umituz/web-hono/types` | `Row<T>`, `NewRow<T>`, `Serialized<T>`, `ClientRow<T>` — type-only |
179
+ | `@umituz/web-hono/validator` | `validateJson(schema, message?)` |
180
+ | `@umituz/web-hono/client` | `apiFetch<T>`, `apiWrite<T>` (void/204-tolerant) |
181
+ | `@umituz/web-hono/store` | `createStore`, `StoreConfig`, `REFETCH_ALL` (+ `read`/`view`/`http`/`subscribeAll`/`snapshot`/`immutable` on the store) |
182
+ | `@umituz/web-hono/store/react` | `makeStoreHooks(store)` → `useQuery`, `useDbValue`, `useCollection`, `useHydration`, `QueryResult` |
183
+ | `@umituz/web-hono/lifecycle` | `resetTables`, `snapshotToSeed`, `seedFromSnapshot`, `TableSpec`, `SeedSnapshot` |
184
+
185
+ ## Migration notes (per feature, all optional)
186
+
187
+ - **`createApi`**: delete the hand-mounted skeleton + health route; keep hand-mounting if your chain differs. Adopting the central `onError` intentionally turns some previously-500 paths into 409/400 — flag it in your app's changelog.
188
+ - **`create`/`remove` on `crudRoutes`**: plain-row POST/DELETE handlers in area routers delete (~15 lines each); the spec gains two optional keys. Existing GET/PATCH responses are byte-identical.
189
+ - **`trio()`**: replace inline time-trio columns with `...trio()` — pure refactor, no SQL change (drizzle-kit sees the same DDL).
190
+ - **Type bridge**: migrate interface-by-interface — `type Product = ClientRow<typeof products>`; verify with tsc per folder.
191
+ - **`immutable: true`**: one config key; React memo consumers start seeing fresh references. Code that relied on stale references should be deleted alongside adoption.
192
+ - **`useHydration`**: delete boot-gate providers; switch on `{ status, error, retry }`.
136
193
 
137
194
  ## What stays in the app
138
195
 
139
- - `api/schema.ts` — every table, the project's `TABLE_PREFIX`, fleet column standards (time trio, soft delete, jsonb nesting)
196
+ - `api/schema.ts` — every table, the project's `TABLE_PREFIX`, domain columns beyond the trio
140
197
  - The `Database` interface, `ENDPOINTS` map and empty state of `src/data/store.ts` — that shape IS the app
141
198
  - Domain routers with business rules (order transitions, reservation overlap guards, restock side effects)
142
199
  - Zod schemas and per-route error messages
143
200
  - Audit/notification/entitlement helpers (they insert into YOUR tables)
144
- - `api/routes/health.ts` — the `BUILD_MARKER` deploy canary is per-project
201
+ - Multi-tenant policy (which org the request belongs to — the package stays tenant-agnostic)
145
202
 
146
203
  ## Testing
147
204
 
@@ -149,7 +206,7 @@ await snapshotToSeed({ specs: TABLE_SPECS, url, outPath: new URL('./seed-data.js
149
206
  npm test
150
207
  ```
151
208
 
152
- 28 vitest cases cover the pure logic and DB-free short-circuit paths (pickPatch filters, uid shape, the 400/404 envelopes, validator contract, client error mapping, reset safety stop, and the store machine: hydration dedupe/retry, refresh selectivity, pub/sub semantics, apiWrite success/failure). Live-DB paths (list/PATCH success, snapshot/seed, hydration against the real API) are proven by the consuming app's E2E — the pilot is foodora.
209
+ 73 vitest cases cover the pure logic AND — since 1.3, via in-memory Postgres (PGlite) — the factory's real database behavior: list/soft-delete hiding, `?limit&offset&order`, POST create (uid prefix, defaults-under-body, zod 400s, unique→409), PATCH stamping, DELETE, and the 1.x additivity pins (no `create`/`remove` ⇒ POST/DELETE 404, params-less GET unchanged). Plus: pickPatch/stampUpdate filters, uid shape, the 400/404 envelopes, validator contract, client error mapping and void-endpoint tolerance, reset safety stop, createApi chain (health/middleware/onError/JSON-404-vs-SPA), and the store machine (hydration dedupe/retry, refresh selectivity, pub/sub, view memoization, immutable refs, hooks).
153
210
 
154
211
  ## License
155
212
 
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@umituz/web-hono",
3
- "version": "1.2.0",
4
- "description": "Hono backend contract for Cloudflare Workers + Neon Postgres: crudRoutes factory, pickPatch, validateJson, apiFetch/apiWrite client, reactive fetch-backed store (+React hooks), and db lifecycle scripts (reset / snapshot / seed)",
3
+ "version": "1.3.0",
4
+ "description": "API backend platform for Cloudflare Workers + Neon Postgres: createApi skeleton + error envelope layer, full-CRUD resource factory (opt-in create/remove, list params), schema→client type bridge (ClientRow), apiFetch/apiWrite client, reactive fetch-backed store (+React hooks), and db lifecycle scripts (reset / snapshot / seed)",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
7
7
  "types": "./src/index.ts",
8
8
  "sideEffects": false,
9
9
  "exports": {
10
10
  ".": "./src/index.ts",
11
+ "./types": "./src/types.ts",
11
12
  "./validator": "./src/validator.ts",
12
13
  "./client": "./src/client.ts",
13
14
  "./store": "./src/store.ts",
@@ -70,13 +71,16 @@
70
71
  }
71
72
  },
72
73
  "devDependencies": {
74
+ "@electric-sql/pglite": "^0.5.9",
73
75
  "@eslint/js": "^9.32.0",
74
76
  "@neondatabase/serverless": "^1.2.0",
77
+ "@testing-library/react": "^16.3.3",
75
78
  "@types/node": "~22.13.10",
76
79
  "@types/react": "^19.1.0",
77
80
  "drizzle-orm": "^0.45.4",
78
81
  "eslint": "^9.32.0",
79
82
  "hono": "^4.13.13",
83
+ "jsdom": "^29.1.1",
80
84
  "react": "^19.1.0",
81
85
  "typescript": "~5.9.2",
82
86
  "typescript-eslint": "^8.58.0",
package/src/api.ts ADDED
@@ -0,0 +1,52 @@
1
+ import { Hono } from 'hono';
2
+ import type { MiddlewareHandler } from 'hono';
3
+ import type { ErrorHandler } from 'hono';
4
+ import { apiNotFound, spaFallback } from './handlers';
5
+ import { apiOnError } from './errors';
6
+ import { healthRouter } from './health';
7
+ import type { ApiEnv } from './env';
8
+
9
+ /**
10
+ * The one-call API skeleton — everything the 1.x apps hand-copied into
11
+ * api/index.ts, routes/health.ts and env wiring, composed once:
12
+ *
13
+ * export default createApi({
14
+ * service: 'storyora',
15
+ * build: BUILD_MARKER,
16
+ * routers: [['/projects', projectsRouter], ['/', orgRouter]],
17
+ * });
18
+ *
19
+ * The chain, in order: /api/health (canary — deliberately BEFORE middleware
20
+ * so uptime probes stay unauthenticated) → your middleware (auth, logging —
21
+ * /api only) → your routers → onError (the `{ error }` envelope) →
22
+ * unmatched /api/* stays JSON 404 → everything else resolves via the ASSETS
23
+ * binding (SPA). Apps needing a different chain keep hand-mounting the
24
+ * same pieces — this factory is the fleet default, not a cage.
25
+ */
26
+ export interface ApiConfig<E extends ApiEnv = ApiEnv> {
27
+ /** Service name surfaced by /api/health. */
28
+ service: string;
29
+ /** CI-injected build marker for the deploy canary; omitted → null. */
30
+ build?: string;
31
+ /** Routers mounted under /api: ['/stories', storiesRouter]. */
32
+ routers?: ReadonlyArray<readonly [string, Hono<{ Bindings: E }>]>;
33
+ /** Middleware applied to the /api sub-app in order (auth, logging…). */
34
+ middleware?: ReadonlyArray<MiddlewareHandler<{ Bindings: E }>>;
35
+ }
36
+
37
+ export function createApi<E extends ApiEnv = ApiEnv>(config: ApiConfig<E>): Hono<{ Bindings: E }> {
38
+ const api = new Hono<{ Bindings: E }>();
39
+
40
+ api.route('/health', healthRouter<E>({ service: config.service, build: config.build }));
41
+ for (const mw of config.middleware ?? []) api.use(mw);
42
+ for (const [path, router] of config.routers ?? []) api.route(path, router);
43
+
44
+ const app = new Hono<{ Bindings: E }>();
45
+ app.route('/api', api);
46
+ // Widening ApiEnv→E is safe at runtime (c.env: E ⊇ ApiEnv); hono's Context
47
+ // invariance just refuses the direct cast.
48
+ app.onError(apiOnError as unknown as ErrorHandler<{ Bindings: E }>);
49
+ app.all('/api/*', apiNotFound);
50
+ app.get('*', spaFallback);
51
+ return app;
52
+ }
package/src/client.ts CHANGED
@@ -12,7 +12,10 @@ export async function apiFetch<T>(path: string, init: { method?: 'POST' | 'PATCH
12
12
  const body = (await res.json().catch(() => null)) as { error?: string } | null;
13
13
  throw new Error(body?.error ?? `API ${path} responded ${res.status}`);
14
14
  }
15
- return (await res.json()) as T;
15
+ // Void endpoints (204 / empty body) resolve to undefined — res.json()
16
+ // would throw a SyntaxError on the empty stream.
17
+ const text = await res.text();
18
+ return (text.length > 0 ? JSON.parse(text) : undefined) as T;
16
19
  }
17
20
 
18
21
  /**
package/src/crud.ts CHANGED
@@ -1,17 +1,25 @@
1
1
  import { Hono } from 'hono';
2
- import { and, asc, desc, eq, isNull } from 'drizzle-orm';
2
+ import { and, asc, desc, eq, getTableColumns, isNull } from 'drizzle-orm';
3
3
  import { drizzle } from 'drizzle-orm/neon-http';
4
4
  import { neon } from '@neondatabase/serverless';
5
+ import type { Context } from 'hono';
5
6
  import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
6
- import { pickPatch, stampUpdate } from './lib';
7
+ import { z } from 'zod';
8
+ import { pickPatch, stampUpdate, uid } from './lib';
7
9
  import type { ApiEnv } from './env';
8
10
 
9
11
  /**
10
- * The standard entity resource: GET list (soft-deleted hidden, ordered) +
11
- * PATCH /:id (pickPatch-filtered body, updatedAt stamp, 404 on miss).
12
- * Mount it onto an area router with `.route('/', crudRoutes({ ... }))`.
12
+ * The standard entity resource factory: GET list (soft-deleted hidden,
13
+ * ordered, optional ?limit/&offset/&order) + PATCH /:id (pickPatch-filtered
14
+ * body, updatedAt stamp, 404 on miss) — plus OPT-IN POST create (zod schema,
15
+ * uid prefix, server-side defaults) and DELETE /:id (soft delete). Mount it
16
+ * onto an area router with `.route('/', crudRoutes({ ... }))`.
13
17
  *
14
- * listRoutes is its GET-only sibling for append-only collections (event
18
+ * Omitting `create`/`remove` registers exactly GET + PATCH — the 1.x
19
+ * surface, byte-identical. `db` is injectable (tests, Hyperdrive variants);
20
+ * the default builds a per-request neon-http instance as before.
21
+ *
22
+ * listRoutes is the GET-only sibling for append-only collections (event
15
23
  * logs, activities, users) whose rows are written server-side only.
16
24
  *
17
25
  * Entities with business rules (role immutability guards, goods-receipt
@@ -19,31 +27,66 @@ import type { ApiEnv } from './env';
19
27
  * the factory is for plain settings/catalog rows only.
20
28
  */
21
29
 
30
+ /** Anything the factory can select/insert/update against — the return type
31
+ * of the default neon-http construction. Injected instances from other
32
+ * drivers (pglite, node-postgres) differ only at the type level; injection
33
+ * sites bypass with `as unknown as CrudDb`. */
34
+ type RequestContext = Context<{ Bindings: ApiEnv }>;
35
+ function defaultDb(c: RequestContext) {
36
+ // Schema-less drizzle: the factory only runs select/insert/update, which
37
+ // never touch the schema registry (only `db.query.*` does) — so it builds
38
+ // its own instance from the request's binding instead of requiring one.
39
+ return drizzle(neon(c.env.DATABASE_URL));
40
+ }
41
+ export type CrudDb = ReturnType<typeof defaultDb>;
42
+ export type CrudDbFactory = (c: RequestContext) => CrudDb;
43
+
22
44
  export type CrudTable = PgTable & { id: PgColumn; deletedAt: PgColumn };
23
45
 
46
+ /** Opt-in POST create: zod-validated body, server-generated uid, optional
47
+ * request-scoped stamps (organizationId, createdBy…). */
48
+ export interface CreateSpec {
49
+ /** zod schema for the request body (`.strict()` per fleet convention). */
50
+ schema: z.ZodType;
51
+ /** uid prefix: 'prd' → prd_<base36 ts><counter>. */
52
+ prefix: string;
53
+ /** Server-side stamps merged UNDER the parsed body — body values win. */
54
+ defaults?: (c: RequestContext) => Record<string, unknown>;
55
+ }
56
+
24
57
  export interface ListSpec {
25
58
  /** Path under /api, e.g. '/activities'. */
26
59
  path: string;
27
60
  table: PgTable & { deletedAt: PgColumn };
28
61
  /** List order; defaults to insertion order. */
29
62
  orderBy?: { col: PgColumn; dir?: 'asc' | 'desc' };
63
+ /** Injectable db factory (tests, Hyperdrive). Default: per-request
64
+ * drizzle(neon(c.env.DATABASE_URL)) — the 1.x behavior. */
65
+ db?: CrudDbFactory;
30
66
  }
31
67
 
32
68
  export interface CrudSpec extends ListSpec {
33
69
  table: CrudTable;
34
70
  /** Human label for 404s — 'Product' → 'Product not found'. */
35
71
  label: string;
72
+ /** Opt-in POST create. Absent ⇒ no POST route (404), as in 1.x. */
73
+ create?: CreateSpec;
74
+ /** Opt-in soft-delete DELETE. Absent ⇒ no DELETE route (404), as in 1.x. */
75
+ remove?: boolean;
36
76
  }
37
77
 
78
+ /** ?limit cap — protects the hydrate-everything thin-read doctrine. */
79
+ const MAX_LIST_LIMIT = 500;
80
+
38
81
  /** GET-only list (soft-deleted hidden) for append-only collections — event
39
82
  * logs, activities, users. No PATCH: these rows are written server-side. */
40
83
  export function listRoutes(spec: ListSpec): Hono<{ Bindings: ApiEnv }> {
41
84
  const { path, table, orderBy } = spec;
85
+ const getDb = spec.db ?? defaultDb;
42
86
  const router = new Hono<{ Bindings: ApiEnv }>();
43
87
 
44
88
  router.get(path, async (c) => {
45
- // Schema-less drizzle: see the note in crudRoutes.
46
- const db = drizzle(neon(c.env.DATABASE_URL));
89
+ const db = getDb(c);
47
90
  const q = db.select().from(table).where(isNull(table.deletedAt)).$dynamic();
48
91
  if (orderBy) q.orderBy(orderBy.dir === 'desc' ? desc(orderBy.col) : asc(orderBy.col));
49
92
  return c.json(await q);
@@ -54,22 +97,54 @@ export function listRoutes(spec: ListSpec): Hono<{ Bindings: ApiEnv }> {
54
97
 
55
98
  export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
56
99
  const { path, table, label, orderBy } = spec;
100
+ const getDb = spec.db ?? defaultDb;
57
101
  const router = new Hono<{ Bindings: ApiEnv }>();
58
102
 
59
103
  router.get(path, async (c) => {
60
- // Schema-less drizzle: the factory only runs select/update, which never
61
- // touch the schema registry (only `db.query.*` does) — so it builds its
62
- // own instance from the request's binding instead of requiring one.
63
- const db = drizzle(neon(c.env.DATABASE_URL));
104
+ const db = getDb(c);
64
105
  const q = db.select().from(table).where(isNull(table.deletedAt)).$dynamic();
65
- if (orderBy) q.orderBy(orderBy.dir === 'desc' ? desc(orderBy.col) : asc(orderBy.col));
106
+
107
+ // ?order=col | -col (leading '-' = desc) — whitelisted against the
108
+ // table's own property columns; an explicit order overrides spec.orderBy.
109
+ const orderParam = c.req.query('order');
110
+ let orderCol: PgColumn | undefined;
111
+ let dir: 'asc' | 'desc' = 'asc';
112
+ if (orderParam !== undefined) {
113
+ const wantDesc = orderParam.startsWith('-');
114
+ const name = orderParam.slice(wantDesc ? 1 : 0);
115
+ const found = (getTableColumns(table) as unknown as Record<string, PgColumn>)[name];
116
+ if (!found) return c.json({ error: 'Invalid order column' }, 400);
117
+ orderCol = found;
118
+ dir = wantDesc ? 'desc' : 'asc';
119
+ } else if (orderBy) {
120
+ orderCol = orderBy.col;
121
+ dir = orderBy.dir ?? 'asc';
122
+ }
123
+ if (orderCol) q.orderBy(dir === 'desc' ? desc(orderCol) : asc(orderCol));
124
+
125
+ // ?limit/&offset= — absent params add no clauses: the 1.x query exactly.
126
+ // offset without order follows the spec/default insertion order (the
127
+ // same caveat 1.x lists always had).
128
+ const limitParam = c.req.query('limit');
129
+ if (limitParam !== undefined) {
130
+ const n = Number(limitParam);
131
+ if (!Number.isInteger(n) || n < 1 || n > MAX_LIST_LIMIT) return c.json({ error: 'Invalid limit' }, 400);
132
+ q.limit(n);
133
+ }
134
+ const offsetParam = c.req.query('offset');
135
+ if (offsetParam !== undefined) {
136
+ const n = Number(offsetParam);
137
+ if (!Number.isInteger(n) || n < 0) return c.json({ error: 'Invalid offset' }, 400);
138
+ q.offset(n);
139
+ }
140
+
66
141
  return c.json(await q);
67
142
  });
68
143
 
69
144
  router.patch(`${path}/:id`, async (c) => {
70
145
  const patch = pickPatch(table, await c.req.json().catch(() => null));
71
146
  if (!patch) return c.json({ error: 'No updatable fields' }, 400);
72
- const db = drizzle(neon(c.env.DATABASE_URL));
147
+ const db = getDb(c);
73
148
  const [row] = await db
74
149
  .update(table)
75
150
  // Generic tables can't carry per-table set types — values are already
@@ -81,5 +156,38 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
81
156
  return row ? c.json(row) : c.json({ error: `${label} not found` }, 404);
82
157
  });
83
158
 
159
+ if (spec.create) {
160
+ const { schema, prefix, defaults } = spec.create;
161
+ router.post(path, async (c) => {
162
+ const parsed = schema.safeParse(await c.req.json().catch(() => null));
163
+ if (!parsed.success) {
164
+ return c.json({ error: 'Invalid request body', details: parsed.error.flatten().fieldErrors }, 400);
165
+ }
166
+ const body = parsed.data as Record<string, unknown>;
167
+ const db = getDb(c);
168
+ const [row] = await db
169
+ .insert(table)
170
+ // id LAST: server-generated, never client-supplied. createdAt/
171
+ // updatedAt come from the DB column defaults (fleet convention).
172
+ .values({ ...defaults?.(c), ...body, id: uid(prefix) } as never)
173
+ .returning();
174
+ return c.json(row, 201);
175
+ });
176
+ }
177
+
178
+ if (spec.remove) {
179
+ router.delete(`${path}/:id`, async (c) => {
180
+ const db = getDb(c);
181
+ const [row] = await db
182
+ .update(table)
183
+ // Soft delete: every read filters isNull(deletedAt), so the row
184
+ // vanishes from lists without losing history.
185
+ .set({ deletedAt: new Date(), ...stampUpdate(table) } as never)
186
+ .where(and(eq(table.id, c.req.param('id')), isNull(table.deletedAt)))
187
+ .returning({ id: table.id });
188
+ return row ? c.json({ ok: true }) : c.json({ error: `${label} not found` }, 404);
189
+ });
190
+ }
191
+
84
192
  return router;
85
193
  }
package/src/errors.ts ADDED
@@ -0,0 +1,70 @@
1
+ import type { ErrorHandler } from 'hono';
2
+ import type { ContentfulStatusCode } from 'hono/utils/http-status';
3
+ import { ZodError } from 'zod';
4
+ import type { ApiEnv } from './env';
5
+
6
+ /**
7
+ * The error layer of the `{ error, details? }` envelope. Routes throw
8
+ * `ApiError` (or let drizzle/postgres errors bubble) and `apiOnError` —
9
+ * installed by `createApi`, or by hand via `app.onError(apiOnError)` —
10
+ * maps everything to the envelope. Unexpected errors never leak internals:
11
+ * they answer a generic 500 and log server-side.
12
+ */
13
+
14
+ /** A deliberate 4xx: the route's own words, the envelope's shape. */
15
+ export class ApiError extends Error {
16
+ constructor(
17
+ /** Literal status this error answers with (404, 400, 409…). */
18
+ public readonly status: ContentfulStatusCode,
19
+ message: string,
20
+ /** Optional details (zod fieldErrors, ids, …). */
21
+ public readonly details?: unknown,
22
+ ) {
23
+ super(message);
24
+ this.name = 'ApiError';
25
+ }
26
+
27
+ /** `404 { error: '${label} not found' }` — the fleet's miss shape. */
28
+ static notFound(label: string): ApiError {
29
+ return new ApiError(404, `${label} not found`);
30
+ }
31
+
32
+ static badRequest(message: string, details?: unknown): ApiError {
33
+ return new ApiError(400, message, details);
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Postgres unique_violation — the code sits on the error itself (pglite,
39
+ * node-postgres) or nested in a driver cause-chain (neon-http). Depth-capped
40
+ * walk so malformed causes can't loop.
41
+ */
42
+ function isUniqueViolation(err: unknown): boolean {
43
+ let e: unknown = err;
44
+ for (let depth = 0; e !== null && typeof e === 'object' && depth < 3; depth += 1) {
45
+ if ((e as { code?: unknown }).code === '23505') return true;
46
+ e = (e as { cause?: unknown }).cause;
47
+ }
48
+ return false;
49
+ }
50
+
51
+ /** The standard onError: every failure speaks the envelope. */
52
+ export const apiOnError: ErrorHandler<{ Bindings: ApiEnv }> = (err, c) => {
53
+ if (err instanceof ApiError) {
54
+ return c.json(
55
+ err.details !== undefined ? { error: err.message, details: err.details } : { error: err.message },
56
+ err.status,
57
+ );
58
+ }
59
+ if (err instanceof ZodError) {
60
+ // Safety net: validateJson normally answers inline, but a hand-rolled
61
+ // safeParse that throws lands here with the same contract.
62
+ return c.json({ error: 'Invalid request body', details: err.flatten().fieldErrors }, 400);
63
+ }
64
+ if (isUniqueViolation(err)) {
65
+ return c.json({ error: 'Already exists' }, 409);
66
+ }
67
+ // Unexpected: log server-side, answer generic — never leak internals.
68
+ console.error(`[api] ${c.req.method} ${c.req.path}:`, err);
69
+ return c.json({ error: 'Internal server error' }, 500);
70
+ };
package/src/health.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { Hono } from 'hono';
2
+ import type { ApiEnv } from './env';
3
+
4
+ /**
5
+ * The deploy canary: `GET /api/health` → `{ ok, service, build, time }`.
6
+ * `build` is the CI-injected marker (missing → null) — bump it so the E2E
7
+ * canary can prove the new Worker is the one answering. Replaces the
8
+ * per-app routes/health.ts that 1.x apps copied around verbatim.
9
+ */
10
+ export function healthRouter<E extends ApiEnv = ApiEnv>(opts: { service: string; build?: string }): Hono<{ Bindings: E }> {
11
+ const router = new Hono<{ Bindings: E }>();
12
+ router.get('/', (c) =>
13
+ c.json({ ok: true, service: opts.service, build: opts.build ?? null, time: new Date().toISOString() }),
14
+ );
15
+ return router;
16
+ }
package/src/index.ts CHANGED
@@ -1,22 +1,29 @@
1
1
  /**
2
- * @umituz/web-hono — the Hono backend contract for single-Worker apps on
3
- * Cloudflare (SPA assets + `/api/*` Hono) with Neon Postgres via drizzle:
4
- * the crudRoutes factory, pickPatch/uid helpers, getDb, the JSON-404 and
5
- * SPA-fallback handlers, and the ApiEnv binding types.
2
+ * @umituz/web-hono — the API backend platform for single-Worker apps on
3
+ * Cloudflare (SPA assets + `/api/*` Hono) with Neon Postgres via drizzle.
6
4
  *
7
5
  * Apps keep their schema (with TABLE_PREFIX), domain routers, zod schemas,
8
- * and business rules — this package owns the cross-cutting API skeleton
9
- * only.
6
+ * and business rules — this package owns the cross-cutting skeleton:
7
+ * the createApi app factory, the error envelope layer, the full-CRUD
8
+ * resource factory, getDb, the uid/pickPatch/stampUpdate/trio helpers,
9
+ * the JSON-404 and SPA-fallback handlers, and the ApiEnv binding types.
10
10
  *
11
11
  * Entry points:
12
12
  * `.` server core (this file)
13
+ * `/types` Row/NewRow/Serialized/ClientRow — the schema→client type bridge
13
14
  * `/validator` validateJson — the zod `{ error, details }` body contract
14
15
  * `/client` apiFetch / apiWrite — the same-origin API client
16
+ * `/store` createStore — the fetch-backed reactive store
17
+ * `/store/react` makeStoreHooks — useQuery/useDbValue/useCollection/useHydration
15
18
  * `/lifecycle` reset / snapshot / seed — the shared-Neon db lifecycle
16
19
  */
20
+ export { createApi } from './api';
21
+ export type { ApiConfig } from './api';
22
+ export { healthRouter } from './health';
23
+ export { ApiError, apiOnError } from './errors';
17
24
  export { crudRoutes, listRoutes } from './crud';
18
- export type { CrudSpec, CrudTable, ListSpec } from './crud';
25
+ export type { CrudSpec, CrudTable, CrudDb, CrudDbFactory, CreateSpec, ListSpec } from './crud';
19
26
  export { getDb } from './db';
20
- export { uid, pickPatch, stampUpdate } from './lib';
27
+ export { uid, pickPatch, stampUpdate, trio } from './lib';
21
28
  export { apiNotFound, spaFallback } from './handlers';
22
29
  export type { ApiEnv } from './env';
package/src/lib.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { getTableColumns } from 'drizzle-orm';
2
+ import { timestamp } from 'drizzle-orm/pg-core';
2
3
  import type { PgTable } from 'drizzle-orm/pg-core';
3
4
 
4
5
  /** Server-side id generation: `${prefix}_${base36 timestamp}${base36 counter}`. */
@@ -8,6 +9,20 @@ export function uid(prefix: string): string {
8
9
  return `${prefix}_${Date.now().toString(36)}${idCounter.toString(36)}`;
9
10
  }
10
11
 
12
+ /**
13
+ * Fleet time-trio columns for timestamptz tables — spread into a pgTable
14
+ * definition: `{ id: text('id').primaryKey(), name: text('name'), ...trio() }`.
15
+ * One encoding of the fleet standard instead of the three (inline columns,
16
+ * factory functions, spread objects) the 1.x apps each hand-rolled.
17
+ */
18
+ export function trio() {
19
+ return {
20
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
21
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
22
+ deletedAt: timestamp('deleted_at', { withTimezone: true }),
23
+ };
24
+ }
25
+
11
26
  /** Fields no client may ever patch. */
12
27
  const PROTECTED_KEYS = new Set(['id', 'createdAt', 'updatedAt', 'deletedAt']);
13
28
 
@@ -28,9 +43,11 @@ function localDateStamp(): string {
28
43
  */
29
44
  export function stampUpdate(table: PgTable): Record<string, unknown> {
30
45
  const columns = getTableColumns(table) as unknown as Record<string, { columnType: string }>;
31
- return columns.updatedAt?.columnType.includes('Timestamp')
32
- ? { updatedAt: new Date() }
33
- : { updatedAt: localDateStamp() };
46
+ const updatedAt = columns.updatedAt;
47
+ // No updatedAt column → stamp nothing; stamping a nonexistent column would
48
+ // fail the drizzle update at runtime.
49
+ if (!updatedAt) return {};
50
+ return updatedAt.columnType.includes('Timestamp') ? { updatedAt: new Date() } : { updatedAt: localDateStamp() };
34
51
  }
35
52
 
36
53
  /**
@@ -71,5 +71,41 @@ export function makeStoreHooks<Database extends object>(store: Store<Database>)
71
71
  return valueRef.current;
72
72
  }
73
73
 
74
- return { useQuery, useDbValue };
74
+ /** Typed synchronous collection read that re-renders on that collection's
75
+ * channel: `const items = useCollection('items');` — Database['items']. */
76
+ function useCollection<K extends keyof Database & string>(key: K): Database[K] {
77
+ const [, force] = useState(0);
78
+ useEffect(() => store.subscribe([key], () => force((v) => v + 1)), [key]);
79
+ return store.getDb()[key];
80
+ }
81
+
82
+ /** The app boot gate: loading while the first hydration runs, error +
83
+ * retry on failure. Replaces the per-app boot-gate providers 1.x apps
84
+ * hand-rolled around ensureHydrated. */
85
+ function useHydration(): { status: 'loading' | 'ready' | 'error'; error?: string; retry: () => void } {
86
+ const [state, setState] = useState<{ status: 'loading' | 'ready' | 'error'; error?: string }>({ status: 'loading' });
87
+ const [attempt, setAttempt] = useState(0);
88
+
89
+ useEffect(() => {
90
+ let alive = true;
91
+ setState({ status: 'loading' });
92
+ store.ensureHydrated().then(
93
+ () => {
94
+ if (alive) setState({ status: 'ready' });
95
+ },
96
+ (err) => {
97
+ // ensureHydrated already reset itself — the next call (retry) refetches.
98
+ if (alive) setState({ status: 'error', error: err instanceof Error ? err.message : 'Hydration failed' });
99
+ },
100
+ );
101
+ return () => {
102
+ alive = false;
103
+ };
104
+ }, [attempt]);
105
+
106
+ const retry = useCallback(() => setAttempt((a) => a + 1), []);
107
+ return { status: state.status, error: state.error, retry };
108
+ }
109
+
110
+ return { useQuery, useDbValue, useCollection, useHydration };
75
111
  }
package/src/store.ts CHANGED
Binary file
package/src/types.ts ADDED
@@ -0,0 +1,31 @@
1
+ import type { InferInsertModel, InferSelectModel } from 'drizzle-orm';
2
+ import type { PgTable } from 'drizzle-orm/pg-core';
3
+
4
+ /**
5
+ * The server↔client type bridge. The drizzle schema is the single source of
6
+ * truth: the server row, the wire shape, and the store cache all DERIVE from
7
+ * it — no hand-mirrored interface files that silently drift (the 1.x fleet
8
+ * maintained those by convention only).
9
+ *
10
+ * // app schema: export const products = pgTable(...)
11
+ * type Product = ClientRow<typeof products>; // what src/data/store.ts caches
12
+ * type NewProduct = NewRow<typeof products>; // what a POST body becomes
13
+ *
14
+ * This entry is type-only — client code importing it pulls no server runtime.
15
+ */
16
+
17
+ /** The server-side row straight from the drizzle schema (Date objects for
18
+ * timestamptz columns — what drizzle returns, what handlers pass to c.json). */
19
+ export type Row<T extends PgTable> = InferSelectModel<T>;
20
+
21
+ /** The insert shape (POST bodies after zod) — defaults/optional per schema. */
22
+ export type NewRow<T extends PgTable> = InferInsertModel<T>;
23
+
24
+ /** What JSON.stringify delivers over the wire: Date → ISO string, everything
25
+ * else (jsonb, enums, date mode:'string' columns — already strings) as-is. */
26
+ export type Serialized<T> = {
27
+ [K in keyof T]: T[K] extends Date ? string : T[K] extends Date | null ? string | null : T[K];
28
+ };
29
+
30
+ /** The client-cached row type: what apiFetch/store hold after c.json(). */
31
+ export type ClientRow<T extends PgTable> = Serialized<Row<T>>;