@umituz/web-hono 1.0.0 → 1.1.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,6 +1,6 @@
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, and the shared-Neon database lifecycle scripts.
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.
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
 
@@ -8,7 +8,7 @@ The package is **source-distributed** (published as raw TypeScript in `src/`). W
8
8
 
9
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
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.** `apiFetch`/`apiWrite` never import your store; hosts pass their own typed `refresh` (usually via a 3-line wrapper that binds their collection keys).
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.
12
12
  - **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
13
 
14
14
  ## Installation
@@ -26,6 +26,8 @@ Peer dependencies (install alongside): `hono ^4`, `drizzle-orm ^0.45`, `@neondat
26
26
  | `@umituz/web-hono` | `crudRoutes`, `CrudSpec`/`CrudTable`, `getDb`, `uid`, `pickPatch`, `apiNotFound`, `spaFallback`, `ApiEnv` | `api/index.ts`, area routers, `api/db.ts` |
27
27
  | `@umituz/web-hono/validator` | `validateJson(schema, message?)` | every hand-written POST/PATCH route |
28
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) |
29
31
  | `@umituz/web-hono/lifecycle` | `resetTables`, `snapshotToSeed`, `seedFromSnapshot`, `TableSpec`, `SeedSnapshot` | `scripts/reset.ts` / `snapshot.ts` / `seed.ts` wrappers |
30
32
 
31
33
  ## Quick start
@@ -84,17 +86,39 @@ import * as schema from './schema';
84
86
  export const getDbBound = (env: { DATABASE_URL: string }) => getDb(env, schema);
85
87
  ```
86
88
 
87
- **5. Frontend client** (`src/data/http.ts`):
89
+ **5. Frontend data layer** — the app owns its shape, the package owns the machine:
88
90
 
89
91
  ```ts
90
- import { apiFetch, apiWrite as write } from '@umituz/web-hono/client';
91
- import { refresh, type CollectionKey } from './store';
92
+ // src/data/store.ts — this file IS the app's data layer now
93
+ import { createStore } from '@umituz/web-hono/store';
92
94
 
93
- export { apiFetch };
94
- export const apiWrite = <T = void>(path: string, init: Parameters<typeof write>[1], keys: CollectionKey[] = []) =>
95
- write<T>(path, init, keys, (k) => refresh(k));
95
+ export interface Database { orders: Order[]; loyalty: LoyaltyProgram; /* … */ }
96
+ export type CollectionKey = keyof Database;
97
+
98
+ const ENDPOINTS: Record<CollectionKey, string> = { orders: '/api/orders', loyalty: '/api/loyalty', /* … */ };
99
+ const emptyDatabase = (): Database => ({ orders: [], loyalty: EMPTY_LOYALTY });
100
+
101
+ export const store = createStore<Database>({ endpoints: ENDPOINTS, empty: emptyDatabase });
102
+ export const { ensureHydrated, refresh, getDb, subscribe, apiWrite } = store;
103
+ ```
104
+
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';
96
109
  ```
97
110
 
111
+ ```ts
112
+ // src/core/useQuery.ts — hooks bound to the store (react: optional peer)
113
+ import { makeStoreHooks } from '@umituz/web-hono/store/react';
114
+ import { store } from '@/data/store';
115
+
116
+ export const { useQuery, useDbValue } = makeStoreHooks(store);
117
+ export type { QueryResult } from '@umituz/web-hono/store/react';
118
+ ```
119
+
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.
121
+
98
122
  **6. Lifecycle scripts** (`scripts/`) — keep only your `TABLE_SPECS` registry and thin wrappers:
99
123
 
100
124
  ```ts
