@softistx/riva-rest 0.0.0-stage → 0.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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +151 -2
  3. package/dist/bff/index.d.ts +15 -0
  4. package/dist/bff/index.d.ts.map +1 -0
  5. package/dist/bff/index.js +21 -0
  6. package/dist/bff/index.js.map +10 -0
  7. package/dist/chunks/index-9628zgfc.js +8 -0
  8. package/dist/chunks/index-9628zgfc.js.map +10 -0
  9. package/dist/chunks/index-ytrzmcp0.js +28 -0
  10. package/dist/chunks/index-ytrzmcp0.js.map +10 -0
  11. package/dist/entities/index.d.ts +27 -0
  12. package/dist/entities/index.d.ts.map +1 -0
  13. package/dist/entities/index.js +38 -0
  14. package/dist/entities/index.js.map +10 -0
  15. package/dist/errors.d.ts +17 -0
  16. package/dist/errors.d.ts.map +1 -0
  17. package/dist/http-transport.d.ts +13 -0
  18. package/dist/http-transport.d.ts.map +1 -0
  19. package/dist/index.d.ts +13 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +148 -0
  22. package/dist/index.js.map +14 -0
  23. package/dist/operation.d.ts +16 -0
  24. package/dist/operation.d.ts.map +1 -0
  25. package/dist/query.d.ts +44 -0
  26. package/dist/query.d.ts.map +1 -0
  27. package/dist/server/index.d.ts +18 -0
  28. package/dist/server/index.d.ts.map +1 -0
  29. package/dist/server/index.js +45 -0
  30. package/dist/server/index.js.map +10 -0
  31. package/dist/transport.d.ts +38 -0
  32. package/dist/transport.d.ts.map +1 -0
  33. package/dist/types.d.ts +42 -0
  34. package/dist/types.d.ts.map +1 -0
  35. package/dist/wire.d.ts +5 -0
  36. package/dist/wire.d.ts.map +1 -0
  37. package/docs/README.md +19 -0
  38. package/docs/guide/bff.md +92 -0
  39. package/docs/guide/cache.md +44 -0
  40. package/docs/guide/errors.md +33 -0
  41. package/docs/guide/free-fetcher.md +47 -0
  42. package/docs/guide/openapi.md +45 -0
  43. package/docs/guide/transport.md +49 -0
  44. package/docs/troubleshooting.md +184 -0
  45. package/package.json +85 -5
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Steve Tsala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,152 @@
1
- # Temporary Holding Version
1
+ # @softistx/riva-rest
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ REST for [riva](https://github.com/softistx/riva/blob/develop/packages/riva/README.md): `query` and `mutation` definitions typed from an OpenAPI spec through [`@softistx/openapi-httpyz`](https://github.com/softistx/nxgt-http/tree/develop/packages/openapi-httpyz) (path parameters, query, body and reply, never annotated), a free-fetcher mode for APIs with no schema, a per-client transport over [`@softistx/httpyz`](https://github.com/softistx/nxgt-http/tree/develop/packages/httpyz), and httpyz's errors mapped to riva's.
4
+
5
+ Guides and fixes: [docs](./docs/README.md). Work in progress, see the [spec](https://github.com/softistx/riva/blob/develop/docs/spec.md).
6
+
7
+ ```sh
8
+ bun add @softistx/riva @softistx/riva-rest @softistx/httpyz @softistx/openapi-httpyz zod
9
+ bun add -d @softistx/openapi-codegen typescript
10
+ ```
11
+
12
+ Peers: `@softistx/riva` and `@softistx/httpyz`. `@softistx/openapi-httpyz` is optional: only the OpenAPI mode needs it. `@softistx/openapi-codegen` writes the operations table at build time, and that generated `operations.ts` imports `zod`. The runtime entries import none of them.
13
+
14
+ ## Provide the transport
15
+
16
+ Definitions are stateless; the transport lives on the `RivaClient` that runs them. Give each client one when you create it (on the server, one per request).
17
+
18
+ The OpenAPI mode reads the operations the spec describes, which `@softistx/openapi-codegen` generates:
19
+
20
+ ```sh
21
+ bunx nxgt-openapi generate -i openapi.yaml # writes generated/openapi
22
+ ```
23
+
24
+ Then, in `api.ts`:
25
+
26
+ ```ts
27
+ import { createHttpClient } from '@softistx/httpyz';
28
+ import { createOpenApiClient } from '@softistx/openapi-httpyz';
29
+ import { createRivaClient } from '@softistx/riva';
30
+ import { httpyzTransport, provideRest } from '@softistx/riva-rest';
31
+ import { operations } from './generated/openapi/operations'; // from `nxgt-openapi generate`
32
+
33
+ const http = createHttpClient({ baseUrl: 'https://api.example.com', timeout: 10_000 });
34
+ export const api = createOpenApiClient(http, operations);
35
+
36
+ export const client = createRivaClient();
37
+ provideRest(client, httpyzTransport(http, api));
38
+ ```
39
+
40
+ `httpyzTransport(http, api?)`: pass `api` for the OpenAPI mode; without it only free fetchers run. A read on a client with no transport throws `RivaScopeError`. [Guide](./docs/guide/transport.md).
41
+
42
+ ## OpenAPI mode
43
+
44
+ `query(api, 'method path', options?)`: the route is the one the spec writes (`'get /invoices/{id}'`), checked at compile time and when the definition is created. The variables are the operation's input (`param`, `query`, `json`, …), the data is its 2xx reply, both from the spec.
45
+
46
+ ```ts
47
+ import { mutation, query } from '@softistx/riva-rest';
48
+ import { api } from './api';
49
+
50
+ export const invoice = query(api, 'get /invoices/{id}', { staleTime: '30s' });
51
+ export const invoices = query(api, 'get /invoices');
52
+ export const createInvoice = mutation(api, 'post /invoices', { invalidates: [invoices] });
53
+
54
+ await invoice.ensure(client, { param: { id: '7' } }); // Invoice
55
+ await createInvoice.run(client, { json: { number: 'F-8', total: 120 } });
56
+ client.get(invoices); // an operation whose input is all optional takes no variables
57
+ ```
58
+
59
+ The id is the route; any core option works (`staleTime`, `gcTime`, `retry`, `refetchEvery`, `cache`, and for a mutation `optimistic`, `updates`, `invalidates`). `query()` takes every route but `put`, `patch` and `delete`, `mutation()` every one but `get`, `head` and `options`. [Guide](./docs/guide/openapi.md).
60
+
61
+ ## Free fetcher
62
+
63
+ For an API with no schema, write the function: its types are the definition's types.
64
+
65
+ ```ts
66
+ import { mutation, query } from '@softistx/riva-rest';
67
+
68
+ type Todo = { id: string; title: string; done: boolean };
69
+
70
+ export const todos = query({
71
+ id: 'todos',
72
+ fetch: async (vars: { done?: boolean }, { http, signal }) => {
73
+ const reply = await http.get('/todos', { query: vars, signal });
74
+ return reply.data as Todo[];
75
+ },
76
+ });
77
+
78
+ export const renameTodo = mutation({
79
+ id: 'renameTodo',
80
+ run: async (vars: { id: string; title: string }, { http, signal }) =>
81
+ (await http.patch('/todos/{id}', { param: { id: vars.id }, json: { title: vars.title }, signal })).data as Todo,
82
+ });
83
+ ```
84
+
85
+ `id` is required. The context is the core's plus `http`, read lazily. [Guide](./docs/guide/free-fetcher.md).
86
+
87
+ ## Errors
88
+
89
+ The transport and the free fetcher throw riva's errors, defined once in the core so `instanceof` holds.
90
+
91
+ | httpyz | riva | retried |
92
+ | --- | --- | --- |
93
+ | a status the spec declares, not 2xx | `RivaHttpError` (`HTTP_404`, the reply is its `cause`) | 5xx, 408, 429 |
94
+ | `UndeclaredStatusError`, `ReplyStatusError` | `RivaHttpError` | 5xx, 408, 429 |
95
+ | `NetworkError`, `TimeoutError` | `RivaNetworkError` | yes |
96
+ | `ValidationError` on the request | `RivaRequestError` `RIVA_VALIDATION` | no |
97
+ | `ValidationError` on the reply | `RivaRequestError` `RIVA_INVALID_RESPONSE` | no |
98
+ | the caller's abort | `RivaAbortError` | no |
99
+ | a transport with no OpenAPI client, or one that lacks the operation | `RivaRequestError` `RIVA_REST_UNWIRED` | no |
100
+
101
+ `toRivaError(error, signal?)` is exported for your own transports. [Guide](./docs/guide/errors.md), [troubleshooting](./docs/troubleshooting.md).
102
+
103
+ ## BFF mode
104
+
105
+ Run the REST calls on the server and keep the browser away from the API: the browser posts `{ id, variables }` to a `dataRoute` (`@softistx/riva-react-router`'s `/_data`), the server runs the operation through the request client's transport (with its session and base URL) and sends the data back.
106
+
107
+ Server: `rivaMiddleware({ setup })` gives each request client its transport, and `dataRoute({ sources: [operations(api)] })` serves the spec's operations. Browser: the same definitions with `provideRest(client, bffTransport())` in the router provider's `setup`. Ids are `rest:<operationId>`; free fetchers are server-only. [Guide](./docs/guide/bff.md).
108
+
109
+ ```tsx
110
+ import { RivaRouterProvider } from '@softistx/riva-react-router';
111
+ import { provideRest } from '@softistx/riva-rest';
112
+ import { bffTransport } from '@softistx/riva-rest/bff';
113
+ import { Outlet } from 'react-router';
114
+
115
+ export default function Root() {
116
+ return (
117
+ <RivaRouterProvider setup={(client) => provideRest(client, bffTransport())}>
118
+ <Outlet />
119
+ </RivaRouterProvider>
120
+ );
121
+ }
122
+ ```
123
+
124
+ ## Cache
125
+
126
+ By default an entry is keyed by request: the route and its input. To share resources between queries, opt in to entities from `@softistx/riva-rest/entities`: each object you recognise is stored once, and a refetch or a mutation result updates every query that shows it.
127
+
128
+ ```ts
129
+ import { query, mutation } from '@softistx/riva-rest';
130
+ import { restEntities } from '@softistx/riva-rest/entities';
131
+ import { api } from './api';
132
+
133
+ // One policy for the client's queries and mutations.
134
+ export const cache = restEntities({
135
+ Invoice: { is: (o) => 'number' in o, key: (o) => o['id'] as string },
136
+ });
137
+
138
+ export const invoice = query(api, 'get /invoices/{id}', { cache });
139
+ export const invoices = query(api, 'get /invoices', { cache });
140
+ export const createInvoice = mutation(api, 'post /invoices', { cache });
141
+ ```
142
+
143
+ `is` says whether an object of a response is that type (REST has no `__typename`), `key` gives its id. Share the `restEntities()` result itself. [Guide](./docs/guide/cache.md).
144
+
145
+ ## Entry points
146
+
147
+ - `@softistx/riva-rest`: `query`, `mutation`, `rest` (`{ query, mutation }`), `provideRest`, `httpyzTransport`, `toRivaError`, `operationOf` (reads a route into `{ id, method, path, operationId, hasInput }`) and the types: `RestTransport`, `RestContext`, `Route`, `Operation`, the options (`RestQueryOptions`, `RestMutationOptions`, `FreeQueryOptions`, `FreeMutationOptions`), the routes (`RouteOf`, `QueryRoute`, `MutationRoute`) and `InputOf`, `DataOf`, `SpecOf`, `ClientOf`, `DecodedOf`.
148
+ - `@softistx/riva-rest/entities`: `restEntities` and the types `RestEntity`, `RestEntities`.
149
+ - `@softistx/riva-rest/server`: `operations(api)` (a `DataSource` for `dataRoute`), the constant `PREFIX` (`'rest:'`, the prefix of every id the route serves: `rest:<operationId>`) and the types `DataSource`, `DataOperation`, `OperationsOf`.
150
+ - `@softistx/riva-rest/bff`: `bffTransport(opts)` and the type `BffTransportOptions`.
151
+
152
+ Size: riva + riva-rest stays under 8 kB gzipped, and riva + `/bff` under 9 kB, httpyz and openapi-httpyz not counted.
@@ -0,0 +1,15 @@
1
+ import { type BffTransportOptions } from '@softistx/riva/data';
2
+ import type { RestTransport } from '../transport';
3
+ export type { BffTransportOptions };
4
+ /**
5
+ * The browser's REST transport: posts `{ id: 'rest:<operationId>', variables }`
6
+ * to a `dataRoute` and reads `{ data }` back, Dates included. The route's
7
+ * refusals and the API's errors come back as `RivaRequestError` with the
8
+ * route's `code` and `status` (retryable for 5xx, 408 and 429); a failed fetch
9
+ * is a `RivaNetworkError`, an abort a `RivaAbortError`, a body that is not the
10
+ * route's JSON `RIVA_INVALID_RESPONSE`. Cookies of the same origin go with the
11
+ * call. It holds no httpyz client: a free fetcher that reads `http` throws
12
+ * `RivaScopeError`, since it only runs on the server.
13
+ */
14
+ export declare function bffTransport(opts?: BffTransportOptions): RestTransport;
15
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/bff/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,mBAAmB,EAAY,MAAM,qBAAqB,CAAC;AACzE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAGlD,YAAY,EAAE,mBAAmB,EAAE,CAAC;AAEpC;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,IAAI,GAAE,mBAAwB,GAAG,aAAa,CAU1E"}
@@ -0,0 +1,21 @@
1
+ import {
2
+ PREFIX2
3
+ } from "../chunks/index-9628zgfc.js";
4
+
5
+ // src/bff/index.ts
6
+ import { RivaScopeError } from "@softistx/riva";
7
+ import { postData } from "@softistx/riva/data";
8
+ function bffTransport(opts = {}) {
9
+ return {
10
+ get http() {
11
+ throw new RivaScopeError("A free fetcher uses httpyz, which is server-only: in the browser, call it through an operation of the API's spec (query(api, ...)) served by operations() on /_data, or run it in a loader.");
12
+ },
13
+ call: (route, input, { signal }) => postData(opts, `${PREFIX2}${route.operationId}`, input, signal)
14
+ };
15
+ }
16
+ export {
17
+ bffTransport
18
+ };
19
+
20
+ //# debugId=FAA9418967AF284A64756E2164756E21
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/bff/index.ts"],
4
+ "sourcesContent": [
5
+ "import type { HttpClient } from '@softistx/httpyz';\nimport { RivaScopeError } from '@softistx/riva';\nimport { type BffTransportOptions, postData } from '@softistx/riva/data';\nimport type { RestTransport } from '../transport';\nimport { PREFIX } from '../wire';\n\nexport type { BffTransportOptions };\n\n/**\n * The browser's REST transport: posts `{ id: 'rest:<operationId>', variables }`\n * to a `dataRoute` and reads `{ data }` back, Dates included. The route's\n * refusals and the API's errors come back as `RivaRequestError` with the\n * route's `code` and `status` (retryable for 5xx, 408 and 429); a failed fetch\n * is a `RivaNetworkError`, an abort a `RivaAbortError`, a body that is not the\n * route's JSON `RIVA_INVALID_RESPONSE`. Cookies of the same origin go with the\n * call. It holds no httpyz client: a free fetcher that reads `http` throws\n * `RivaScopeError`, since it only runs on the server.\n */\nexport function bffTransport(opts: BffTransportOptions = {}): RestTransport {\n\treturn {\n\t\tget http(): HttpClient {\n\t\t\tthrow new RivaScopeError(\n\t\t\t\t\"A free fetcher uses httpyz, which is server-only: in the browser, call it through an operation of the API's spec (query(api, ...)) served by operations() on /_data, or run it in a loader.\",\n\t\t\t);\n\t\t},\n\t\tcall: (route, input, { signal }) =>\n\t\t\tpostData(opts, `${PREFIX}${route.operationId}`, input, signal),\n\t};\n}\n"
6
+ ],
7
+ "mappings": ";;;;;AACA;AACA;AAgBO,SAAS,YAAY,CAAC,OAA4B,CAAC,GAAkB;AAAA,EAC3E,OAAO;AAAA,QACF,IAAI,GAAe;AAAA,MACtB,MAAM,IAAI,eACT,6LACD;AAAA;AAAA,IAED,MAAM,CAAC,OAAO,SAAS,aACtB,SAAS,MAAM,GAAG,UAAS,MAAM,eAAe,OAAO,MAAM;AAAA,EAC/D;AAAA;",
8
+ "debugId": "FAA9418967AF284A64756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,8 @@
1
+ // src/wire.ts
2
+ var SAFE = new Set(["get", "head", "options"]);
3
+ var PREFIX2 = "rest:";
4
+
5
+ export { SAFE, PREFIX2 };
6
+
7
+ //# debugId=3224C07E9BFD01E364756E2164756E21
8
+ //# sourceMappingURL=index-9628zgfc.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/wire.ts"],
4
+ "sourcesContent": [
5
+ "/** HTTP methods that only read: their operations are queries, the others mutations. */\nexport const SAFE: ReadonlySet<string> = new Set(['get', 'head', 'options']);\n\n/** The id the browser names an operation by: `rest:<operationId>`. */\nexport const PREFIX = 'rest:';\n"
6
+ ],
7
+ "mappings": ";AACO,IAAM,OAA4B,IAAI,IAAI,CAAC,OAAO,QAAQ,SAAS,CAAC;AAGpE,IAAM,UAAS;",
8
+ "debugId": "3224C07E9BFD01E364756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,28 @@
1
+ // src/transport.ts
2
+ import {
3
+ RivaScopeError
4
+ } from "@softistx/riva";
5
+ var SLOT = {};
6
+ function provideRest2(client, transport) {
7
+ client.slots.set(SLOT, transport);
8
+ }
9
+ function transportOf(client) {
10
+ const transport = client.slots.get(SLOT);
11
+ if (!transport)
12
+ throw new RivaScopeError("No REST transport on this RivaClient: call provideRest(client, httpyzTransport(http, api)) when you create it.");
13
+ return transport;
14
+ }
15
+ var restContext = (ctx) => Object.defineProperty({ ...ctx }, "http", {
16
+ enumerable: true,
17
+ get() {
18
+ const { http } = transportOf(ctx.client);
19
+ if (!http)
20
+ throw new RivaScopeError("The REST transport of this RivaClient holds no httpyz client: build it with httpyzTransport(http, api).");
21
+ return http;
22
+ }
23
+ });
24
+
25
+ export { provideRest2, transportOf, restContext };
26
+
27
+ //# debugId=524892BA929C7D9F64756E2164756E21
28
+ //# sourceMappingURL=index-ytrzmcp0.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/transport.ts"],
4
+ "sourcesContent": [
5
+ "import type { HttpClient } from '@softistx/httpyz';\nimport {\n\ttype FetchContext,\n\ttype RivaClient,\n\tRivaScopeError,\n} from '@softistx/riva';\n\n/** Which operation to call, as found in the client's table when the definition was made. */\nexport interface Route {\n\t/** The method, lowercase. */\n\treadonly method: string;\n\t/** The path as the spec writes it. */\n\treadonly path: string;\n\t/** The operation's `operationId`, the key of the client's table. */\n\treadonly operationId: string;\n\t/** Whether the operation takes an input (parameters or a body). */\n\treadonly hasInput: boolean;\n}\n\n/**\n * Runs one OpenAPI operation. `@softistx/riva-rest` ships `httpyzTransport`;\n * any object of this shape works (a transport that posts to a BFF route, a\n * test double). It resolves with the data of the 2xx reply and throws\n * `RivaError`s.\n */\nexport interface RestTransport {\n\t/** The httpyz client, handed to free fetchers; absent on a transport that has none. */\n\treadonly http?: HttpClient;\n\tcall(\n\t\troute: Route,\n\t\tinput: unknown,\n\t\toptions: { signal: AbortSignal },\n\t): Promise<unknown>;\n}\n\n// Held on the client's slots: the transport of a request dies with its client.\nconst SLOT = {};\n\n/** Gives `client` the transport its REST definitions fetch through. */\nexport function provideRest(\n\tclient: RivaClient,\n\ttransport: RestTransport,\n): void {\n\tclient.slots.set(SLOT, transport);\n}\n\n/** The transport `provideRest` gave `client`; throws `RivaScopeError` when none. */\nexport function transportOf(client: RivaClient): RestTransport {\n\tconst transport = client.slots.get(SLOT) as RestTransport | undefined;\n\tif (!transport)\n\t\tthrow new RivaScopeError(\n\t\t\t'No REST transport on this RivaClient: call provideRest(client, httpyzTransport(http, api)) when you create it.',\n\t\t);\n\treturn transport;\n}\n\n/** What a free fetcher receives: the core's context, and the client's httpyz instance. */\nexport interface RestContext extends FetchContext {\n\t/** The httpyz client of the transport; reading it with none provided throws `RivaScopeError`. */\n\treadonly http: HttpClient;\n}\n\n/** The core's context, with `http` read from the client's transport when the fetcher asks for it. */\nexport const restContext = (ctx: FetchContext): RestContext =>\n\tObject.defineProperty({ ...ctx }, 'http', {\n\t\tenumerable: true,\n\t\tget(): HttpClient {\n\t\t\tconst { http } = transportOf(ctx.client);\n\t\t\tif (!http)\n\t\t\t\tthrow new RivaScopeError(\n\t\t\t\t\t'The REST transport of this RivaClient holds no httpyz client: build it with httpyzTransport(http, api).',\n\t\t\t\t);\n\t\t\treturn http;\n\t\t},\n\t}) as RestContext;\n"
6
+ ],
7
+ "mappings": ";AACA;AAAA;AAAA;AAmCA,IAAM,OAAO,CAAC;AAGP,SAAS,YAAW,CAC1B,QACA,WACO;AAAA,EACP,OAAO,MAAM,IAAI,MAAM,SAAS;AAAA;AAI1B,SAAS,WAAW,CAAC,QAAmC;AAAA,EAC9D,MAAM,YAAY,OAAO,MAAM,IAAI,IAAI;AAAA,EACvC,IAAI,CAAC;AAAA,IACJ,MAAM,IAAI,eACT,gHACD;AAAA,EACD,OAAO;AAAA;AAUD,IAAM,cAAc,CAAC,QAC3B,OAAO,eAAe,KAAK,IAAI,GAAG,QAAQ;AAAA,EACzC,YAAY;AAAA,EACZ,GAAG,GAAe;AAAA,IACjB,QAAQ,SAAS,YAAY,IAAI,MAAM;AAAA,IACvC,IAAI,CAAC;AAAA,MACJ,MAAM,IAAI,eACT,yGACD;AAAA,IACD,OAAO;AAAA;AAET,CAAC;",
8
+ "debugId": "524892BA929C7D9F64756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,27 @@
1
+ import { type EntitiesOptions, type EntityPolicy, type Fields } from '@softistx/riva/entities';
2
+ /** How one REST resource becomes an entity. */
3
+ export interface RestEntity {
4
+ /** Whether an object of the response is one (a shape check: `'invoiceNo' in o`). */
5
+ is(obj: Fields): boolean;
6
+ /** Its id; `undefined` leaves the object a plain value. */
7
+ key(obj: Fields): string | number | undefined;
8
+ }
9
+ /** The entity types of an API, by name: `{ Invoice: { is, key } }`. */
10
+ export type RestEntities = Record<string, RestEntity>;
11
+ /**
12
+ * A cache policy that stores the REST resources you declare as shared
13
+ * entities, so a refetch of one query updates the others and a mutation's
14
+ * result reaches every query that shows it:
15
+ *
16
+ * ```ts
17
+ * const cache = restEntities({
18
+ * Invoice: { is: (o) => 'number' in o, key: (o) => o['id'] as string },
19
+ * });
20
+ * query(api, 'get /invoices/{id}', { cache });
21
+ * ```
22
+ *
23
+ * Objects `is` recognises get a `__typename`, so the data a reader sees
24
+ * carries it. Share one policy between the queries of a client.
25
+ */
26
+ export declare function restEntities(types: RestEntities, options?: Pick<EntitiesOptions, 'identify'>): EntityPolicy;
27
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/entities/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,eAAe,EACpB,KAAK,YAAY,EAEjB,KAAK,MAAM,EAEX,MAAM,yBAAyB,CAAC;AAEjC,+CAA+C;AAC/C,MAAM,WAAW,UAAU;IAC1B,oFAAoF;IACpF,EAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IACzB,2DAA2D;IAC3D,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;CAC9C;AAED,uEAAuE;AACvE,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;AAatD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,YAAY,CAC3B,KAAK,EAAE,YAAY,EACnB,OAAO,CAAC,EAAE,IAAI,CAAC,eAAe,EAAE,UAAU,CAAC,GACzC,YAAY,CAcd"}
@@ -0,0 +1,38 @@
1
+ // src/entities/index.ts
2
+ import {
3
+ entities,
4
+ isPlain
5
+ } from "@softistx/riva/entities";
6
+ function tag(types, value) {
7
+ if (Array.isArray(value))
8
+ return value.map((item) => tag(types, item));
9
+ if (!isPlain(value))
10
+ return value;
11
+ const out = {};
12
+ for (const [k, v] of Object.entries(value))
13
+ out[k] = tag(types, v);
14
+ if (typeof out["__typename"] === "string")
15
+ return out;
16
+ const hit = types.find(([, e]) => e.is(value));
17
+ return hit ? { ...out, __typename: hit[0] } : out;
18
+ }
19
+ function restEntities(types, options) {
20
+ const list = Object.entries(types);
21
+ const policy = entities({
22
+ ...options,
23
+ keys: Object.fromEntries(list.map(([name, e]) => [name, e.key]))
24
+ });
25
+ const inner = policy;
26
+ return {
27
+ ...policy,
28
+ write: (client, data, prev, vars) => policy.write(client, tag(list, data), prev, vars),
29
+ layer: (client, data, vars) => inner.layer(client, tag(list, data), vars),
30
+ commit: (client, data, vars) => inner.commit(client, tag(list, data), vars)
31
+ };
32
+ }
33
+ export {
34
+ restEntities
35
+ };
36
+
37
+ //# debugId=3DC5F051E3832C7B64756E2164756E21
38
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/entities/index.ts"],
4
+ "sourcesContent": [
5
+ "import {\n\ttype EntitiesOptions,\n\ttype EntityPolicy,\n\tentities,\n\ttype Fields,\n\tisPlain,\n} from '@softistx/riva/entities';\n\n/** How one REST resource becomes an entity. */\nexport interface RestEntity {\n\t/** Whether an object of the response is one (a shape check: `'invoiceNo' in o`). */\n\tis(obj: Fields): boolean;\n\t/** Its id; `undefined` leaves the object a plain value. */\n\tkey(obj: Fields): string | number | undefined;\n}\n\n/** The entity types of an API, by name: `{ Invoice: { is, key } }`. */\nexport type RestEntities = Record<string, RestEntity>;\n\n/** Tags every object `types` recognises with its `__typename`, on a copy: the response is never mutated. */\nfunction tag(types: [string, RestEntity][], value: unknown): unknown {\n\tif (Array.isArray(value)) return value.map((item) => tag(types, item));\n\tif (!isPlain(value)) return value;\n\tconst out: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(value)) out[k] = tag(types, v);\n\tif (typeof out['__typename'] === 'string') return out;\n\tconst hit = types.find(([, e]) => e.is(value));\n\treturn hit ? { ...out, __typename: hit[0] } : out;\n}\n\n/**\n * A cache policy that stores the REST resources you declare as shared\n * entities, so a refetch of one query updates the others and a mutation's\n * result reaches every query that shows it:\n *\n * ```ts\n * const cache = restEntities({\n * Invoice: { is: (o) => 'number' in o, key: (o) => o['id'] as string },\n * });\n * query(api, 'get /invoices/{id}', { cache });\n * ```\n *\n * Objects `is` recognises get a `__typename`, so the data a reader sees\n * carries it. Share one policy between the queries of a client.\n */\nexport function restEntities(\n\ttypes: RestEntities,\n\toptions?: Pick<EntitiesOptions, 'identify'>,\n): EntityPolicy {\n\tconst list = Object.entries(types);\n\tconst policy = entities({\n\t\t...options,\n\t\tkeys: Object.fromEntries(list.map(([name, e]) => [name, e.key])),\n\t});\n\tconst inner = policy as Required<EntityPolicy>;\n\treturn {\n\t\t...policy,\n\t\twrite: (client, data, prev, vars) =>\n\t\t\tpolicy.write(client, tag(list, data), prev, vars),\n\t\tlayer: (client, data, vars) => inner.layer(client, tag(list, data), vars),\n\t\tcommit: (client, data, vars) => inner.commit(client, tag(list, data), vars),\n\t};\n}\n"
6
+ ],
7
+ "mappings": ";AAAA;AAAA;AAAA;AAAA;AAoBA,SAAS,GAAG,CAAC,OAA+B,OAAyB;AAAA,EACpE,IAAI,MAAM,QAAQ,KAAK;AAAA,IAAG,OAAO,MAAM,IAAI,CAAC,SAAS,IAAI,OAAO,IAAI,CAAC;AAAA,EACrE,IAAI,CAAC,QAAQ,KAAK;AAAA,IAAG,OAAO;AAAA,EAC5B,MAAM,MAA+B,CAAC;AAAA,EACtC,YAAY,GAAG,MAAM,OAAO,QAAQ,KAAK;AAAA,IAAG,IAAI,KAAK,IAAI,OAAO,CAAC;AAAA,EACjE,IAAI,OAAO,IAAI,kBAAkB;AAAA,IAAU,OAAO;AAAA,EAClD,MAAM,MAAM,MAAM,KAAK,IAAI,OAAO,EAAE,GAAG,KAAK,CAAC;AAAA,EAC7C,OAAO,MAAM,KAAK,KAAK,YAAY,IAAI,GAAG,IAAI;AAAA;AAkBxC,SAAS,YAAY,CAC3B,OACA,SACe;AAAA,EACf,MAAM,OAAO,OAAO,QAAQ,KAAK;AAAA,EACjC,MAAM,SAAS,SAAS;AAAA,OACpB;AAAA,IACH,MAAM,OAAO,YAAY,KAAK,IAAI,EAAE,MAAM,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAAA,EAChE,CAAC;AAAA,EACD,MAAM,QAAQ;AAAA,EACd,OAAO;AAAA,OACH;AAAA,IACH,OAAO,CAAC,QAAQ,MAAM,MAAM,SAC3B,OAAO,MAAM,QAAQ,IAAI,MAAM,IAAI,GAAG,MAAM,IAAI;AAAA,IACjD,OAAO,CAAC,QAAQ,MAAM,SAAS,MAAM,MAAM,QAAQ,IAAI,MAAM,IAAI,GAAG,IAAI;AAAA,IACxE,QAAQ,CAAC,QAAQ,MAAM,SAAS,MAAM,OAAO,QAAQ,IAAI,MAAM,IAAI,GAAG,IAAI;AAAA,EAC3E;AAAA;",
8
+ "debugId": "3DC5F051E3832C7B64756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Maps what `@softistx/httpyz` throws to riva's errors, so the core's retry
3
+ * policy and `instanceof` checks work:
4
+ *
5
+ * - the caller's abort: `RivaAbortError`;
6
+ * - `UndeclaredStatusError` and `ReplyStatusError`: `RivaHttpError`, retryable
7
+ * for 5xx, 408 and 429;
8
+ * - `NetworkError` and `TimeoutError`: `RivaNetworkError`, retryable;
9
+ * - `ValidationError`: a non-retryable `RivaRequestError`, `RIVA_VALIDATION`
10
+ * for a request the spec refused (never sent) and `RIVA_INVALID_RESPONSE`
11
+ * for a reply the spec does not describe.
12
+ *
13
+ * Each keeps the httpyz error as its `cause`; anything else is returned as it
14
+ * is.
15
+ */
16
+ export declare function toRivaError(error: unknown, signal?: AbortSignal): unknown;
17
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AA2BA;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CA6BzE"}
@@ -0,0 +1,13 @@
1
+ import type { HttpClient } from '@softistx/httpyz';
2
+ import type { OpenApiClient } from '@softistx/openapi-httpyz';
3
+ import type { RestTransport } from './transport';
4
+ /**
5
+ * The transport over an httpyz client and, for OpenAPI definitions, the
6
+ * client `createOpenApiClient(http, operations)` made over it. A call goes
7
+ * through `api.<method>(path, input, { signal })`, so the spec's validation,
8
+ * decoding and the client's middleware, auth, retries and timeouts all apply.
9
+ * The data of the 2xx reply is returned; a declared reply of another status
10
+ * throws `RivaHttpError`; httpyz's errors are mapped by `toRivaError`.
11
+ */
12
+ export declare function httpyzTransport(http: HttpClient, api?: OpenApiClient<any, any, any>): RestTransport;
13
+ //# sourceMappingURL=http-transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-transport.d.ts","sourceRoot":"","sources":["../src/http-transport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAG9D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AASjD;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAC9B,IAAI,EAAE,UAAU,EAEhB,GAAG,CAAC,EAAE,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,GAChC,aAAa,CAgCf"}
@@ -0,0 +1,13 @@
1
+ import { mutation, query } from './query';
2
+ export { toRivaError } from './errors';
3
+ export { httpyzTransport } from './http-transport';
4
+ export { type Operation, operationOf } from './operation';
5
+ export { type FreeMutationOptions, type FreeQueryOptions, mutation, query, type RestMutationOptions, type RestQueryOptions, } from './query';
6
+ export { provideRest, type RestContext, type RestTransport, type Route, } from './transport';
7
+ export type { ClientOf, DataOf, DecodedOf, InputOf, MutationRoute, QueryRoute, RouteOf, SpecOf, } from './types';
8
+ /** `rest.query(api, 'get /invoices/{id}')`, beside the named exports. */
9
+ export declare const rest: {
10
+ readonly query: typeof query;
11
+ readonly mutation: typeof mutation;
12
+ };
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAE1C,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,KAAK,SAAS,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EACN,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACrB,QAAQ,EACR,KAAK,EACL,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,GACrB,MAAM,SAAS,CAAC;AACjB,OAAO,EACN,WAAW,EACX,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,KAAK,GACV,MAAM,aAAa,CAAC;AACrB,YAAY,EACX,QAAQ,EACR,MAAM,EACN,SAAS,EACT,OAAO,EACP,aAAa,EACb,UAAU,EACV,OAAO,EACP,MAAM,GACN,MAAM,SAAS,CAAC;AAEjB,yEAAyE;AACzE,eAAO,MAAM,IAAI;;;CAA+B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,148 @@
1
+ import {
2
+ provideRest2,
3
+ transportOf,
4
+ restContext
5
+ } from "./chunks/index-ytrzmcp0.js";
6
+ import {
7
+ SAFE
8
+ } from "./chunks/index-9628zgfc.js";
9
+
10
+ // src/query.ts
11
+ import {
12
+ mutation as coreMutation,
13
+ query as coreQuery,
14
+ RivaError as RivaError2
15
+ } from "@softistx/riva";
16
+
17
+ // src/errors.ts
18
+ import {
19
+ RivaAbortError,
20
+ RivaHttpError,
21
+ RivaNetworkError,
22
+ RivaRequestError
23
+ } from "@softistx/riva";
24
+ var isErrorNamed = (e, name) => e instanceof Error && e.name === name;
25
+ var isNamed = (e, name) => isErrorNamed(e, name) && typeof e.method === "string" && typeof e.path === "string";
26
+ function toRivaError(error, signal) {
27
+ if (error instanceof RivaAbortError)
28
+ return error;
29
+ if (signal?.aborted || error instanceof Error && error.name === "AbortError")
30
+ return new RivaAbortError;
31
+ if (error instanceof RivaHttpError || error instanceof RivaNetworkError)
32
+ return error;
33
+ if ((isNamed(error, "UndeclaredStatusError") || isErrorNamed(error, "ReplyStatusError")) && typeof error.status === "number")
34
+ return new RivaHttpError(error.status, error.message, { cause: error });
35
+ if (isNamed(error, "NetworkError") || isNamed(error, "TimeoutError"))
36
+ return new RivaNetworkError(error.message, { cause: error });
37
+ if (isNamed(error, "ValidationError") && (error.failure?.kind === "request" || error.failure?.kind === "response"))
38
+ return new RivaRequestError(error.failure?.kind === "request" ? "RIVA_VALIDATION" : "RIVA_INVALID_RESPONSE", error.message, { retryable: false, cause: error });
39
+ return error;
40
+ }
41
+
42
+ // src/operation.ts
43
+ import { RivaError } from "@softistx/riva";
44
+ function operationOf(spec, route, kind) {
45
+ if (typeof route !== "string")
46
+ throw new RivaError("RIVA_DEFINITION", `riva-rest: ${String(route)} is not a route; write it as '<method> <path>' (get /invoices/{id}).`);
47
+ const at = route.indexOf(" ");
48
+ const method = at > 0 ? route.slice(0, at) : "";
49
+ const path = at > 0 ? route.slice(at + 1) : "";
50
+ if (!method || !path.startsWith("/"))
51
+ throw new RivaError("RIVA_DEFINITION", `riva-rest: "${route}" is not a route; write it as '<method> <path>' (get /invoices/{id}).`);
52
+ const table = spec?.operations ?? {};
53
+ const found = Object.entries(table).find(([, o]) => o.method === method && o.path === path);
54
+ if (!found)
55
+ throw new RivaError("RIVA_DEFINITION", `riva-rest: the OpenAPI client has no operation at ${method.toUpperCase()} ${path}; check the path as the spec writes it.`);
56
+ if (kind === "query" && ["put", "patch", "delete"].includes(method))
57
+ throw new RivaError("RIVA_DEFINITION", `riva-rest: ${method.toUpperCase()} ${path} changes data; define it with mutation(), not query().`);
58
+ if (kind === "mutation" && SAFE.has(method))
59
+ throw new RivaError("RIVA_DEFINITION", `riva-rest: ${method.toUpperCase()} ${path} only reads; define it with query(), not mutation().`);
60
+ const [operationId, entry] = found;
61
+ return {
62
+ id: `${method} ${path}`,
63
+ method,
64
+ path,
65
+ operationId,
66
+ hasInput: (entry.parameters?.length ?? 0) > 0 || entry.body !== undefined
67
+ };
68
+ }
69
+
70
+ // src/query.ts
71
+ var callOf = (route) => async (vars, ctx) => transportOf(ctx.client).call(route, vars, { signal: ctx.signal });
72
+ var guarded = (fn) => async (vars, ctx) => {
73
+ try {
74
+ return await fn(vars, restContext(ctx));
75
+ } catch (error) {
76
+ throw toRivaError(error, ctx.signal);
77
+ }
78
+ };
79
+ var isFree = (a) => typeof a === "object" && a !== null && !("operations" in a);
80
+ function freeId(opts, name) {
81
+ if (typeof opts?.id !== "string" || !opts.id)
82
+ throw new RivaError2("RIVA_DEFINITION", `riva-rest: ${name}() needs an id; a function has no name to derive one from.`);
83
+ }
84
+ function query(first, route, opts = {}) {
85
+ if (isFree(first)) {
86
+ freeId(first, "query");
87
+ const { fetch, ...rest } = first;
88
+ return coreQuery({ ...rest, fetch: guarded(fetch) });
89
+ }
90
+ const op = operationOf(first, route, "query");
91
+ return coreQuery({
92
+ ...opts,
93
+ id: opts.id ?? op.id,
94
+ fetch: callOf(op)
95
+ });
96
+ }
97
+ function mutation(first, route, opts = {}) {
98
+ if (isFree(first)) {
99
+ freeId(first, "mutation");
100
+ const { run, ...rest } = first;
101
+ return coreMutation({ ...rest, run: guarded(run) });
102
+ }
103
+ const op = operationOf(first, route, "mutation");
104
+ return coreMutation({
105
+ ...opts,
106
+ id: opts.id ?? op.id,
107
+ run: callOf(op)
108
+ });
109
+ }
110
+ // src/http-transport.ts
111
+ import { RivaHttpError as RivaHttpError2, RivaRequestError as RivaRequestError2 } from "@softistx/riva";
112
+ var unwired = (message) => new RivaRequestError2("RIVA_REST_UNWIRED", message, { retryable: false });
113
+ function httpyzTransport(http, api) {
114
+ return {
115
+ http,
116
+ async call(route, input, { signal }) {
117
+ if (!api)
118
+ throw unwired("This REST transport has no OpenAPI client: build it with httpyzTransport(http, api) to run OpenAPI definitions.");
119
+ const op = api.op;
120
+ const known = api.operations?.[route.operationId];
121
+ if (typeof op !== "function" || !known)
122
+ throw unwired(`riva-rest: the OpenAPI client has no ${route.method.toUpperCase()} ${route.path}.`);
123
+ try {
124
+ const reply = await (route.hasInput ? op.call(api, route.operationId, input ?? {}, { signal }) : op.call(api, route.operationId, { signal }));
125
+ if (reply.status < 200 || reply.status >= 300)
126
+ throw new RivaHttpError2(reply.status, `${route.method.toUpperCase()} ${route.path}: HTTP ${reply.status}`, { cause: reply });
127
+ return reply.data;
128
+ } catch (error) {
129
+ throw toRivaError(error, signal);
130
+ }
131
+ }
132
+ };
133
+ }
134
+
135
+ // src/index.ts
136
+ var rest = { query, mutation };
137
+ export {
138
+ httpyzTransport,
139
+ mutation,
140
+ operationOf,
141
+ provideRest2 as provideRest,
142
+ query,
143
+ rest,
144
+ toRivaError
145
+ };
146
+
147
+ //# debugId=4C7DB21650D38CAF64756E2164756E21
148
+ //# sourceMappingURL=index.js.map