@softistx/riva-graphql 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.
- package/LICENSE +21 -0
- package/README.md +182 -2
- package/dist/bff/index.d.ts +14 -0
- package/dist/bff/index.d.ts.map +1 -0
- package/dist/bff/index.js +13 -0
- package/dist/bff/index.js.map +10 -0
- package/dist/cache/field-key.d.ts +21 -0
- package/dist/cache/field-key.d.ts.map +1 -0
- package/dist/cache/index.d.ts +3 -0
- package/dist/cache/index.d.ts.map +1 -0
- package/dist/cache/index.js +380 -0
- package/dist/cache/index.js.map +17 -0
- package/dist/cache/normalized.d.ts +14 -0
- package/dist/cache/normalized.d.ts.map +1 -0
- package/dist/cache/read.d.ts +11 -0
- package/dist/cache/read.d.ts.map +1 -0
- package/dist/cache/selection.d.ts +33 -0
- package/dist/cache/selection.d.ts.map +1 -0
- package/dist/cache/type-match.d.ts +16 -0
- package/dist/cache/type-match.d.ts.map +1 -0
- package/dist/cache/typename.d.ts +10 -0
- package/dist/cache/typename.d.ts.map +1 -0
- package/dist/cache/values.d.ts +15 -0
- package/dist/cache/values.d.ts.map +1 -0
- package/dist/cache/write.d.ts +18 -0
- package/dist/cache/write.d.ts.map +1 -0
- package/dist/chunks/index-etvmjkh7.js +11 -0
- package/dist/chunks/index-etvmjkh7.js.map +10 -0
- package/dist/chunks/index-zpgy1hwx.js +59 -0
- package/dist/chunks/index-zpgy1hwx.js.map +11 -0
- package/dist/client-transport.d.ts +10 -0
- package/dist/client-transport.d.ts.map +1 -0
- package/dist/codegen/index.d.ts +34 -0
- package/dist/codegen/index.d.ts.map +1 -0
- package/dist/codegen/index.js +44 -0
- package/dist/codegen/index.js.map +10 -0
- package/dist/errors.d.ts +16 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +96 -0
- package/dist/index.js.map +12 -0
- package/dist/infinite/index.d.ts +15 -0
- package/dist/infinite/index.d.ts.map +1 -0
- package/dist/infinite/index.js +26 -0
- package/dist/infinite/index.js.map +10 -0
- package/dist/operation.d.ts +24 -0
- package/dist/operation.d.ts.map +1 -0
- package/dist/query.d.ts +40 -0
- package/dist/query.d.ts.map +1 -0
- package/dist/run.d.ts +5 -0
- package/dist/run.d.ts.map +1 -0
- package/dist/server/index.d.ts +20 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +47 -0
- package/dist/server/index.js.map +10 -0
- package/dist/transport.d.ts +17 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/types.d.ts +6 -0
- package/dist/types.d.ts.map +1 -0
- package/docs/README.md +22 -0
- package/docs/guide/bff.md +54 -0
- package/docs/guide/cache.md +47 -0
- package/docs/guide/codegen.md +67 -0
- package/docs/guide/documents.md +49 -0
- package/docs/guide/errors.md +42 -0
- package/docs/guide/infinite.md +48 -0
- package/docs/guide/mutations.md +38 -0
- package/docs/guide/queries.md +42 -0
- package/docs/guide/transport.md +71 -0
- package/docs/troubleshooting.md +210 -0
- package/package.json +104 -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,183 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @softistx/riva-graphql
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
GraphQL for [riva](https://github.com/softistx/riva/blob/develop/packages/riva/README.md) over [`@softistx/graphql-client`](https://github.com/softistx/graphql): `query`, `mutation` and `infinite` definitions typed from a `TypedDocumentNode` (variables and data are inferred, never annotated), a per-client transport, errors mapped to riva's, and a codegen helper that builds the allowlist a BFF's `/_data` route executes from the client preset's persisted documents.
|
|
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-graphql @softistx/graphql-client @graphql-typed-document-node/core graphql
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Peers: `@softistx/riva` and `@softistx/graphql-client`. `graphql` and `@graphql-typed-document-node/core` are optional: `graphql` is needed by `/server` (the allowlist parses the manifest's text) and `/codegen`, and the types of every definition need the second (`@softistx/graphql-client` already brings it). The main, `/infinite`, `/cache` and `/bff` entries import none of them.
|
|
12
|
+
|
|
13
|
+
## Documents
|
|
14
|
+
|
|
15
|
+
Documents are written with the client preset's `graphql()` function, as `SCREAMING_SNAKE_CASE` constants (`PATIENTS_QUERY`). Use `documentMode: 'documentNode'` (the preset's default). Every example below uses these constants. [Guide](./docs/guide/documents.md).
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
// app/patients/graphql.ts
|
|
19
|
+
import { graphql } from '../generated/gql';
|
|
20
|
+
|
|
21
|
+
export const PATIENTS_QUERY = graphql(`
|
|
22
|
+
query Patients($school: ID!, $first: Int, $after: String) {
|
|
23
|
+
patients(school: $school, first: $first, after: $after) {
|
|
24
|
+
__typename
|
|
25
|
+
edges { __typename node { __typename id name } cursor }
|
|
26
|
+
pageInfo { __typename hasNextPage endCursor }
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
`);
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Provide the transport
|
|
33
|
+
|
|
34
|
+
Definitions are stateless; the transport lives on the `RivaClient` that runs them. Give each client one, when you create it.
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { createGraphQLClient } from '@softistx/graphql-client';
|
|
38
|
+
import { createRivaClient } from '@softistx/riva';
|
|
39
|
+
import { graphqlClientTransport, provideGraphQL } from '@softistx/riva-graphql';
|
|
40
|
+
|
|
41
|
+
const gql = createGraphQLClient({ url: 'https://api.example.com/graphql' });
|
|
42
|
+
|
|
43
|
+
export const client = createRivaClient();
|
|
44
|
+
provideGraphQL(client, graphqlClientTransport(gql));
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
On the server, build both inside the request handler. A definition that runs on a client with no transport throws a `RivaScopeError` naming `provideGraphQL`. Any object with `execute(operation, variables, { signal })` is a transport. [Guide](./docs/guide/transport.md).
|
|
48
|
+
|
|
49
|
+
## Queries
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import { query } from '@softistx/riva-graphql';
|
|
53
|
+
import { PATIENTS_QUERY } from './graphql';
|
|
54
|
+
|
|
55
|
+
export const patients = query(PATIENTS_QUERY, { staleTime: '30s' });
|
|
56
|
+
|
|
57
|
+
await patients.ensure(client, { school: 'north' }); // variables typed from the document
|
|
58
|
+
const state = client.get(patients, { school: 'north' }); // state.data is the document's data
|
|
59
|
+
patients.invalidate(client, { school: 'north' });
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Options: the core's (`staleTime`, `gcTime`, `retry`, `refetchEvery`, …) plus `id` and `cache`. **Ids must be unique.** [Guide](./docs/guide/queries.md).
|
|
63
|
+
|
|
64
|
+
## Mutations
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import { mutation } from '@softistx/riva-graphql';
|
|
68
|
+
import { RENAME_PATIENT_MUTATION } from './graphql';
|
|
69
|
+
|
|
70
|
+
export const renamePatient = mutation(RENAME_PATIENT_MUTATION, {
|
|
71
|
+
invalidates: [patients], // observed lists refetch once it succeeded
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
await renamePatient.run(client, { id: '1', name: 'Ana' }); // rejects after the rollback
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Options: `optimistic`, `updates`, `invalidates`, `retry`, `cache`, typed from the document. [Guide](./docs/guide/mutations.md).
|
|
78
|
+
|
|
79
|
+
## Infinite lists
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { infinite } from '@softistx/riva-graphql/infinite';
|
|
83
|
+
import { PATIENTS_QUERY } from './graphql';
|
|
84
|
+
|
|
85
|
+
export const patientsFeed = infinite(PATIENTS_QUERY, {
|
|
86
|
+
connection: (data) => data.patients, // { edges, pageInfo }
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
await patientsFeed.ensure(client, { school: 'north' });
|
|
90
|
+
await patientsFeed.fetchNext(client, { school: 'north' });
|
|
91
|
+
const { data, hasNext } = client.get(patientsFeed, { school: 'north' });
|
|
92
|
+
data?.nodes; // the flattened nodes, typed from the document
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Name the cursor variables with `cursor: { after: 'afterCursor' }` when the document calls them otherwise. [Guide](./docs/guide/infinite.md).
|
|
96
|
+
|
|
97
|
+
## Normalized cache
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { mutation, query } from '@softistx/riva-graphql';
|
|
101
|
+
import { normalized } from '@softistx/riva-graphql/cache';
|
|
102
|
+
import { PATIENT_QUERY, PATIENTS_QUERY, RENAME_PATIENT_MUTATION } from './graphql';
|
|
103
|
+
|
|
104
|
+
// PATIENT_QUERY: query Patient($id: ID!) { patient(id: $id) { __typename id name } }
|
|
105
|
+
const cache = normalized({ possibleTypes: { Person: ['Patient', 'Doctor'] } });
|
|
106
|
+
|
|
107
|
+
export const patient = query(PATIENT_QUERY, { cache });
|
|
108
|
+
export const patients = query(PATIENTS_QUERY, { cache });
|
|
109
|
+
export const rename = mutation(RENAME_PATIENT_MUTATION, {
|
|
110
|
+
cache, // the mutation's result updates every entity it returns
|
|
111
|
+
optimistic: (v) => ({ renamePatient: { __typename: 'Patient', id: v.id, name: v.name } }),
|
|
112
|
+
});
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Selections must include `__typename`; a miss is a miss (the data is `undefined` and an observed query refetches). [Guide](./docs/guide/cache.md).
|
|
116
|
+
|
|
117
|
+
## Errors
|
|
118
|
+
|
|
119
|
+
The transport maps `@softistx/graphql-client`'s errors to riva's, so `instanceof` holds and the core's retry policy applies (never retried: a refusal, 4xx; retried: 5xx, 408, 429, the network). An `ApiError` that carries no status is read as 400, so it is not retried:
|
|
120
|
+
|
|
121
|
+
| graphql-client | riva | `code` | retried |
|
|
122
|
+
|---|---|---|---|
|
|
123
|
+
| `ApiError` (the response had `errors`) | `RivaRequestError` | the API's `extensions.code`, untouched (`GRAPHQL_ERROR` when it sent none) | 5xx, 408, 429 |
|
|
124
|
+
| `ApiStatusError` | `RivaHttpError` | `HTTP_<status>` | 5xx, 408, 429 |
|
|
125
|
+
| `ApiUnavailableError` (unreachable, timeout) | `RivaNetworkError` | `RIVA_NETWORK` | yes |
|
|
126
|
+
| `ApiUnavailableError` (no data, no errors) | `RivaRequestError` | `RIVA_INVALID_RESPONSE` | no |
|
|
127
|
+
| the call's abort | `RivaAbortError` | `RIVA_ABORT` | never |
|
|
128
|
+
|
|
129
|
+
The original error is the `cause`. A result missing a selected field, or a non-JSON value, throws `RIVA_CACHE`. [Guide](./docs/guide/errors.md).
|
|
130
|
+
|
|
131
|
+
## Allowlist codegen
|
|
132
|
+
|
|
133
|
+
A BFF's `/_data` route executes only documents it knows by id. The client preset (`@graphql-codegen/client-preset`, run by `@graphql-codegen/cli`) with `persistedDocuments: true` writes `persisted-documents.json`, `{ [hash]: text }`, and puts the same hash on each document as `__meta__.hash`, the id a definition sends. `@softistx/riva-graphql/codegen` turns that file into the manifest: one entry per query and mutation, `{ id, name, kind, document }`, keyed by the preset's hash **as it is** (never recomputed, so an id matches by construction) and sorted, so the same documents give the same bytes.
|
|
134
|
+
|
|
135
|
+
Wire it from codegen's `afterAllFileWrite` hook with `writeAllowlist(persisted, out)`; `buildAllowlist(persisted, config?)` is the same step without the files. [Guide](./docs/guide/codegen.md).
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
import { writeAllowlist } from '@softistx/riva-graphql/codegen';
|
|
139
|
+
|
|
140
|
+
await writeAllowlist('app/generated/persisted-documents.json', 'app/generated/allowlist.json');
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## BFF mode
|
|
144
|
+
|
|
145
|
+
In the browser, `bffTransport` posts `{ id, variables }` to your `dataRoute` (from `@softistx/riva-react-router/server`) and reads `{ data }` back, Dates included. The browser never sends a document: the route runs the manifest's text through the request client, with the session your `setup` gave it.
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
// browser: app/riva.client.ts
|
|
149
|
+
import { bffTransport } from '@softistx/riva-graphql/bff';
|
|
150
|
+
import { provideGraphQL } from '@softistx/riva-graphql';
|
|
151
|
+
|
|
152
|
+
provideGraphQL(client, bffTransport({ url: '/_data' }));
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
// server: app/routes/_data.ts (a route with an action and a loader)
|
|
157
|
+
import { dataRoute } from '@softistx/riva-react-router/server';
|
|
158
|
+
import { allowlist } from '@softistx/riva-graphql/server';
|
|
159
|
+
import manifest from '../generated/allowlist.json';
|
|
160
|
+
|
|
161
|
+
const route = dataRoute({
|
|
162
|
+
sources: [allowlist(manifest)],
|
|
163
|
+
});
|
|
164
|
+
export const action = route.action;
|
|
165
|
+
export const loader = route.loader;
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`bffTransport({ url?, fetch?, headers? })` defaults to `/_data`. Keep `/bff` and `/server` out of each other's bundle. [Guide](./docs/guide/bff.md).
|
|
169
|
+
|
|
170
|
+
## Entry points
|
|
171
|
+
|
|
172
|
+
| Import | Holds | Notes |
|
|
173
|
+
|---|---|---|
|
|
174
|
+
| `@softistx/riva-graphql` | `query`, `mutation`, `provideGraphQL`, `graphqlClientTransport`, `toRivaError`, `operationOf` | Imports `@softistx/riva` only; no optional peer. |
|
|
175
|
+
| `@softistx/riva-graphql/infinite` | `infinite` | Imports `@softistx/riva/infinite`. |
|
|
176
|
+
| `@softistx/riva-graphql/cache` | `normalized` | Imports `@softistx/riva/entities`; no `graphql` value import. |
|
|
177
|
+
| `@softistx/riva-graphql/bff` | `bffTransport` | Browser; imports `@softistx/riva/ssr` only. |
|
|
178
|
+
| `@softistx/riva-graphql/server` | `allowlist` | Server only; needs `graphql`. |
|
|
179
|
+
| `@softistx/riva-graphql/codegen` | `buildAllowlist`, `writeAllowlist` | Node and codegen only; needs `graphql`. |
|
|
180
|
+
|
|
181
|
+
Exported types: `GraphQLTransport`, `Operation`, `OperationKind`, `VarsOf` and `GraphQLQueryOptions`, `GraphQLMutationOptions`, `OperationCache` (main entry); `NormalizedOptions`, `PossibleTypes` (`/cache`); `GraphQLInfiniteOptions` (`/infinite`); `AllowlistConfig`, `AllowlistEntry`, `AllowlistManifest` (`/codegen`); `BffTransportOptions` (`/bff`); `AllowlistInput`, `DataOperation`, `DataSource` (`/server`).
|
|
182
|
+
|
|
183
|
+
riva + riva-graphql stays under 8 kB gzipped, and with the entities and the cache under 11 kB (checked by the repo's size budget), `@softistx/graphql-client` and `graphql` not counted.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type BffTransportOptions } from '@softistx/riva/data';
|
|
2
|
+
import type { GraphQLTransport } from '../transport';
|
|
3
|
+
export type { BffTransportOptions };
|
|
4
|
+
/**
|
|
5
|
+
* The browser's transport: posts `{ id, variables }` to a `dataRoute` and
|
|
6
|
+
* reads `{ data }` back, Dates included. The route's refusals and the API's
|
|
7
|
+
* errors come back as `RivaRequestError` with the route's `code` and `status`
|
|
8
|
+
* (retryable for 5xx, 408 and 429); a failed fetch is a `RivaNetworkError`, an
|
|
9
|
+
* abort a `RivaAbortError`, a body that is not the route's JSON
|
|
10
|
+
* `RIVA_INVALID_RESPONSE` (see `postData` in `@softistx/riva/data`). Cookies
|
|
11
|
+
* of the same origin go with the call.
|
|
12
|
+
*/
|
|
13
|
+
export declare function bffTransport(opts?: BffTransportOptions): GraphQLTransport;
|
|
14
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/bff/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,mBAAmB,EAAY,MAAM,qBAAqB,CAAC;AACzE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAErD,YAAY,EAAE,mBAAmB,EAAE,CAAC;AAEpC;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAAC,IAAI,GAAE,mBAAwB,GAAG,gBAAgB,CAK7E"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// src/bff/index.ts
|
|
2
|
+
import { postData } from "@softistx/riva/data";
|
|
3
|
+
function bffTransport(opts = {}) {
|
|
4
|
+
return {
|
|
5
|
+
execute: (operation, variables, { signal }) => postData(opts, operation.id, variables, signal)
|
|
6
|
+
};
|
|
7
|
+
}
|
|
8
|
+
export {
|
|
9
|
+
bffTransport
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
//# debugId=08654F23CE740DEF64756E2164756E21
|
|
13
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/bff/index.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { type BffTransportOptions, postData } from '@softistx/riva/data';\nimport type { GraphQLTransport } from '../transport';\n\nexport type { BffTransportOptions };\n\n/**\n * The browser's transport: posts `{ id, variables }` to a `dataRoute` and\n * reads `{ data }` back, Dates included. The route's refusals and the API's\n * errors come back as `RivaRequestError` with the route's `code` and `status`\n * (retryable for 5xx, 408 and 429); a failed fetch is a `RivaNetworkError`, an\n * abort a `RivaAbortError`, a body that is not the route's JSON\n * `RIVA_INVALID_RESPONSE` (see `postData` in `@softistx/riva/data`). Cookies\n * of the same origin go with the call.\n */\nexport function bffTransport(opts: BffTransportOptions = {}): GraphQLTransport {\n\treturn {\n\t\texecute: (operation, variables, { signal }) =>\n\t\t\tpostData(opts, operation.id, variables, signal) as never,\n\t};\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": ";AAAA;AAcO,SAAS,YAAY,CAAC,OAA4B,CAAC,GAAqB;AAAA,EAC9E,OAAO;AAAA,IACN,SAAS,CAAC,WAAW,aAAa,aACjC,SAAS,MAAM,UAAU,IAAI,WAAW,MAAM;AAAA,EAChD;AAAA;",
|
|
8
|
+
"debugId": "08654F23CE740DEF64756E2164756E21",
|
|
9
|
+
"names": []
|
|
10
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { FieldNode, ValueNode } from 'graphql';
|
|
2
|
+
/** An operation's variables, its defaults applied. */
|
|
3
|
+
export type Variables = Readonly<Record<string, unknown>>;
|
|
4
|
+
/** A GraphQL value as plain JSON, its variables read from `variables` (an unset one is `undefined`). */
|
|
5
|
+
export declare function valueNode(node: ValueNode, variables: Variables): unknown;
|
|
6
|
+
/**
|
|
7
|
+
* Where a field is stored: its name, and its arguments when it has any,
|
|
8
|
+
* keys sorted, so `book(id: 1)` and `book(id: $id)` with `id: 1` share a key:
|
|
9
|
+
* `book({"id":1})`. An alias never reaches the key.
|
|
10
|
+
*/
|
|
11
|
+
export declare function fieldKey(field: FieldNode, variables: Variables): string;
|
|
12
|
+
/** The field's name in a field key: `book` for `book({"id":1})`. */
|
|
13
|
+
export declare function fieldNameOf(key: string): string;
|
|
14
|
+
/**
|
|
15
|
+
* JSON whose object keys are sorted, at every depth, written as
|
|
16
|
+
* `JSON.stringify` writes it otherwise: `toJSON` is honoured (a `Date` is its
|
|
17
|
+
* ISO string) and a value JSON leaves out is left out. So the key is what
|
|
18
|
+
* goes on the wire. Integer-like keys keep the engine's own order.
|
|
19
|
+
*/
|
|
20
|
+
export declare function stableJson(value: unknown): string;
|
|
21
|
+
//# sourceMappingURL=field-key.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"field-key.d.ts","sourceRoot":"","sources":["../../src/cache/field-key.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEpD,sDAAsD;AACtD,MAAM,MAAM,SAAS,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AAE1D,wGAAwG;AACxG,wBAAgB,SAAS,CAAC,IAAI,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,GAAG,OAAO,CAqBxE;AAED;;;;GAIG;AACH,wBAAgB,QAAQ,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,GAAG,MAAM,CAUvE;AAED,oEAAoE;AACpE,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAG/C;AAED;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAUjD"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/cache/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,iBAAiB,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAClE,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC"}
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
// src/cache/normalized.ts
|
|
2
|
+
import { entities } from "@softistx/riva/entities";
|
|
3
|
+
|
|
4
|
+
// src/cache/read.ts
|
|
5
|
+
import { isPlain as isPlain2, isRef } from "@softistx/riva/entities";
|
|
6
|
+
|
|
7
|
+
// src/cache/field-key.ts
|
|
8
|
+
function valueNode(node, variables) {
|
|
9
|
+
switch (node.kind) {
|
|
10
|
+
case "Variable":
|
|
11
|
+
return variables[node.name.value];
|
|
12
|
+
case "IntValue":
|
|
13
|
+
case "FloatValue":
|
|
14
|
+
return Number(node.value);
|
|
15
|
+
case "NullValue":
|
|
16
|
+
return null;
|
|
17
|
+
case "ListValue":
|
|
18
|
+
return node.values.map((v) => valueNode(v, variables));
|
|
19
|
+
case "ObjectValue": {
|
|
20
|
+
const out = {};
|
|
21
|
+
for (const f of node.fields)
|
|
22
|
+
out[f.name.value] = valueNode(f.value, variables);
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
default:
|
|
26
|
+
return node.value;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function fieldKey(field, variables) {
|
|
30
|
+
const name = field.name.value;
|
|
31
|
+
if (!field.arguments?.length)
|
|
32
|
+
return name;
|
|
33
|
+
const args = {};
|
|
34
|
+
for (const argument of field.arguments) {
|
|
35
|
+
const value = valueNode(argument.value, variables);
|
|
36
|
+
if (value !== undefined)
|
|
37
|
+
args[argument.name.value] = value;
|
|
38
|
+
}
|
|
39
|
+
if (Object.keys(args).length === 0)
|
|
40
|
+
return name;
|
|
41
|
+
return `${name}(${stableJson(args)})`;
|
|
42
|
+
}
|
|
43
|
+
function stableJson(value) {
|
|
44
|
+
return JSON.stringify(value, (_, v) => v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : 1)) : v) ?? "null";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// src/cache/selection.ts
|
|
48
|
+
import { RivaError } from "@softistx/riva";
|
|
49
|
+
function cacheDocumentOf(node) {
|
|
50
|
+
let operation;
|
|
51
|
+
const fragments = new Map;
|
|
52
|
+
for (const definition of node.definitions) {
|
|
53
|
+
if (definition.kind === "OperationDefinition")
|
|
54
|
+
operation ??= definition;
|
|
55
|
+
else if (definition.kind === "FragmentDefinition")
|
|
56
|
+
fragments.set(definition.name.value, definition);
|
|
57
|
+
}
|
|
58
|
+
if (!operation)
|
|
59
|
+
throw new RivaError("RIVA_DEFINITION", "riva-graphql: the document holds no operation; query it with one named operation.");
|
|
60
|
+
return { operation, fragments };
|
|
61
|
+
}
|
|
62
|
+
function variablesOf(operation, given) {
|
|
63
|
+
const variables = {
|
|
64
|
+
...given
|
|
65
|
+
};
|
|
66
|
+
for (const definition of operation.variableDefinitions ?? []) {
|
|
67
|
+
const name = definition.variable.name.value;
|
|
68
|
+
if (variables[name] === undefined && definition.defaultValue)
|
|
69
|
+
variables[name] = valueNode(definition.defaultValue, {});
|
|
70
|
+
}
|
|
71
|
+
return variables;
|
|
72
|
+
}
|
|
73
|
+
function collectFields(sets, typename, walk, undecidedApply) {
|
|
74
|
+
const collected = { fields: new Map, undecided: [] };
|
|
75
|
+
const seen = new Set;
|
|
76
|
+
const visit = (set) => {
|
|
77
|
+
for (const selection of set.selections) {
|
|
78
|
+
if (!included(selection, walk.variables))
|
|
79
|
+
continue;
|
|
80
|
+
if (selection.kind === "Field") {
|
|
81
|
+
const key = selection.alias?.value ?? selection.name.value;
|
|
82
|
+
const group = collected.fields.get(key);
|
|
83
|
+
if (group)
|
|
84
|
+
group.push(selection);
|
|
85
|
+
else
|
|
86
|
+
collected.fields.set(key, [selection]);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
const fragment = fragmentOf(selection, walk, seen);
|
|
90
|
+
if (!fragment)
|
|
91
|
+
continue;
|
|
92
|
+
const match = walk.matches(fragment.condition, typename);
|
|
93
|
+
if (match || match === undefined && undecidedApply)
|
|
94
|
+
visit(fragment.set);
|
|
95
|
+
else if (match === undefined)
|
|
96
|
+
collected.undecided.push(fragment.set);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
for (const set of sets)
|
|
100
|
+
visit(set);
|
|
101
|
+
return collected;
|
|
102
|
+
}
|
|
103
|
+
function subSelections(fields) {
|
|
104
|
+
return fields.flatMap((field) => field.selectionSet ? [field.selectionSet] : []);
|
|
105
|
+
}
|
|
106
|
+
function fragmentOf(selection, walk, seen) {
|
|
107
|
+
if (selection.kind === "InlineFragment")
|
|
108
|
+
return {
|
|
109
|
+
condition: selection.typeCondition?.name.value,
|
|
110
|
+
set: selection.selectionSet
|
|
111
|
+
};
|
|
112
|
+
const name = selection.name.value;
|
|
113
|
+
if (seen.has(name))
|
|
114
|
+
return;
|
|
115
|
+
seen.add(name);
|
|
116
|
+
const definition = walk.document.fragments.get(name);
|
|
117
|
+
if (!definition)
|
|
118
|
+
throw new RivaError("RIVA_DEFINITION", `riva-graphql: the document uses the fragment ${name} but does not define it; include its definition in the document.`);
|
|
119
|
+
return {
|
|
120
|
+
condition: definition.typeCondition.name.value,
|
|
121
|
+
set: definition.selectionSet
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
function included(selection, variables) {
|
|
125
|
+
for (const directive of selection.directives ?? []) {
|
|
126
|
+
const name = directive.name.value;
|
|
127
|
+
if (name !== "skip" && name !== "include")
|
|
128
|
+
continue;
|
|
129
|
+
const argument = directive.arguments?.find((a) => a.name.value === "if");
|
|
130
|
+
const value = argument ? valueNode(argument.value, variables) : undefined;
|
|
131
|
+
if (name === "skip" && value === true)
|
|
132
|
+
return false;
|
|
133
|
+
if (name === "include" && value !== true)
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// src/cache/values.ts
|
|
140
|
+
import { RivaError as RivaError2 } from "@softistx/riva";
|
|
141
|
+
import { isPlain } from "@softistx/riva/entities";
|
|
142
|
+
function assertJson(value, field, seen = new WeakSet) {
|
|
143
|
+
const type = typeof value;
|
|
144
|
+
if (value === null || type === "string" || type === "boolean")
|
|
145
|
+
return;
|
|
146
|
+
if (type === "number" && Number.isFinite(value))
|
|
147
|
+
return;
|
|
148
|
+
const list = Array.isArray(value);
|
|
149
|
+
const obj = value;
|
|
150
|
+
if (type === "object" && (list || isPlain(value)) && !seen.has(value)) {
|
|
151
|
+
seen.add(value);
|
|
152
|
+
for (const item of list ? value : Object.values(value))
|
|
153
|
+
assertJson(item, field, seen);
|
|
154
|
+
seen.delete(value);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
throw new RivaError2("RIVA_CACHE", `The GraphQL cache holds JSON: field ${field} holds ${type === "object" ? seen.has(obj) ? "a cycle" : obj.constructor.name : type === "number" ? value : type}.`);
|
|
158
|
+
}
|
|
159
|
+
function mergeValues(a, b) {
|
|
160
|
+
if (isPlain(a) && isPlain(b)) {
|
|
161
|
+
const out = { ...a };
|
|
162
|
+
for (const k of Object.keys(b))
|
|
163
|
+
out[k] = mergeValues(a[k], b[k]);
|
|
164
|
+
return out;
|
|
165
|
+
}
|
|
166
|
+
if (Array.isArray(a) && Array.isArray(b) && a.length === b.length)
|
|
167
|
+
return a.map((x, i) => mergeValues(x, b[i]));
|
|
168
|
+
return b;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// src/cache/read.ts
|
|
172
|
+
var missing = Symbol("missing");
|
|
173
|
+
function readResult(walk, store, root) {
|
|
174
|
+
const reader = { ...walk, variables: root.vars, store };
|
|
175
|
+
const data = readObject(reader, root.data, [walk.document.operation.selectionSet], true);
|
|
176
|
+
return data === missing ? undefined : data;
|
|
177
|
+
}
|
|
178
|
+
function readObject(reader, source, sets, root = false) {
|
|
179
|
+
const typename = source["__typename"];
|
|
180
|
+
const { fields, undecided } = collectFields(sets, typeof typename === "string" ? typename : undefined, root ? { ...reader, matches: () => true } : reader, false);
|
|
181
|
+
const result = {};
|
|
182
|
+
for (const [responseKey, nodes] of fields) {
|
|
183
|
+
const key = fieldKey(nodes[0], reader.variables);
|
|
184
|
+
if (!Object.hasOwn(source, key))
|
|
185
|
+
return missing;
|
|
186
|
+
const value = readValue(reader, source[key], subSelections(nodes));
|
|
187
|
+
if (value === missing)
|
|
188
|
+
return missing;
|
|
189
|
+
result[responseKey] = value;
|
|
190
|
+
}
|
|
191
|
+
let out = result;
|
|
192
|
+
for (const set of undecided) {
|
|
193
|
+
const extra = readObject(reader, source, [set]);
|
|
194
|
+
if (extra !== missing)
|
|
195
|
+
out = mergeValues(out, extra);
|
|
196
|
+
}
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
function readValue(reader, value, sets) {
|
|
200
|
+
if (value === null || typeof value !== "object")
|
|
201
|
+
return value;
|
|
202
|
+
if (sets.length === 0)
|
|
203
|
+
return value;
|
|
204
|
+
if (Array.isArray(value)) {
|
|
205
|
+
const items = value.map((item) => readValue(reader, item, sets));
|
|
206
|
+
return items.includes(missing) ? missing : items;
|
|
207
|
+
}
|
|
208
|
+
if (isRef(value)) {
|
|
209
|
+
const target = reader.store.fields(value.__ref);
|
|
210
|
+
return target ? readObject(reader, target, sets) : missing;
|
|
211
|
+
}
|
|
212
|
+
return isPlain2(value) ? readObject(reader, value, sets) : value;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// src/cache/type-match.ts
|
|
216
|
+
function typeMatcher(possibleTypes = {}) {
|
|
217
|
+
const members = closure(possibleTypes);
|
|
218
|
+
const known = members.size > 0;
|
|
219
|
+
return (condition, typename) => {
|
|
220
|
+
if (condition === undefined || condition === typename)
|
|
221
|
+
return true;
|
|
222
|
+
if (typename === undefined)
|
|
223
|
+
return;
|
|
224
|
+
const types = members.get(condition);
|
|
225
|
+
if (types)
|
|
226
|
+
return types.has(typename);
|
|
227
|
+
return known ? false : undefined;
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
function closure(possibleTypes) {
|
|
231
|
+
const members = new Map;
|
|
232
|
+
const expand = (type, into, seen) => {
|
|
233
|
+
if (seen.has(type))
|
|
234
|
+
return;
|
|
235
|
+
seen.add(type);
|
|
236
|
+
for (const member of possibleTypes[type] ?? []) {
|
|
237
|
+
into.add(member);
|
|
238
|
+
if (Object.hasOwn(possibleTypes, member))
|
|
239
|
+
expand(member, into, seen);
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
for (const type of Object.keys(possibleTypes)) {
|
|
243
|
+
const into = new Set;
|
|
244
|
+
expand(type, into, new Set);
|
|
245
|
+
members.set(type, into);
|
|
246
|
+
}
|
|
247
|
+
return members;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// src/cache/typename.ts
|
|
251
|
+
import { RivaError as RivaError3 } from "@softistx/riva";
|
|
252
|
+
var missing2 = (field) => `riva-graphql: the field "${field}" selects no __typename, which the cache needs to identify objects: add the client preset's addTypenameSelectionDocumentTransform to its documentTransforms.`;
|
|
253
|
+
function assertTypename(node) {
|
|
254
|
+
const fragments = new Map;
|
|
255
|
+
for (const d of node.definitions)
|
|
256
|
+
if (d.kind === "FragmentDefinition")
|
|
257
|
+
fragments.set(d.name.value, d);
|
|
258
|
+
const has = (set) => set.selections.some((s) => s.kind === "Field" ? s.name.value === "__typename" : s.kind === "InlineFragment" && !s.typeCondition && has(s.selectionSet));
|
|
259
|
+
const check = (set, seen) => {
|
|
260
|
+
for (const s of set.selections) {
|
|
261
|
+
if (s.kind === "Field") {
|
|
262
|
+
if (s.selectionSet && !has(s.selectionSet))
|
|
263
|
+
throw new RivaError3("RIVA_DEFINITION", missing2(s.name.value));
|
|
264
|
+
if (s.selectionSet)
|
|
265
|
+
check(s.selectionSet, seen);
|
|
266
|
+
} else if (s.kind === "InlineFragment")
|
|
267
|
+
check(s.selectionSet, seen);
|
|
268
|
+
else {
|
|
269
|
+
const f = fragments.get(s.name.value);
|
|
270
|
+
if (f && !seen.has(f.name.value)) {
|
|
271
|
+
seen.add(f.name.value);
|
|
272
|
+
check(f.selectionSet, seen);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
for (const d of node.definitions)
|
|
278
|
+
if (d.kind === "OperationDefinition")
|
|
279
|
+
check(d.selectionSet, new Set);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// src/cache/write.ts
|
|
283
|
+
import { RivaError as RivaError4 } from "@softistx/riva";
|
|
284
|
+
import { isPlain as isPlain3, isRef as isRef2 } from "@softistx/riva/entities";
|
|
285
|
+
function writeResult(walk, store, data) {
|
|
286
|
+
if (!isPlain3(data))
|
|
287
|
+
throw new RivaError4("RIVA_CACHE", "The GraphQL cache stores an operation's data: an object.");
|
|
288
|
+
const writer = { ...walk, store, pending: new Map };
|
|
289
|
+
const { operation } = walk.document;
|
|
290
|
+
const { fields } = collectFields([operation.selectionSet], undefined, { ...walk, matches: () => true }, true);
|
|
291
|
+
const entries = writeFields(writer, data, fields, undefined);
|
|
292
|
+
const root = operation.operation === "query" ? { vars: walk.variables, data: entries } : undefined;
|
|
293
|
+
return { root, pending: writer.pending };
|
|
294
|
+
}
|
|
295
|
+
function writeObject(writer, data, sets, existing) {
|
|
296
|
+
const typename = data["__typename"];
|
|
297
|
+
const { fields } = collectFields(sets, typeof typename === "string" ? typename : undefined, writer, true);
|
|
298
|
+
const ref = writer.store.identify(byName(data, fields));
|
|
299
|
+
if (ref) {
|
|
300
|
+
const held = { ...writer.store.peek(ref), ...writer.pending.get(ref) };
|
|
301
|
+
const entries = writeFields(writer, data, fields, held);
|
|
302
|
+
writer.pending.set(ref, { ...writer.pending.get(ref), ...entries });
|
|
303
|
+
return { __ref: ref };
|
|
304
|
+
}
|
|
305
|
+
const previous = isPlain3(existing) && !isRef2(existing) && existing["__typename"] === typename ? existing : undefined;
|
|
306
|
+
const entries = writeFields(writer, data, fields, previous);
|
|
307
|
+
if (previous && agrees(previous, entries))
|
|
308
|
+
return { ...previous, ...entries };
|
|
309
|
+
return previous ? writeFields(writer, data, fields, undefined) : entries;
|
|
310
|
+
}
|
|
311
|
+
var isNested = (v) => typeof v === "object" && v !== null;
|
|
312
|
+
function agrees(a, b) {
|
|
313
|
+
return Object.keys(b).every((k) => {
|
|
314
|
+
const x = a[k];
|
|
315
|
+
const y = b[k];
|
|
316
|
+
return !Object.hasOwn(a, k) || isNested(x) || isNested(y) || x === y;
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
function writeFields(writer, data, fields, previous) {
|
|
320
|
+
const entries = {};
|
|
321
|
+
for (const [responseKey, nodes] of fields) {
|
|
322
|
+
if (!Object.hasOwn(data, responseKey))
|
|
323
|
+
continue;
|
|
324
|
+
const key = fieldKey(nodes[0], writer.variables);
|
|
325
|
+
entries[key] = writeValue(writer, data[responseKey], key, subSelections(nodes), Object.hasOwn(entries, key) ? entries[key] : previous?.[key]);
|
|
326
|
+
}
|
|
327
|
+
return entries;
|
|
328
|
+
}
|
|
329
|
+
function writeValue(writer, value, field, sets, existing) {
|
|
330
|
+
if (value === undefined || value === null)
|
|
331
|
+
return null;
|
|
332
|
+
if (sets.length === 0) {
|
|
333
|
+
assertJson(value, field);
|
|
334
|
+
return value;
|
|
335
|
+
}
|
|
336
|
+
if (Array.isArray(value))
|
|
337
|
+
return value.map((item, i) => writeValue(writer, item, field, sets, Array.isArray(existing) && existing.length === value.length ? existing[i] : undefined));
|
|
338
|
+
if (!isPlain3(value)) {
|
|
339
|
+
assertJson(value, field);
|
|
340
|
+
return value;
|
|
341
|
+
}
|
|
342
|
+
return writeObject(writer, value, sets, existing);
|
|
343
|
+
}
|
|
344
|
+
function byName(data, fields) {
|
|
345
|
+
const named = {};
|
|
346
|
+
for (const [responseKey, [node]] of fields) {
|
|
347
|
+
if (!node || node.arguments?.length || !Object.hasOwn(data, responseKey))
|
|
348
|
+
continue;
|
|
349
|
+
const name = node.name.value;
|
|
350
|
+
if (!Object.hasOwn(named, name))
|
|
351
|
+
named[name] = data[responseKey];
|
|
352
|
+
}
|
|
353
|
+
return named;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// src/cache/normalized.ts
|
|
357
|
+
function normalized(opts = {}) {
|
|
358
|
+
const matches = typeMatcher(opts.possibleTypes);
|
|
359
|
+
return {
|
|
360
|
+
forOperation(op) {
|
|
361
|
+
assertTypename(op.document);
|
|
362
|
+
const document = cacheDocumentOf(op.document);
|
|
363
|
+
const walk = (variables) => ({
|
|
364
|
+
document,
|
|
365
|
+
matches,
|
|
366
|
+
variables
|
|
367
|
+
});
|
|
368
|
+
return entities(opts, {
|
|
369
|
+
normalize: (store, data, vars) => writeResult(walk(variablesOf(document.operation, vars)), store, data),
|
|
370
|
+
denormalize: (store, root) => root === undefined ? undefined : readResult(walk({}), store, root)
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
export {
|
|
376
|
+
normalized
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
//# debugId=D7F15F600B618A3764756E2164756E21
|
|
380
|
+
//# sourceMappingURL=index.js.map
|