ramdb2-client 0.0.0-stage → 2.0.0-alpha.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 ADDED
@@ -0,0 +1,5 @@
1
+ # ramdb2-client
2
+
3
+ ## 2.0.0-alpha.1
4
+
5
+ No changes in this release.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Emmanuel Leparquier
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,290 @@
1
- # Temporary Holding Version
1
+ # ramdb2-client
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
+ **The objects of a ramdb2 database, ready to use in a web site.**
4
+
5
+ ramdb2-client talks to a [ramdb2-server](https://www.npmjs.com/package/ramdb2-server). Its classes are generated
6
+ from the schema of the server by `ramdb2-cli client`: a page gets real objects, whole, with their relations and their
7
+ computed fields, and edits them through drafts that check the rules before sending, and never overwrite the change
8
+ of another user without telling.
9
+
10
+ ```js
11
+ import { configure } from 'ramdb2-client'
12
+ import { classes, Project } from './model/index.js'
13
+
14
+ configure({ url: '/graphql', classes })
15
+
16
+ const { items, total } = await Project.list({
17
+ include: ['tasks'],
18
+ query: { where: { status: 'OPEN' }, orderBy: { name: 'asc' }, limit: 20 },
19
+ })
20
+ items[0].totalHours // a computed field, calculated by the server
21
+ items[0].tasks[0].name // a relation, loaded in the same request
22
+
23
+ await items[0].update({ name: 'Planning v3' }) // sends only this field, with its expected value
24
+ ```
25
+
26
+ It does not depend on Vue: it works in any page, in Node and in tests. [ramdb2-vue](https://www.npmjs.com/package/ramdb2-vue) builds a whole site
27
+ on it.
28
+
29
+ ## Contents
30
+
31
+ 1. [Getting started](#1-getting-started)
32
+ 2. [The classes](#2-the-classes)
33
+ 3. [Reading](#3-reading)
34
+ 4. [Changing: drafts](#4-changing-drafts)
35
+ 5. [Errors](#5-errors)
36
+ 6. [Authentication](#6-authentication)
37
+ 7. [Your own operations](#7-your-own-operations)
38
+ 8. [Describing the fields](#8-describing-the-fields)
39
+ 9. [Configuration](#9-configuration)
40
+ 10. [Testing](#10-testing)
41
+
42
+ ## 1. Getting started
43
+
44
+ Generate the classes from the schema of the server, in the client application:
45
+
46
+ ```sh
47
+ ramdb2-cli client --schema ../my_server/schema/preTypeDefs.graphql --dest src/model
48
+ ```
49
+
50
+ | File | Content | Rewritten |
51
+ |---|---|---|
52
+ | `generated/<type>.js` | `XxxBase`: the fields, relations, rules and getters of the type | at each generation |
53
+ | `extended/<type>.js` | `Xxx extends XxxBase`: your code (labels, rules, getters) | never (created when missing) |
54
+ | `index.js` | the classes, and `classes` for `configure` | at each generation |
55
+
56
+ Then configure the client once, at the start of the application:
57
+
58
+ ```js
59
+ import { configure } from 'ramdb2-client'
60
+ import { classes } from './model/index.js'
61
+
62
+ configure({ url: '/graphql', classes })
63
+ ```
64
+
65
+ With Vue, call `configure({ reactive })` with the `reactive` of Vue (ramdb2-vue does it for you): the objects then
66
+ refresh every view that shows them.
67
+
68
+ ## 2. The classes
69
+
70
+ A generated class knows everything the screens need: its fields and foreign keys (`static fields`), its computed and
71
+ `@transient` fields (`computed`, `transient`), its relations (`relations`), its full-text fields (`fullText`), the
72
+ default values of a new object (`defaults`), and the rules of the schema (`generatedRules`: required fields,
73
+ `@pattern`, enums). Fields marked `@private` on the server (a password) are not in the API, so not in the class.
74
+
75
+ The extended class is yours, and the generator never rewrites it:
76
+
77
+ ```js
78
+ // extended/task.js
79
+ import TaskBase from '../generated/task.js'
80
+
81
+ export default class Task extends TaskBase {
82
+ // The labels shown by every table and form of this type; without one, the name of the field
83
+ static labels = { name: 'Name', project: 'Project', hours: 'Hours' }
84
+
85
+ // The labels of the values of an enum
86
+ static valueLabels = { status: { TODO: 'To do', DONE: 'Done' } }
87
+
88
+ // The field that shows an object, e.g. in a list of choices. Default: name, label, title, code or login
89
+ static display = 'name'
90
+
91
+ // The input of a field, when the default one does not fit
92
+ static inputs = { description: 'textarea' }
93
+
94
+ // More rules, run before a save, after the generated ones: (values, obj) => '' or a message
95
+ static rules = {
96
+ hours: [values => values.hours < 0 ? 'hours must be positive' : ''],
97
+ }
98
+
99
+ // Your own getters: never a # private field (it would break the reactive proxy of Vue), use _ for internal values
100
+ get isLong() { return this.hours > 8 }
101
+ }
102
+ ```
103
+
104
+ ## 3. Reading
105
+
106
+ ### `Type.list({ query, include, name, signal })`
107
+
108
+ A query of ramdb2, in the MongoDB syntax (section 10 of the spec of ramdb2), always sent in variables:
109
+
110
+ ```js
111
+ const { items, total, aggregates, groups } = await Task.list({
112
+ query: {
113
+ where: { idProject: 3, hours: { $gte: 2 }, $text: { $search: 'design' } },
114
+ orderBy: [{ hours: 'desc' }, { name: 'asc' }],
115
+ limit: 20,
116
+ offset: 40,
117
+ },
118
+ include: ['project'],
119
+ })
120
+ ```
121
+
122
+ - `items`: the objects of the page; `total`: their number before the pagination;
123
+ - `aggregates`: `{ sum: { $sum: 'hours' }, count: { $count: {} } }` computed on the whole filter (`limit: 0` gives
124
+ them without any row);
125
+ - `groups`: with `groupBy: ['idProject']`, one entry per group: `[{ key: { idProject: 3 }, sum: 12 }, …]`.
126
+
127
+ ### `Type.byId(id, { include })`, `object.reload({ include })`
128
+
129
+ One object; `NotFoundError` when it does not exist.
130
+
131
+ ### Whole objects, relations on demand
132
+
133
+ An object always comes **whole**: its stored fields, its foreign keys, its computed and `@transient` fields. Its
134
+ **relations** come only when `include` asks for them, in the same request (`'tasks.project'` goes deeper). Reading a
135
+ relation that was not loaded throws a `RelationNotLoadedError`: a getter never sends a request on its own, so there
136
+ is no hidden request per row.
137
+
138
+ A list relation comes whole, without filter or pagination. To filter or paginate the children, query their type
139
+ with `$in` on the ids of the parents.
140
+
141
+ ### One instance per object
142
+
143
+ Two queries that return the same object give the **same instance**, updated with the last values received: every
144
+ screen shows the same values. The instances are held weakly: an object that no screen holds any more is released.
145
+ It is not a cache: every screen asks the server.
146
+
147
+ ## 4. Changing: drafts
148
+
149
+ An instance holds the values of the server: it is **read-only** (`task.name = 'x'` throws). A change goes through a
150
+ **draft**, which a form binds to:
151
+
152
+ ```js
153
+ const draft = Task.newDraft({ idProject: 3 }) // a new object, with the defaults of the schema
154
+ // or: const draft = task.edit() // a stored object
155
+
156
+ draft.values.name = 'Design'
157
+ draft.validate() // the local rules, no request: true when valid, messages in draft.errors
158
+ await draft.check() // the rules of the server (foreign keys, unique indexes…), nothing is changed
159
+ const task = await draft.save()
160
+ ```
161
+
162
+ | Member | |
163
+ |---|---|
164
+ | `values` | the values being edited |
165
+ | `base` | the values read at the start |
166
+ | `changed` | the fields whose value differs from `base` |
167
+ | `errors` | one message per field, `''` when valid |
168
+ | `conflicts` | the fields of the last conflict |
169
+ | `isNew` | not created yet |
170
+ | `set(values)`, `reset()` | set some values; back to `base` |
171
+ | `validate(fields?)`, `check(fields?)`, `save()` | see above; `save()` runs `validate()` first |
172
+
173
+ `task.update({ hours: 4 })` is a shortcut for `task.edit().set({ hours: 4 }).save()`, e.g. an inline edit.
174
+ `task.delete()` deletes the object (the `@onDelete` policies of the server apply) and the identity map forgets it.
175
+
176
+ ### Two users on the same object
177
+
178
+ An update sends **only the changed fields**, with the values read at the start (`expected`). Two users changing
179
+ different fields of an object both keep their change. When another user changed one of the same fields in the
180
+ meantime, the server refuses with `CONFLICT`, and the draft:
181
+
182
+ - reloads the object;
183
+ - puts the value of the other user in each conflicting field, and lists them in `draft.conflicts`;
184
+ - makes the fields the user did not touch follow the server, so that the next save does not undo the other change;
185
+ - throws the `ConflictError`: show the new values, and save again to keep yours.
186
+
187
+ ## 5. Errors
188
+
189
+ The codes of the server become typed errors:
190
+
191
+ | Code | Error | Content |
192
+ |---|---|---|
193
+ | `BAD_USER_INPUT` | `ValidationError` | `fieldErrors`: one message per field |
194
+ | `CONFLICT` | `ConflictError` | `fields`, `current` (the stored values of the server) |
195
+ | `NOT_FOUND` | `NotFoundError` | |
196
+ | `FORBIDDEN` | `ForbiddenError` | |
197
+ | `INTEGRITY` | `IntegrityError` | |
198
+ | `UNAUTHENTICATED` | `UnauthenticatedError` | |
199
+ | HTTP or network failure | `NetworkError` | `status` |
200
+
201
+ All extend `RamdbError` (`code`, `errors`: the raw GraphQL errors, `path`). An aborted request (`signal`) rejects
202
+ with the `AbortError` of `fetch`, untouched. Nothing is ever sent again on its own: a mutation sent twice could be
203
+ applied twice.
204
+
205
+ The messages of the rules are those of ramdb2, in English (`name is required`); ramdb2-vue translates them.
206
+
207
+ ## 6. Authentication
208
+
209
+ On the authentication module of ramdb2-server (`newToken`, `renewToken`, `me`, a Bearer JWT):
210
+
211
+ ```js
212
+ import { isLoggedIn, login, logout, session } from 'ramdb2-client'
213
+
214
+ const user = await login('admin', 'secret12') // newToken, then me
215
+ session().user // the current user, an instance of the User class
216
+ logout() // drops the token and forgets every object
217
+ ```
218
+
219
+ - The token is kept in `localStorage`. The password never is.
220
+ - Its expiry is **measured as a duration from its reception** (`exp − iat`): a wrong clock on the computer of the
221
+ user does not matter. The server alone enforces the session.
222
+ - **Sliding renewal**: with less than a quarter of its duration left, the token is renewed (`renewToken`) before
223
+ the next request. An active user stays logged in.
224
+ - An expired token ends the session: the token is dropped and `auth.onUnauthenticated` is called.
225
+ - A `FORBIDDEN` while logged in asks `me`: when the server does not recognise the token any more (user deleted,
226
+ secret changed), the session ends and an `UnauthenticatedError` is thrown; otherwise it is a real refusal.
227
+ - When another user logs in, the objects of the previous one are forgotten.
228
+
229
+ Also: `loadMe()` (reload the user, e.g. after a reload of the page), `isLoggedIn()`, `renew()`, `token()`,
230
+ `tokenExpiry(token)`.
231
+
232
+ A server without this module: set `auth: { standard: false }`, and the `header` and `prefix` of its token.
233
+
234
+ ## 7. Your own operations
235
+
236
+ `request(document, variables, { name, signal, auth })` sends an operation written in your project, with the token
237
+ of the session:
238
+
239
+ ```js
240
+ const data = await request('query PlanningLoad($id: Int!) { planningLoad(id: $id) }', { id: 3 })
241
+ ```
242
+
243
+ Every operation has a **name**, written in the logs of the server so that a line leads back to its page. The
244
+ standard ones are named by default (`TaskList`, `TaskById`, `TaskCreate`, `TaskUpdate`, `TaskDelete`,
245
+ `TaskDataCheck`); `name` replaces it on a call, and `setOperationPrefix('PlanningPage')` prefixes them for a page:
246
+ `PlanningPage_TaskList`. A GraphQL name holds only letters, digits and `_`.
247
+
248
+ `activity().pending` is the number of requests in progress, e.g. for a loading indicator.
249
+
250
+ ## 8. Describing the fields
251
+
252
+ For a screen that shows or edits any type:
253
+
254
+ | Function | Gives |
255
+ |---|---|
256
+ | `describeField(Type, field)` | `{ name, label, input, stored, required, values, valueLabels, relation, type }`; `input` is `text`, `number`, `boolean`, `enum`, `relation` or the `static inputs` of the class |
257
+ | `labelOf(Type, path)` | the label of a field or of a path (`project.name`); a foreign key takes the label of its relation |
258
+ | `valueLabelOf(Type, field, value)` | the label of a value of an enum |
259
+ | `displayOf(object)`, `displayField(Type)` | the text that shows an object, and its field |
260
+ | `valueAt(object, path)` | the value at a path through loaded relations |
261
+ | `includeFor(Type, columns)` | the relations to include to show some columns |
262
+
263
+ The rule factories `required`, `requiredKey`, `pattern` and `oneOf` give the same messages as ramdb2, and say what
264
+ they check (`rule.required`, `rule.allowed`, `rule.pattern`).
265
+
266
+ ## 9. Configuration
267
+
268
+ `configure(options)` merges its options into the current configuration:
269
+
270
+ | Option | Default | |
271
+ |---|---|---|
272
+ | `url` | `/graphql` | the endpoint of ramdb2-server |
273
+ | `classes` | | the generated classes (`register(...classes)` does the same) |
274
+ | `reactive` | identity | makes the objects and drafts reactive: the `reactive` of Vue |
275
+ | `fetch` | `globalThis.fetch` | for the tests |
276
+ | `storage` | `localStorage` | where the token is kept; `memoryStorage()` in Node |
277
+ | `auth.header`, `auth.prefix` | `authorization`, `Bearer` | the header of the token |
278
+ | `auth.userType` | `User` | the type returned by `me` |
279
+ | `auth.standard` | `true` | the server has the authentication module of ramdb2-server |
280
+ | `auth.onUnauthenticated` | nothing | called when the session is over |
281
+
282
+ ## 10. Testing
283
+
284
+ The tests of this package run with `node --test`: `npm test -w ramdb2-client`.
285
+
286
+ - **Unit tests** give `configure({ fetch })` a function that answers like the server, and `storage: memoryStorage()`.
287
+ - **End-to-end tests** start a real ramdb2-server, created by `ramdb2-cli new` on a SQLite database in memory, and
288
+ generate the client classes with `ramdb2-cli client` (`test/setup.js`, run before the tests).
289
+
290
+ Node 22 or later: `fetch`, `WeakRef` and `--expose-gc` (to test the release of the objects) are built in.
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "ramdb2-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.0.0-alpha.1",
4
+ "description": "Client of ramdb2-server: the objects of the database, ready to use in a web site",
5
+ "type": "module",
6
+ "exports": "./src/index.js",
7
+ "license": "MIT",
8
+ "author": "Emmanuel Leparquier",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://gitlab.com/eleparquier/ramdb2.git",
12
+ "directory": "packages/ramdb2-client"
13
+ },
14
+ "homepage": "https://gitlab.com/eleparquier/ramdb2/-/tree/master/packages/ramdb2-client",
15
+ "files": [
16
+ "src",
17
+ "CHANGELOG.md"
18
+ ],
19
+ "scripts": {
20
+ "pretest": "node test/setup.js",
21
+ "test": "node --test --expose-gc \"test/**/*.test.js\""
22
+ },
23
+ "devDependencies": {
24
+ "@vue/reactivity": "^3.5.44"
25
+ }
26
+ }
package/src/auth.js ADDED
@@ -0,0 +1,215 @@
1
+ import { config, operationName } from './config.js'
2
+ import { ForbiddenError, UnauthenticatedError } from './errors.js'
3
+ import { clearInstances } from './identity.js'
4
+ import { send } from './transport.js'
5
+ import { hydrate, selection } from './hydrate.js'
6
+
7
+ // Authentication (D10), on the module of ramdb2-server (D46): newToken, renewToken and me, a Bearer JWT.
8
+ // The token is kept in localStorage. Its expiry is measured as a duration from its reception (exp - iat), so that
9
+ // a wrong clock on the computer of the user does not matter. The server alone enforces the session: this side only
10
+ // decides when to renew the token and when to ask the user to log in again.
11
+
12
+ const KEY = 'ramdb2.token'
13
+
14
+ /** @type {Promise<void> | null} the renewal in progress, shared by the requests that need it */
15
+ let renewing = null
16
+
17
+ /**
18
+ * The session: the current user, reactive when configure({ reactive }) is called before its first use.
19
+ * @returns {{user: object | null}}
20
+ */
21
+ export function session() {
22
+ config.session ??= config.reactive({ user: null })
23
+ return config.session
24
+ }
25
+
26
+ /**
27
+ * Reads the expiry of a token: `exp` (JWT, seconds) or `expiration` (milliseconds), and `iat` (seconds).
28
+ * @param {string} token
29
+ * @returns {{duration: number | null, expiresAt: number | null}} in milliseconds; null when unknown
30
+ */
31
+ export function tokenExpiry(token) {
32
+ try {
33
+ const payload = JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')))
34
+ const expiresAt = typeof payload.exp === 'number' ? payload.exp * 1000
35
+ : typeof payload.expiration === 'number' ? payload.expiration : null
36
+ const duration = typeof payload.exp === 'number' && typeof payload.iat === 'number' ? (payload.exp - payload.iat) * 1000 : null
37
+ return { duration, expiresAt }
38
+ } catch {
39
+ return { duration: null, expiresAt: null } // not a JWT: the server alone knows its expiry
40
+ }
41
+ }
42
+
43
+ function readRecord() {
44
+ try {
45
+ return JSON.parse(config.storage?.getItem(KEY) ?? 'null')
46
+ } catch {
47
+ return null
48
+ }
49
+ }
50
+
51
+ function writeRecord(record) {
52
+ if (record) config.storage?.setItem(KEY, JSON.stringify(record))
53
+ else config.storage?.removeItem(KEY)
54
+ }
55
+
56
+ /** The token kept, or null. */
57
+ export function token() {
58
+ return readRecord()?.token ?? null
59
+ }
60
+
61
+ /**
62
+ * Keeps a token received from the server, with the moment of its reception.
63
+ * @param {string} value
64
+ * @param {number | null} [userId] the user of the token, to clear the data of another user at the next login
65
+ * @param {number} [receivedAt] the moment of the reception, in milliseconds of the local clock (now; the tests go back in time)
66
+ */
67
+ export function setToken(value, userId = readRecord()?.userId ?? null, receivedAt = Date.now()) {
68
+ writeRecord({ token: value, receivedAt, ...tokenExpiry(value), userId })
69
+ }
70
+
71
+ /**
72
+ * Milliseconds before the token expires: Infinity when its expiry is unknown, 0 or less when expired or absent.
73
+ * @param {number} [now]
74
+ */
75
+ export function remaining(now = Date.now()) {
76
+ const record = readRecord()
77
+ if (!record?.token) return 0
78
+ // A duration counted from the reception does not depend on the clock being right
79
+ if (record.duration !== null && record.duration !== undefined) return record.duration - (now - record.receivedAt)
80
+ if (record.expiresAt !== null && record.expiresAt !== undefined) return record.expiresAt - now
81
+ return Infinity
82
+ }
83
+
84
+ /** True when a token is kept and not expired. */
85
+ export function isLoggedIn() {
86
+ return remaining() > 0
87
+ }
88
+
89
+ /** The headers of an authenticated request. */
90
+ export function authHeaders() {
91
+ const value = token()
92
+ if (!value) return {}
93
+ return { [config.auth.header]: config.auth.prefix ? `${config.auth.prefix} ${value}` : value }
94
+ }
95
+
96
+ // The session is over (token expired or refused): the token is dropped and the application asks the user to log
97
+ // in again. The instances are kept: the screen stays as it is and the user logs in again over it.
98
+ function sessionOver() {
99
+ writeRecord(null)
100
+ session().user = null
101
+ config.auth.onUnauthenticated()
102
+ }
103
+
104
+ /**
105
+ * Logs in with the module of ramdb2-server: newToken, then me. When another user was logged in before, the
106
+ * objects of that user are forgotten.
107
+ * @param {string} login
108
+ * @param {string} password
109
+ * @param {{name?: string}} [options]
110
+ * @returns {Promise<object | null>} the user
111
+ */
112
+ export async function login(login, password, { name } = {}) {
113
+ const data = await send('query NewToken($login: String!, $password: String!) { newToken(login: $login, password: $password) }',
114
+ { login, password }, { name: operationName('NewToken', name) })
115
+ const previous = readRecord()?.userId ?? null
116
+ setToken(data.newToken, previous)
117
+ const raw = await fetchRawMe()
118
+ // Cleared before the user is hydrated, so that the new user is recorded in the identity map
119
+ if (previous !== null && previous !== raw?.id) clearInstances()
120
+ setToken(data.newToken, raw?.id ?? null)
121
+ const user = raw ? hydrateUser(raw) : null
122
+ session().user = user
123
+ return user
124
+ }
125
+
126
+ /** Logs out: drops the token and forgets every object (D10). The JWT is stateless: the server is not called. */
127
+ export function logout() {
128
+ writeRecord(null)
129
+ clearInstances()
130
+ session().user = null
131
+ }
132
+
133
+ /**
134
+ * Loads the current user with `me` and keeps it in session().user.
135
+ * @returns {Promise<object | null>}
136
+ */
137
+ export async function loadMe() {
138
+ const user = await fetchMe()
139
+ session().user = user
140
+ return user
141
+ }
142
+
143
+ async function fetchMe() {
144
+ const raw = await fetchRawMe()
145
+ return raw ? hydrateUser(raw) : null
146
+ }
147
+
148
+ async function fetchRawMe() {
149
+ const userClass = config.classes.get(config.auth.userType)
150
+ const fields = userClass ? selection(userClass) : 'id'
151
+ const data = await send(`query Me { me { ${fields} } }`, {}, { name: operationName('Me'), headers: authHeaders() })
152
+ return data.me ?? null
153
+ }
154
+
155
+ function hydrateUser(raw) {
156
+ const userClass = config.classes.get(config.auth.userType)
157
+ return userClass ? hydrate(userClass, raw) : raw
158
+ }
159
+
160
+ /** Renews the token with renewToken: a new token, a new expiry. Shared by the requests that need it. */
161
+ export function renew() {
162
+ renewing ??= (async () => {
163
+ try {
164
+ const data = await send('query RenewToken { renewToken }', {}, { name: operationName('RenewToken'), headers: authHeaders() })
165
+ setToken(data.renewToken)
166
+ } catch (error) {
167
+ if (error instanceof UnauthenticatedError) sessionOver()
168
+ // Any other failure (network…): the token is kept, the next request tries again
169
+ } finally {
170
+ renewing = null
171
+ }
172
+ })()
173
+ return renewing
174
+ }
175
+
176
+ /**
177
+ * Before each authenticated request: an expired token ends the session, a token near its end is renewed
178
+ * (sliding renewal: less than a quarter of its duration left).
179
+ */
180
+ export async function beforeRequest() {
181
+ if (renewing) await renewing
182
+ const record = readRecord()
183
+ if (!record?.token) return
184
+ const left = remaining()
185
+ if (left <= 0) return sessionOver()
186
+ if (config.auth.standard && record.duration && left < record.duration / 4) await renew()
187
+ }
188
+
189
+ /**
190
+ * After a failed authenticated request: translates the errors that mean the session is over (D10).
191
+ * - UNAUTHENTICATED: the token is dropped and onUnauthenticated is called;
192
+ * - FORBIDDEN while logged in: the server may have stopped recognising the token (user deleted, secret changed…),
193
+ * which it reports as a refusal of the project. `me` tells: null means the session is over.
194
+ * @param {unknown} error
195
+ * @returns {Promise<unknown>} the error to throw
196
+ */
197
+ export async function afterError(error) {
198
+ if (error instanceof UnauthenticatedError) {
199
+ if (token()) sessionOver()
200
+ return error
201
+ }
202
+ if (error instanceof ForbiddenError && config.auth.standard && isLoggedIn()) {
203
+ let user
204
+ try {
205
+ user = await fetchMe()
206
+ } catch {
207
+ return error
208
+ }
209
+ if (user === null) {
210
+ sessionOver()
211
+ return new UnauthenticatedError('The session is over: log in again', { code: 'UNAUTHENTICATED', errors: error.errors })
212
+ }
213
+ }
214
+ return error
215
+ }
package/src/config.js ADDED
@@ -0,0 +1,104 @@
1
+ // The configuration of the client: one server per application, so one configuration per page.
2
+
3
+ const NAME = /^[_A-Za-z][_0-9A-Za-z]*$/
4
+
5
+ /**
6
+ * @typedef {object} AuthOptions
7
+ * @property {string} [header] the header that carries the token. Default: authorization
8
+ * @property {string} [prefix] written before the token. Default: Bearer (the module of ramdb2-server, D46)
9
+ * @property {string} [userType] the GraphQL type returned by `me`. Default: User
10
+ * @property {boolean} [standard] the server has the module of ramdb2-server (newToken, renewToken, me). Default: true
11
+ * @property {() => void} [onUnauthenticated] called when the session is over: no token, expired or refused (D10)
12
+ *
13
+ * @typedef {object} Options
14
+ * @property {string} [url] the GraphQL endpoint of ramdb2-server
15
+ * @property {typeof fetch} [fetch] the fetch function, for the tests. Default: globalThis.fetch
16
+ * @property {<T extends object>(obj: T) => T} [reactive] makes an object reactive, e.g. reactive of Vue (D8)
17
+ * @property {Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> | null} [storage] where the token is kept. Default: localStorage
18
+ * @property {Function[]} [classes] the client classes generated by ramdb2-cli
19
+ * @property {AuthOptions} [auth]
20
+ */
21
+
22
+ function defaults() {
23
+ return {
24
+ url: '/graphql',
25
+ fetch: (...args) => globalThis.fetch(...args),
26
+ reactive: obj => obj,
27
+ storage: globalThis.localStorage ?? memoryStorage(),
28
+ classes: new Map(),
29
+ operationPrefix: '',
30
+ auth: { header: 'authorization', prefix: 'Bearer', userType: 'User', standard: true, onUnauthenticated: () => {} },
31
+ }
32
+ }
33
+
34
+ /** The current configuration. Internal: use configure(). */
35
+ export const config = defaults()
36
+
37
+ /**
38
+ * Configures the client. Each call merges its options into the current configuration.
39
+ * @param {Options} options
40
+ */
41
+ export function configure(options) {
42
+ const { classes, auth, ...rest } = options
43
+ Object.assign(config, rest)
44
+ if (auth) Object.assign(config.auth, auth)
45
+ if (classes) register(...classes)
46
+ }
47
+
48
+ /**
49
+ * Registers client classes: their relations find their target class by its GraphQL type name.
50
+ * @param {...Function} classes
51
+ */
52
+ export function register(...classes) {
53
+ for (const cls of classes) {
54
+ if (typeof cls.typeName !== 'string') throw new TypeError(`${cls.name} is not a client class: static typeName missing`)
55
+ config.classes.set(cls.typeName, cls)
56
+ }
57
+ }
58
+
59
+ /**
60
+ * The class of a GraphQL type.
61
+ * @param {string} typeName
62
+ */
63
+ export function classOf(typeName) {
64
+ const cls = config.classes.get(typeName)
65
+ if (!cls) throw new Error(`No client class registered for the type ${typeName}: pass it to configure({ classes })`)
66
+ return cls
67
+ }
68
+
69
+ /**
70
+ * Sets the prefix of the default operation names, e.g. the page: PlanningPage_TaskList (D9).
71
+ * It is written in the logs of the server, to find the page that sent a request.
72
+ * @param {string} prefix a GraphQL name, or '' for none
73
+ */
74
+ export function setOperationPrefix(prefix) {
75
+ if (prefix !== '' && !NAME.test(prefix)) throw new Error(`Invalid operation prefix "${prefix}": letters, digits and _ only`)
76
+ config.operationPrefix = prefix
77
+ }
78
+
79
+ /**
80
+ * The name of an operation: the name given by the caller, or the default name with the prefix of the page.
81
+ * @param {string} defaultName e.g. TaskList
82
+ * @param {string} [name]
83
+ */
84
+ export function operationName(defaultName, name) {
85
+ const result = name ?? (config.operationPrefix ? `${config.operationPrefix}_${defaultName}` : defaultName)
86
+ if (!NAME.test(result)) throw new Error(`Invalid operation name "${result}": letters, digits and _ only`)
87
+ return result
88
+ }
89
+
90
+ /** Back to the default configuration. For the tests. */
91
+ export function resetConfig() {
92
+ for (const key of Object.keys(config)) delete config[key]
93
+ Object.assign(config, defaults())
94
+ }
95
+
96
+ /** A storage in memory, when localStorage does not exist (Node, private modes). */
97
+ export function memoryStorage() {
98
+ const values = new Map()
99
+ return {
100
+ getItem: key => values.get(key) ?? null,
101
+ setItem: (key, value) => values.set(key, String(value)),
102
+ removeItem: key => values.delete(key),
103
+ }
104
+ }