@20baht/app 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # @20baht/app changelog
2
2
 
3
+ ## 0.1.1
4
+
5
+ - `@20baht/app/browser`: `appClient<typeof app>({ url, fetch, headers })`, the client of the app's form and table routes, typed by the app's type alone. `submit(name, data)` answers `{ ok, answer }`, `invalid` with the 422's `issues`, or `refused` with the status and message; `search(name, query)` answers `{ ok, page }` or `refused`. No dependency, no element.
6
+
3
7
  ## 0.1.0
4
8
 
5
9
  - First release. `defineApp({ forms, tables, definitions, validation, caller, policy })`: a write route per form, a search route per table and the routes of `@20baht/definitions`, as a `fetch` handler any server runs.
package/README.md CHANGED
@@ -106,6 +106,32 @@ type Search = Routes['POST /tables/orders']; // { body: TableQueryOf, answer: Ta
106
106
  A form, table or column the definition does not have is a type error. The definitions routes are not
107
107
  in the map.
108
108
 
109
+ ## The client: `@20baht/app/browser`
110
+
111
+ The same routes as two calls, typed by the app. Only the app's type is imported, so nothing of the
112
+ server reaches the bundle; it has no dependency and knows no element.
113
+
114
+ ```ts
115
+ import { appClient } from '@20baht/app/browser';
116
+ import type { app } from '../server/app';
117
+
118
+ const api = appClient<typeof app>({ url: '/api' });
119
+
120
+ const sent = await api.submit('order', { customer: 'Ann', qty: 2 });
121
+ if (sent.ok) sent.answer; // what the form's handler returned
122
+ else if (sent.reason === 'invalid') sent.issues; // the 422: { ref, message }[], refs the form's
123
+ else sent.message; // 'refused': any other answer, with its status
124
+
125
+ const found = await api.search('orders', { sort: { key: 'qty', dir: 'desc' } });
126
+ if (found.ok) found.page.rows; // the table's rows
127
+ ```
128
+
129
+ - `url`: where the app is mounted (the page's own origin without it). `fetch`: the host's own, for
130
+ its credentials. `headers`: asked on every request, for a token that is refreshed.
131
+ - A call resolves for whatever the server answers and rejects only when no answer came.
132
+ - With `@20baht/ui/typed`: `order.onSubmit((data) => api.submit('order', data))` and
133
+ `orders.onQuery((query) => api.search('orders', query))` fit without a cast.
134
+
109
135
  ## Not in this version
110
136
 
111
137
  Runs (their actions will be `runs.*`), live queries and MCP.
@@ -0,0 +1,65 @@
1
+ import type { RoutesOf } from './index.js';
2
+ /** The names after `prefix` among the routes `Routes`. */
3
+ type Names<Routes, Prefix extends string> = keyof Routes extends infer Key ? Key extends `${Prefix}${infer Name}` ? Name : never : never;
4
+ type Route<Routes, Key> = Key extends keyof Routes ? Routes[Key] : never;
5
+ type Part<R, Key extends PropertyKey> = R extends Record<Key, infer Value> ? Value : never;
6
+ /** The names of an app's forms. */
7
+ export type FormName<A> = Names<RoutesOf<A>, 'POST /forms/'>;
8
+ /** The names of an app's tables. */
9
+ export type TableName<A> = Names<RoutesOf<A>, 'POST /tables/'>;
10
+ type FormRouteOf<A, Name extends string> = Route<RoutesOf<A>, `POST /forms/${Name}`>;
11
+ type TableRouteOf<A, Name extends string> = Route<RoutesOf<A>, `POST /tables/${Name}`>;
12
+ /** The body a form's route takes. */
13
+ export type FormBody<A, Name extends string> = Part<FormRouteOf<A, Name>, 'body'>;
14
+ /** What a form's handler answers. */
15
+ export type FormAnswer<A, Name extends string> = Part<FormRouteOf<A, Name>, 'answer'>;
16
+ /** A refused submission's issues. */
17
+ export type FormIssues<A, Name extends string> = Part<Part<FormRouteOf<A, Name>, 422>, 'issues'>;
18
+ /** The query a table's route takes. */
19
+ export type TableBody<A, Name extends string> = Part<TableRouteOf<A, Name>, 'body'>;
20
+ /** The page a table's route answers. */
21
+ export type TableAnswer<A, Name extends string> = Part<TableRouteOf<A, Name>, 'answer'>;
22
+ /** The server said no for another reason than the form's own checks: its status and message. */
23
+ export interface Refused {
24
+ ok: false;
25
+ reason: 'refused';
26
+ status: number;
27
+ /** The answer's `message`, or `HTTP <status>` when it has none. */
28
+ message: string;
29
+ }
30
+ export type SubmitResult<A, Name extends string> = {
31
+ ok: true;
32
+ answer: FormAnswer<A, Name>;
33
+ } | {
34
+ ok: false;
35
+ reason: 'invalid';
36
+ issues: FormIssues<A, Name>;
37
+ } | Refused;
38
+ export type SearchResult<A, Name extends string> = {
39
+ ok: true;
40
+ page: TableAnswer<A, Name>;
41
+ } | Refused;
42
+ export interface AppClientOptions {
43
+ /** Where the app is mounted: `/api`, or another origin. The page's own origin without it. */
44
+ url?: string;
45
+ /** The page's `fetch` without it. A host's own carries its credentials. */
46
+ fetch?: (url: string, init: RequestInit) => Promise<Response>;
47
+ /** Headers of every request, asked each time (a token that is refreshed). */
48
+ headers?: () => Record<string, string> | Promise<Record<string, string>>;
49
+ }
50
+ export interface AppClient<A> {
51
+ /**
52
+ * `POST /forms/<name>`. Resolves for whatever the server answers; rejects only when no answer
53
+ * came (the network, an abort).
54
+ */
55
+ submit<Name extends FormName<A>>(name: Name, data: FormBody<A, NoInfer<Name>>): Promise<SubmitResult<A, Name>>;
56
+ /** `POST /tables/<name>`. */
57
+ search<Name extends TableName<A>>(name: Name, query: TableBody<A, NoInfer<Name>>): Promise<SearchResult<A, Name>>;
58
+ }
59
+ /**
60
+ * The client of an app's routes. `A` is the app's type (`typeof app`, imported as a type): a
61
+ * form or table it does not have, a body that is not the form's, a column that is not the
62
+ * table's, is a type error.
63
+ */
64
+ export declare function appClient<A>(options?: AppClientOptions): AppClient<A>;
65
+ export {};
@@ -0,0 +1,40 @@
1
+ const isRecord = (value) => typeof value === 'object' && value !== null;
2
+ async function jsonOf(response) {
3
+ const [type = ''] = (response.headers.get('content-type') ?? '').split(';');
4
+ if (type.trim().toLowerCase() !== 'application/json')
5
+ return undefined;
6
+ const text = await response.text();
7
+ return text === '' ? undefined : JSON.parse(text);
8
+ }
9
+ function refused(status, body) {
10
+ const message = isRecord(body) && typeof body.message === 'string' ? body.message : `HTTP ${String(status)}`;
11
+ return { ok: false, reason: 'refused', status, message };
12
+ }
13
+ export function appClient(options = {}) {
14
+ const base = (options.url ?? '').replace(/\/+$/, '');
15
+ const send = options.fetch ?? ((url, init) => globalThis.fetch(url, init));
16
+ const post = async (path, body) => {
17
+ const response = await send(`${base}${path}`, {
18
+ method: 'POST',
19
+ headers: { ...(await options.headers?.()), 'content-type': 'application/json' },
20
+ body: JSON.stringify(body),
21
+ });
22
+ return { status: response.status, body: await jsonOf(response) };
23
+ };
24
+ const passed = (status) => status >= 200 && status < 300;
25
+ return {
26
+ async submit(name, data) {
27
+ const { status, body } = await post(`/forms/${name}`, data);
28
+ if (passed(status))
29
+ return { ok: true, answer: body };
30
+ if (status === 422 && isRecord(body) && Array.isArray(body.issues)) {
31
+ return { ok: false, reason: 'invalid', issues: body.issues };
32
+ }
33
+ return refused(status, body);
34
+ },
35
+ async search(name, query) {
36
+ const { status, body } = await post(`/tables/${name}`, query);
37
+ return passed(status) ? { ok: true, page: body } : refused(status, body);
38
+ },
39
+ };
40
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@20baht/app",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=20.19.0"
@@ -27,6 +27,11 @@
27
27
  "import": "./dist/index.js",
28
28
  "default": "./dist/index.js"
29
29
  },
30
+ "./browser": {
31
+ "types": "./dist/browser.d.ts",
32
+ "import": "./dist/browser.js",
33
+ "default": "./dist/browser.js"
34
+ },
30
35
  "./package.json": "./package.json"
31
36
  },
32
37
  "scripts": {