@@ -113,6 +137,7 @@ await snapshotToSeed({ specs: TABLE_SPECS, url, outPath: new URL('./seed-data.js
113
137
  ## What stays in the app
114
138
 
115
139
  - `api/schema.ts` — every table, the project's `TABLE_PREFIX`, fleet column standards (time trio, soft delete, jsonb nesting)
140
+ - The `Database` interface, `ENDPOINTS` map and empty state of `src/data/store.ts` — that shape IS the app
116
141
  - Domain routers with business rules (order transitions, reservation overlap guards, restock side effects)
117
142
  - Zod schemas and per-route error messages
118
143
  - Audit/notification/entitlement helpers (they insert into YOUR tables)
@@ -124,7 +149,7 @@ await snapshotToSeed({ specs: TABLE_SPECS, url, outPath: new URL('./seed-data.js
124
149
  npm test
125
150
  ```
126
151
 
127
- 21 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). Live-DB paths (list/PATCH success, snapshot/seed) are proven by the consuming app's E2E — the pilot is foodora.
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.
128
153
 
129
154
  ## License
130
155
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@umituz/web-hono",
3
- "version": "1.0.0",
4
- "description": "Hono backend contract for Cloudflare Workers + Neon Postgres: crudRoutes factory, pickPatch, validateJson, apiFetch/apiWrite client, and db lifecycle scripts (reset / snapshot / seed)",
3
+ "version": "1.1.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)",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
7
7
  "types": "./src/index.ts",
@@ -10,6 +10,8 @@
10
10
  ".": "./src/index.ts",
11
11
  "./validator": "./src/validator.ts",
12
12
  "./client": "./src/client.ts",
13
+ "./store": "./src/store.ts",
14
+ "./store/react": "./src/store-react.ts",
13
15
  "./lifecycle": "./src/lifecycle.ts",
14
16
  "./package.json": "./package.json"
15
17
  },
@@ -39,6 +41,9 @@
39
41
  "zod",
40
42
  "validation",
41
43
  "api-client",
44
+ "store",
45
+ "reactive-store",
46
+ "cache",
42
47
  "seed",
43
48
  "snapshot",
44
49
  "database-lifecycle",
@@ -50,21 +55,29 @@
50
55
  "license": "MIT",
51
56
  "repository": {
52
57
  "type": "git",
53
- "url": "https://github.com/umituz/web-hono"
58
+ "url": "git+https://github.com/umituz/web-hono.git"
54
59
  },
55
60
  "peerDependencies": {
56
61
  "@neondatabase/serverless": "^1.0.0",
57
62
  "drizzle-orm": "^0.45.4",
58
63
  "hono": "^4.0.0",
64
+ "react": "^18.0.0 || ^19.0.0",
59
65
  "zod": "^4.0.0"
60
66
  },
67
+ "peerDependenciesMeta": {
68
+ "react": {
69
+ "optional": true
70
+ }
71
+ },
61
72
  "devDependencies": {
62
73
  "@eslint/js": "^9.32.0",
63
74
  "@neondatabase/serverless": "^1.2.0",
64
75
  "@types/node": "~22.13.10",
76
+ "@types/react": "^19.1.0",
65
77
  "drizzle-orm": "^0.45.4",
66
78
  "eslint": "^9.32.0",
67
79
  "hono": "^4.13.13",
80
+ "react": "^19.1.0",
68
81
  "typescript": "~5.9.2",
69
82
  "typescript-eslint": "^8.58.0",
70
83
  "vitest": "3.2.4",
@@ -0,0 +1,75 @@
1
+ /* React bindings for a createStore instance. The store is framework-free;
2
+ apps that don't use React never import this entry. Binding pattern:
3
+
4
+ const store = createStore(config);
5
+ export const { useQuery, useDbValue } = makeStoreHooks(store); */
6
+
7
+ import { useCallback, useEffect, useRef, useState } from 'react';
8
+ import { REFETCH_ALL, type createStore } from './store';
9
+
10
+ export interface QueryResult<T> {
11
+ data: T | undefined;
12
+ status: 'loading' | 'success' | 'error';
13
+ error?: string;
14
+ refetch: () => void;
15
+ }
16
+
17
+ export type Store<Database extends object> = ReturnType<typeof createStore<Database>>;
18
+
19
+ export function makeStoreHooks<Database extends object>(store: Store<Database>) {
20
+ /** Async queries with loading/error states; re-runs when the underlying
21
+ * collections change (via the store's pub/sub) or when the key changes. */
22
+ function useQuery<T>(key: unknown[], fetcher: () => Promise<T>, enabled = true): QueryResult<T> {
23
+ const keyStr = JSON.stringify(key);
24
+ const fetcherRef = useRef(fetcher);
25
+ fetcherRef.current = fetcher;
26
+
27
+ const [tick, setTick] = useState(0);
28
+ const [state, setState] = useState<{ data?: T; status: 'loading' | 'success' | 'error'; error?: string }>({
29
+ status: 'loading',
30
+ });
31
+ const requestId = useRef(0);
32
+
33
+ useEffect(() => {
34
+ if (!enabled) return;
35
+ const id = ++requestId.current;
36
+ let alive = true;
37
+ setState((s) => ({ ...s, status: 'loading' }));
38
+ fetcherRef.current().then(
39
+ (data) => {
40
+ if (alive && id === requestId.current) setState({ data, status: 'success' });
41
+ },
42
+ (err) => {
43
+ if (alive && id === requestId.current)
44
+ setState({ data: undefined, status: 'error', error: err instanceof Error ? err.message : 'Request failed' });
45
+ },
46
+ );
47
+ return () => {
48
+ alive = false;
49
+ };
50
+ }, [keyStr, tick, enabled]);
51
+
52
+ useEffect(() => {
53
+ const keys: string[] = JSON.parse(keyStr);
54
+ return store.subscribe([...keys, REFETCH_ALL], () => setTick((t) => t + 1));
55
+ }, [keyStr]);
56
+
57
+ const refetch = useCallback(() => setTick((t) => t + 1), []);
58
+ return { data: state.data, status: state.status, error: state.error, refetch };
59
+ }
60
+
61
+ /** Non-promise variant for synchronous derived reads that should still
62
+ * refresh when collections change. */
63
+ function useDbValue<T>(compute: () => T, keys: string[]): T {
64
+ const [, force] = useState(0);
65
+ const computeRef = useRef(compute);
66
+ computeRef.current = compute;
67
+ const valueRef = useRef<T>(compute());
68
+ valueRef.current = computeRef.current();
69
+ // deps: the joined key string — the subscription only changes when it does
70
+ useEffect(() => store.subscribe(keys, () => force((v) => v + 1)), [keys.join(',')]);
71
+ return valueRef.current;
72
+ }
73
+
74
+ return { useQuery, useDbValue };
75
+ }
package/src/store.ts ADDED
@@ -0,0 +1,88 @@
1
+ /* Fetch-backed reactive cache — the client twin of the thin-read/fat-write
2
+ doctrine. The app owns its Database shape, endpoint map and empty-state
3
+ factory (that IS the app); this module owns the machine: hydrate-every-
4
+ collection-once, targeted refresh after writes, synchronous reads and
5
+ per-collection pub/sub. `apiWrite` comes back bound to the store, so the
6
+ whole client glue per app is one `createStore` call. */
7
+
8
+ import { apiFetch, apiWrite as clientApiWrite } from './client';
9
+
10
+ export interface StoreConfig<Database extends object> {
11
+ /** API endpoint per collection key (e.g. orders → '/api/orders'). */
12
+ endpoints: Record<keyof Database & string, string>;
13
+ /** Fresh empty cache — the pre-hydration state (arrays, singleton defaults). */
14
+ empty: () => Database;
15
+ }
16
+
17
+ /** Wildcard channel: every emit also pings its subscribers (useQuery). */
18
+ export const REFETCH_ALL = '__refetch_all__';
19
+
20
+ type Listener = () => void;
21
+
22
+ export function createStore<Database extends object>(config: StoreConfig<Database>) {
23
+ const { endpoints, empty } = config;
24
+ const keys = Object.keys(endpoints) as (keyof Database & string)[];
25
+ const cache: Database = empty(); // mutated in place as collections load
26
+ let hydration: Promise<void> | null = null;
27
+
28
+ const listeners = new Map<string, Set<Listener>>();
29
+
30
+ function emit(key: string) {
31
+ listeners.get(key)?.forEach((l) => l());
32
+ listeners.get(REFETCH_ALL)?.forEach((l) => l());
33
+ }
34
+
35
+ async function loadCollection(key: keyof Database & string): Promise<void> {
36
+ // Rows arrive domain-shaped (drizzle serializes property names; dates as
37
+ // ISO strings). Singleton collections return their one row — same call.
38
+ (cache as Record<string, unknown>)[key] = await apiFetch<unknown>(endpoints[key]);
39
+ }
40
+
41
+ /** Fetch every collection once (parallel) and populate the cache. */
42
+ function ensureHydrated(): Promise<void> {
43
+ if (!hydration) {
44
+ hydration = (async () => {
45
+ await Promise.all(keys.map((key) => loadCollection(key)));
46
+ keys.forEach(emit); // per-collection subscribers
47
+ emit(REFETCH_ALL); // useQuery subscribers
48
+ })().catch((err) => {
49
+ hydration = null; // next reader retries
50
+ throw err;
51
+ });
52
+ }
53
+ return hydration;
54
+ }
55
+
56
+ /** Re-fetch the given collections after a write, then invalidate subscribers. */
57
+ async function refresh(collectionKeys: ReadonlyArray<keyof Database & string>): Promise<void> {
58
+ await Promise.all(collectionKeys.map((key) => loadCollection(key)));
59
+ collectionKeys.forEach(emit);
60
+ }
61
+
62
+ /** Synchronous cache read (empty until first hydration completes). */
63
+ function getDb(): Database {
64
+ return cache;
65
+ }
66
+
67
+ function subscribe(collectionKeys: string[], cb: Listener): () => void {
68
+ const disposers = collectionKeys.map((key) => {
69
+ if (!listeners.has(key)) listeners.set(key, new Set());
70
+ listeners.get(key)!.add(cb);
71
+ return () => listeners.get(key)?.delete(cb);
72
+ });
73
+ return () => disposers.forEach((d) => d());
74
+ }
75
+
76
+ /** The repository write idiom, bound: mutate through the API, then refresh
77
+ * the collections the write touched. Refresh only runs when the write
78
+ * succeeded — failures leave the cache untouched. */
79
+ function apiWrite<T = void>(
80
+ path: string,
81
+ init: { method: 'POST' | 'PATCH' | 'PUT' | 'DELETE'; json?: unknown },
82
+ collectionKeys: ReadonlyArray<keyof Database & string> = [],
83
+ ): Promise<T> {
84
+ return clientApiWrite<T>(path, init, [...collectionKeys], (keys) => refresh(keys as (keyof Database & string)[]));
85
+ }
86
+
87
+ return { ensureHydrated, refresh, getDb, subscribe, emit, apiWrite };
88
+ }