ramdb2-cli 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,7 @@
1
+ # ramdb2-cli
2
+
3
+ ## 2.0.0-alpha.1
4
+
5
+ ### Minor Changes
6
+
7
+ - 14d1f42: `ramdb2-cli infra build`: the Docker files of each server from `infra.yaml`, a front nginx with HTTPS and one domain per site, the API, its backups and the web site of each ramdb2 project.
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,429 @@
1
- # Temporary Holding Version
1
+ # ramdb2-cli
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 command line of ramdb2**: it turns a GraphQL schema into the classes of a [ramdb2-core](https://www.npmjs.com/package/ramdb2-core) database
4
+ and the schema of a [ramdb2-server](https://www.npmjs.com/package/ramdb2-server) API, creates new projects, draws the data model and
5
+ queries a running server.
6
+
7
+ | Command | |
8
+ |---|---|
9
+ | [`generate`](#generate) | the classes, the GraphQL schema and the schema of the operations, from the preTypeDefs |
10
+ | [`client`](#client) | the classes of a ramdb2-client application, from the preTypeDefs of its server |
11
+ | [`new`](#new) | a project ready to start, on ramdb2 and ramdb2-server, with a web site if asked |
12
+ | [`plantuml`](#plantuml) | the entity-relationship diagram of the data model |
13
+ | [`query`](#query) | a GraphQL query to a server, with an authentication token managed for you |
14
+ | [`convert`](#convert) | a v1 preTypeDefs (annotations in the descriptions) converted to directives |
15
+
16
+ ```sh
17
+ ramdb2-cli --help
18
+ ```
19
+
20
+ ```sh
21
+ npm install -g ramdb2-cli@alpha # or, without installing it: npx ramdb2-cli@alpha new my_project
22
+ ```
23
+
24
+ All the ramdb2 packages share one version: a project created by `ramdb2-cli new` depends on the version of the
25
+ ramdb2-cli that created it. Node.js 22 or later.
26
+
27
+ ---
28
+
29
+ ## generate
30
+
31
+ ```sh
32
+ ramdb2-cli generate --schema schema/preTypeDefs.graphql --dest .
33
+ ramdb2-cli generate --schema schema/preTypeDefs.graphql --schema schema/types.graphql --dest .
34
+ ```
35
+
36
+ Several `--schema` files are read as one schema. In a project created by `ramdb2-cli new`: `npm run generate`.
37
+
38
+ ### What it writes
39
+
40
+ | File | Content | Rewritten |
41
+ |---|---|---|
42
+ | `db/generated/<table>.js` | class `XxxBase`: fields, foreign keys, indexes, rules, default values, getters and setters, relations, computed fields, finders, invalidation code | at each generation |
43
+ | `db/extended/<table>.js` | class `Xxx extends XxxBase`: your business rules, computed fields and methods | never: created when missing |
44
+ | `db/index.js` | the extended classes, and `classes` for `store.register(...classes)` | at each generation |
45
+ | `schema/typeDefs.graphql` | the schema served by the API: without the directives (but `@sensitive`) nor the `@private` fields, with `id` and the foreign keys | at each generation |
46
+ | `schema/operations.graphql` | the `JSON` scalar, and for each type its input (with the `@sensitive` fields, without the `@private` ones), validation, query and list types, its queries and mutations | at each generation |
47
+
48
+ Never edit a generated file: the next generation would erase the change. Everything you write goes in
49
+ `db/extended`, and in your own schema files (`extend type Query { ... }`).
50
+
51
+ ### The schema: the preTypeDefs
52
+
53
+ ```graphql
54
+ enum Genre { NOVEL ESSAY }
55
+
56
+ "An author of books."
57
+ type Author @persistent @group(name: "LIBRARY") {
58
+ id: Int!
59
+ name: String! @index(type: FULLTEXT)
60
+ code: String! @pattern(regex: "^[A-Z]{2}$", message: "code must be 2 uppercase letters") @index
61
+ books: [Book!] @field(name: "idAuthor")
62
+ loanCount: Int! @computed(depends: ["books.loans"])
63
+ }
64
+
65
+ type Book @persistent @group(name: "LIBRARY") @index(fields: ["idAuthor", "title"]) {
66
+ id: Int!
67
+ author: Author!
68
+ sequel: Book
69
+ title: String! @index(type: FULLTEXT)
70
+ year: Int! @index(type: BTREE)
71
+ genre: Genre!
72
+ loans: [Loan!] @field(name: "idBook") @onDelete(action: RESTRICT)
73
+ authorName: String! @computed(depends: ["author.name"])
74
+ shelf: String! @transient
75
+ }
76
+
77
+ type Loan @persistent {
78
+ id: Int!
79
+ book: Book!
80
+ borrower: String!
81
+ }
82
+ ```
83
+
84
+ ### Directives
85
+
86
+ The directives are declared by ramdb2-cli, not in your files. graphql-js checks every use: an unknown directive,
87
+ a directive in the wrong place, a missing or badly typed argument is an error.
88
+
89
+ | Directive | On | Arguments | Meaning |
90
+ |---|---|---|---|
91
+ | `@persistent` | type | | a ramdb2 table |
92
+ | `@group` | type | `name: String!` | package of the type in the diagram |
93
+ | `@index` | field | `type: MAP \| BTREE \| FULLTEXT = MAP`, `name: String`, `unique: Boolean` | an index on the field; `unique` (MAP only): no two objects with the same value |
94
+ | `@index` (repeatable) | type | `fields: [String!]!` (two or more), `name: String`, `unique: Boolean` | an index on several fields |
95
+ | `@field` | list | `name: String!` | the foreign key held by the other type |
96
+ | `@onDelete` | list | `action: CASCADE \| SET_ZERO \| RESTRICT \| NOTHING` | deletion policy of these objects |
97
+ | `@computed` | field | `depends: [String!]!` | a cached value, with the paths it depends on |
98
+ | `@pattern` | field | `regex: String!`, `message: String` | a validation rule |
99
+ | `@transient` | field | | a field of the API that is not stored |
100
+ | `@sensitive` | field | | its value is masked in the logs of ramdb2-server (`"[REDACTED]"`) |
101
+ | `@private` | field | | stored and read by your code, but absent from the API: neither read, written nor queried (a password hash). Not with `!` when it would be required, nor with a FULLTEXT index |
102
+
103
+ ### How the fields are read
104
+
105
+ In a `@persistent` type, every field is stored, except `@computed` and `@transient` ones:
106
+
107
+ | Field | Becomes |
108
+ |---|---|
109
+ | scalar, enum, custom scalar | a stored field |
110
+ | `author: Author!` (a persistent type) | a relation: the foreign key `idAuthor` (`id` + the field name), required because of `!` |
111
+ | `books: [Book!] @field(name: "idAuthor")` | a list relation: the books whose `idAuthor` is this author |
112
+ | any other type, a list of scalars | an error, unless `@computed` or `@transient` |
113
+
114
+ - **Default values**: `0` (Int, Float), `''` (String, ID), `false` (Boolean), the first value of a non-null enum,
115
+ `null` otherwise.
116
+ - **Generated rules**: `required` for a `String!`, an `ID!` or a non-null custom scalar; `pattern` for
117
+ `@pattern`; `oneOf` for an enum (with `null` when it is nullable). The foreign keys are checked by ramdb2.
118
+ - **Deletion policy without `@onDelete`**: `CASCADE` for a required key, `SET_ZERO` for an optional one, as in the
119
+ v1. Without a list relation pointing back: `NOTHING`.
120
+
121
+ ### Finders
122
+
123
+ Each index gets static finders that read it directly:
124
+
125
+ ```js
126
+ Book.findByIdAuthor(3) // the inverse index of each foreign key
127
+ Author.findByCode('VH') // @index
128
+ Book.findByIdAuthorAndTitle(3, 'Germinal') // @index(fields: [...]): the last arguments can be left out
129
+ Book.findByYear(1885) // @index(type: BTREE)
130
+ Book.rangeOfYear({ gte: 1880 }, { reverse: true })
131
+ Book.search('germ') // @index(type: FULLTEXT): one full-text index per type
132
+ ```
133
+
134
+ An index with a `name:` gets a finder named `findBy` + the name.
135
+
136
+ ### Computed fields
137
+
138
+ ramdb2-cli inverts each dependency path and generates the code that invalidates the right values, in the methods
139
+ `_invalidateDependents` and `_invalidateLinks` of every type the path goes through. You only write the compute
140
+ function, in the extended class:
141
+
142
+ ```js
143
+ // db/extended/author.js
144
+ export default class Author extends AuthorBase {
145
+ computeLoanCount() {
146
+ let count = 0
147
+ for (const book of this.books) count += book.loans.size
148
+ return count
149
+ }
150
+ }
151
+ ```
152
+
153
+ Until it is written, reading the field throws `Author must implement computeLoanCount()`.
154
+
155
+ ### Checks
156
+
157
+ Every problem of the schema is listed at once:
158
+
159
+ ```
160
+ Invalid schema:
161
+ - Project.tasks: @field(name: "idProjet") needs an object relation projet: Project in Task
162
+ - Task.tags: a list of scalars cannot be persistent: add @transient or @computed
163
+ - Task.a: depends "project.nope": nope is not a field of Project
164
+ - Task: computed fields depend on each other in a cycle: a -> b -> c -> a
165
+ ```
166
+
167
+ A type used but not defined in the files given (defined by another layer) is read as a scalar, with a warning.
168
+
169
+ ---
170
+
171
+ ## new
172
+
173
+ ```sh
174
+ ramdb2-cli new my_project
175
+ cd my_project
176
+ npm install
177
+ npm start # http://localhost:4000
178
+ npm run dev # the same, with readable logs (pino-pretty)
179
+ ```
180
+
181
+ The folder must be empty or missing. ramdb2-cli writes the project, then runs `generate`:
182
+
183
+ | File | Content |
184
+ |---|---|
185
+ | `package.json` | `ramdb2-core`, `ramdb2-server` (and `ramdb2-cli` in dev), at the version of this ramdb2-cli; scripts `start`, `dev`, `generate`, `test`, `backup`, `create-user`; `pino-pretty` in dev |
186
+ | `.env.example` | the variables read at the start, with the command that makes a `TOKEN_SECRET` |
187
+ | `schema/preTypeDefs.graphql` | an example model: projects and tasks, an enum, full-text, a computed field; and the users (unique login, `@private` password) |
188
+ | `schema/project.graphql` | the operations written by hand: `health`, `changePassword`, `setPassword` |
189
+ | `db/extended/project.js` | an example extended class, with a rule and a compute function |
190
+ | `src/config.js` | the options of `startServer`, shared by the server and the tests: `auth`, `checkEntry`, the `context` (IP, user agent) and the `logging` |
191
+ | `src/auth.js` | `verifyCredentials` and `findUser`, for the authentication module of ramdb2-server |
192
+ | `src/index.js` | the start: `PORT`, `DB_PATH`, `LOG_LEVEL`, `TRUST_PROXY`, `TOKEN_SECRET` and `TOKEN_DURATION` from the environment or `.env` |
193
+ | `src/permissions.js`, `src/resolvers.js` | the permissions and the resolvers of the project |
194
+ | `scripts/backup.js` | a hot backup, with an example of cron in the README |
195
+ | `scripts/createUser.js` | `npm run create-user -- <login> [ADMIN\|USER]`: asks the password, creates the user or changes its password. The server must be stopped |
196
+ | `test/server.test.js` | a test of the API on an SQLite database in memory |
197
+
198
+ **Authentication is wired, but open.** `newToken`, `renewToken` and `me` work as soon as `TOKEN_SECRET` is set
199
+ (the server refuses to start without it), but `checkEntry` and the permissions allow everything. To close the
200
+ API: create a first user with `npm run create-user -- <login>`, uncomment the line of `checkEntry` in
201
+ `src/config.js`, then write the permissions on `context.user`. The password is `@private`: it is set by
202
+ `create-user`, by `changePassword(password, newPassword)` for the logged-in user, or by `setPassword(id, password)`
203
+ for an `ADMIN`. These mutations block the server while hashing, about 150 ms per hash.
204
+
205
+ `--packages <folder>` depends on the `packages` folder of a clone of the ramdb2 repository instead, through `file:`
206
+ paths: to try a change of ramdb2 before it is published. The paths are relative for a project next to the
207
+ repository, absolute otherwise. npm copies these packages into the `node_modules` of the project: after a change in
208
+ the repository, run `npm install` again in the project.
209
+
210
+ ### With a web site: `--with-client`
211
+
212
+ ```sh
213
+ ramdb2-cli new my_site --with-client
214
+ cd my_site
215
+ npm install # once, at the root: installs server/ and web/
216
+ cp server/.env.example server/.env # then set TOKEN_SECRET
217
+ npm run create-user -- admin # a first user, server stopped
218
+ npm run server # http://localhost:4000
219
+ npm run web # in another terminal: http://localhost:5173
220
+ ```
221
+
222
+ One project, two npm workspaces:
223
+
224
+ | Path | Content |
225
+ |---|---|
226
+ | `package.json` | the workspaces; scripts `generate` (server, then site), `server`, `web`, `build`, `test`, `create-user` |
227
+ | `server/` | the server project above |
228
+ | `web/package.json` | `ramdb2-client`, `ramdb2-vue` (and `ramdb2-cli` in dev), at the version of this ramdb2-cli, Vue, vue-router, Vite; scripts `dev`, `build`, `preview`, `generate` |
229
+ | `web/vite.config.js` | in development, `/graphql` goes to the server, on port 4000 |
230
+ | `web/src/main.js` | the connection to the server, the routes (home, login, error page), the menu |
231
+ | `web/src/App.vue`, `web/src/pages/Home.vue` | the structure of the site, and a home page |
232
+ | `web/src/db/` | the client classes, generated from the schema of `server/` ([`client`](#client)) |
233
+
234
+ A minimal skeleton: add the pages in `web/src/pages`, their routes and the menu in `web/src/main.js`. The README of
235
+ `web/` shows a page with a whole CRUD table. `npm run build` compiles the site into `web/dist/`; serving it in
236
+ production is up to you for now.
237
+
238
+ ---
239
+
240
+ ## client
241
+
242
+ ```sh
243
+ ramdb2-cli client --schema ../my_server/schema/preTypeDefs.graphql --dest src/model
244
+ ```
245
+
246
+ Run in the client application, on the preTypeDefs of its server (several `--schema` files are read as one schema,
247
+ as for `generate`). It writes, in `--dest`:
248
+
249
+ | File | Content | Rewritten |
250
+ |---|---|---|
251
+ | `generated/<table>.js` | `XxxBase extends ClientObject` (from `ramdb2-client`): `typeName`, `operations`, `fields`, `computed`, `transient`, `fullText`, `relations`, `defaults`, `generatedRules`, and a getter per field, foreign key, relation, computed and transient field | at each generation |
252
+ | `extended/<table>.js` | `Xxx extends XxxBase`: the code of the application (`static rules`, getters) | never (created when missing) |
253
+ | `index.js` | the extended classes, and `classes` for `configure({ classes })` | at each generation |
254
+
255
+ - **Read-only instances**: getters only (`this._f`, `this._c` for computed and transient fields, `this._relation('name')`), no setter. Never a `#`
256
+ private field: it breaks the reactive proxy of Vue.
257
+ - `fields`: `id`, the foreign keys (`idProject`), then the stored fields. `@private` fields are left out, as in the
258
+ API.
259
+ - `transient`: the `@transient` fields of a scalar type (scalar, enum, custom scalar, list of them), always loaded
260
+ with the object. One of an object type, or with a required argument, is left out with a warning.
261
+ - `fullText`: the fields of the `FULLTEXT` index, in the order of the schema (`[]` without one), for a search with `$text`.
262
+ - `generatedRules`: the same rules as the server (`required`, `pattern`, `oneOf`), plus `requiredKey('idProject')`
263
+ for a required object relation.
264
+ - `operations`: the names of the standard operations of ramdb2-server (`projects`, `projectById`, …).
265
+
266
+ ---
267
+
268
+ ## plantuml
269
+
270
+ ```sh
271
+ ramdb2-cli plantuml --schema schema/preTypeDefs.graphql --output model.puml
272
+ plantuml -tsvg model.puml
273
+ ```
274
+
275
+ The entity-relationship diagram of the persistent types:
276
+
277
+ - one package per `@group`; the types without group outside;
278
+ - for each table: the id, the foreign keys with their target (and `0 = none` when optional), the stored fields,
279
+ then the computed and transient fields in grey;
280
+ - for each foreign key, an association with its cardinality (`||` required, `|o` optional) and its deletion policy.
281
+
282
+ ```
283
+ author ||--o{ book : idAuthor (CASCADE)
284
+ book |o--o{ book : idSequel (SET_ZERO)
285
+ book ||--o{ loan : idBook (RESTRICT)
286
+ ```
287
+
288
+ Without `--output`, the diagram is printed. Render it with the PlantUML plugin of your IDE, or as SVG: in PNG,
289
+ PlantUML cuts the image at 4096 pixels.
290
+
291
+ ---
292
+
293
+ ## query
294
+
295
+ ```sh
296
+ ramdb2-cli query prod '{ projects { total } }'
297
+ ramdb2-cli query prod 'query($q: TaskQuery) { tasks(query: $q) { total items { name } } }' \
298
+ --variables '{"q": {"where": {"$text": {"$search": "design"}}, "limit": 10}}'
299
+ ramdb2-cli query prod --file report.graphql --variables '{"year": 2026}'
300
+ ```
301
+
302
+ Sends a GraphQL query to the server of a profile and prints the JSON response. The exit code is 1 when the
303
+ response holds errors: it can be used in scripts.
304
+
305
+ ### Profiles
306
+
307
+ One file per server, `~/.config/ramdb2-cli/<profile>.json` (or `$XDG_CONFIG_HOME/ramdb2-cli`):
308
+
309
+ ```json
310
+ {
311
+ "url": "https://api.example.com/graphql",
312
+ "login": "manu",
313
+ "auth": {
314
+ "query": "query($login: String!, $password: String!) { newToken(login: $login, password: $password) }",
315
+ "header": "authorization",
316
+ "prefix": "Bearer "
317
+ }
318
+ }
319
+ ```
320
+
321
+ Without `auth`, the query is sent without token. `header` defaults to `authorization`, `prefix` to nothing.
322
+ This profile fits a server with the authentication module of ramdb2-server.
323
+
324
+ ### Token and password
325
+
326
+ - The token is obtained with `auth.query`: it is the only value of its response.
327
+ - It is kept in `~/.cache/ramdb2-cli/<profile>.token` (or `$XDG_CACHE_HOME`), readable by you only, until it
328
+ expires. Its expiry is read in the token: the standard JWT `exp`, or `expiration` in milliseconds. A token
329
+ that expires within 30 seconds is renewed, and so is a token the server refuses (HTTP 401 or
330
+ `UNAUTHENTICATED`), once.
331
+ - **The password is never stored**: it comes from `RAMDB2_CLI_PASSWORD`, or is asked on the terminal, without echo.
332
+
333
+ Passing the query in variables is also the way to send the `$` keys of the query syntax: GraphQL does not
334
+ allow them in the text of a query.
335
+
336
+ ---
337
+
338
+ ## convert
339
+
340
+ ```sh
341
+ ramdb2-cli convert --input preTypeDefs.v1.graphql --output preTypeDefs.graphql
342
+ ```
343
+
344
+ Writes a copy of a v1 preTypeDefs with directives instead of annotations. The comments, the order and the rest
345
+ of the descriptions are kept. An existing output is replaced only with `--force`.
346
+
347
+ | v1 | v2 |
348
+ |---|---|
349
+ | `[PERSISTENT]` on a type | `@persistent` |
350
+ | `[GROUP=TASK]` | `@group(name: "TASK")` |
351
+ | `[PERSISTENT]` on a field | nothing: persistent by default |
352
+ | a field without `[PERSISTENT]` | `@transient` |
353
+ | `[FIELD=idTask]` | `@field(name: "idTask")` |
354
+
355
+ The deletion policies of the v1 lived in JavaScript (`extIndexConfig`): they are not converted. A warning lists
356
+ each list relation to check; write an `@onDelete` where the policy is not the default one.
357
+
358
+ ---
359
+
360
+ ## infra
361
+
362
+ The servers of your sites, in Docker: one front nginx per server (HTTPS, one domain per site), and for each ramdb2
363
+ site its API, its backups and its web site. Only Docker is needed on the server: the images are built there, from
364
+ your machine, with `DOCKER_HOST=ssh://`.
365
+
366
+ ```sh
367
+ ramdb2-cli infra build # build/<server>/ for every server of ./infra.yaml
368
+ ramdb2-cli infra build ovh1 # one server
369
+ ```
370
+
371
+ An infra folder (a git repository of its own):
372
+
373
+ | Path | Content |
374
+ |---|---|
375
+ | `infra.yaml` | the backups, the servers and their sites |
376
+ | `custom/<name>.nginx.conf`, `custom/<name>.compose.yaml` | a site that is not a ramdb2 project, written by hand |
377
+ | `build/` | generated, rewritten by each build: keep it out of git |
378
+
379
+ ```yaml
380
+ backup:
381
+ target: sftp://backup@backups.example.org:22/ramdb2 # one folder per site under it
382
+ servers:
383
+ ovh1:
384
+ host: ssh://manu@ovh1.example.org
385
+ email: me@example.org # the Let's Encrypt account
386
+ sites:
387
+ ilife: # unique on all the servers: containers, volume, backup folder
388
+ source: ../ilife # the project, made by ramdb2-cli new, relative to infra.yaml
389
+ domain: ilife.fr
390
+ aliases: [www.ilife.fr] # redirected (301) to domain
391
+ memory: 512m
392
+ custom:
393
+ - gancio # custom/gancio.nginx.conf, and custom/gancio.compose.yaml if any
394
+ - name: wiki
395
+ domains: [wiki.example.org] # certbot keeps a certificate, in /etc/nginx/certs/wiki.example.org/
396
+ ```
397
+
398
+ All the errors of `infra.yaml` are reported at once. `build/<server>/` holds:
399
+
400
+ | File | Content |
401
+ |---|---|
402
+ | `compose.yaml` | the Compose project of the server, the custom compose files included |
403
+ | `nginx/` | the front nginx image: its configuration, one file per site, the custom ones copied |
404
+ | `<site>/api.Dockerfile` | the API (target `api`, `node src/index.js`) and its backups (target `backup`, `ramdb2-server-backup schedule`) |
405
+ | `<site>/web.Dockerfile` | for a project made with `--with-client`: the site compiled by Vite, served by nginx |
406
+ | `certificates.json` | the certificates of the server and their domains |
407
+
408
+ - Each domain: HTTP redirected to HTTPS, `/graphql` to the API, the rest to the web site (all to the API for a
409
+ project without a web site).
410
+ - The database lives in a Docker volume, `<site>-data`. The images never contain `node_modules` from your machine,
411
+ a database, a backup or a `.env`.
412
+ - Nothing is mounted from your machine: the nginx configuration is in its image; the secrets come from the
413
+ environment of `docker compose` (`RAMDB2_SECRETS`, the folder of the site `.env` files, and `BACKUP_SSH_KEY`).
414
+ - The healthcheck of the API sends the GraphQL query `health`: keep it open without a login.
415
+ - Until a certificate exists, nginx serves a self-signed one, so that it can start.
416
+
417
+ ---
418
+
419
+ ## Programmatic use
420
+
421
+ ```js
422
+ import { generate, generateClient, newProject, plantuml, query, convert, readSchema } from 'ramdb2-cli'
423
+
424
+ const { written, kept, warnings } = generate({ schema: 'schema/preTypeDefs.graphql', dest: '.' })
425
+ generateClient({ schema: '../my_server/schema/preTypeDefs.graphql', dest: 'src/model' }) // same result
426
+ const model = readSchema(source) // throws a SchemaError listing every problem
427
+ const puml = plantuml('schema/preTypeDefs.graphql')
428
+ const { status, body } = await query({ profile: 'prod', query: '{ projects { total } }' })
429
+ ```
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "ramdb2-cli",
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": "Code generator and project scaffolding for ramdb2 and ramdb2-server",
5
+ "type": "module",
6
+ "exports": "./src/index.js",
7
+ "bin": {
8
+ "ramdb2-cli": "src/cli.js"
9
+ },
10
+ "license": "MIT",
11
+ "author": "Emmanuel Leparquier",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://gitlab.com/eleparquier/ramdb2.git",
15
+ "directory": "packages/ramdb2-cli"
16
+ },
17
+ "homepage": "https://gitlab.com/eleparquier/ramdb2/-/tree/master/packages/ramdb2-cli",
18
+ "files": [
19
+ "src",
20
+ "CHANGELOG.md"
21
+ ],
22
+ "scripts": {
23
+ "test": "node --test \"test/**/*.test.js\""
24
+ },
25
+ "dependencies": {
26
+ "graphql": "^16.14.2",
27
+ "yaml": "^2.9.1"
28
+ },
29
+ "devDependencies": {
30
+ "@vitejs/plugin-vue": "^6.0.10",
31
+ "ramdb2-core": "^2.0.0-alpha.1",
32
+ "vite": "^8.3.5",
33
+ "vue": "^3.5.44",
34
+ "vue-router": "^5.4.0"
35
+ }
36
+ }
package/src/cli.js ADDED
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
3
+ import { parseArgs } from 'node:util'
4
+ import { generate, generateClient } from './generate.js'
5
+ import { convert } from './convert.js'
6
+ import { newProject } from './new.js'
7
+ import { plantuml } from './plantuml.js'
8
+ import { query } from './query.js'
9
+ import { readInfra } from './infra/config.js'
10
+ import { buildInfra } from './infra/build.js'
11
+
12
+ const HELP = `ramdb2-cli: code generator of ramdb2
13
+
14
+ ramdb2-cli generate --schema <preTypeDefs.graphql> [--schema <other.graphql>...] --dest <folder>
15
+ Generates the classes (db/generated, rewritten; db/extended, created once), db/index.js,
16
+ schema/typeDefs.graphql and schema/operations.graphql. Several --schema files are read as one schema.
17
+
18
+ ramdb2-cli client --schema <preTypeDefs.graphql> [--schema <other.graphql>...] --dest <folder>
19
+ Generates the classes of a ramdb2-client application from the schema of its server: generated/ (rewritten),
20
+ extended/ (created once) and index.js, with the classes for configure({ classes }).
21
+
22
+ ramdb2-cli plantuml --schema <preTypeDefs.graphql> [--schema <other.graphql>...] [--output <model.puml>]
23
+ Entity-relationship diagram of the persistent types, in PlantUML: one package per @group,
24
+ foreign keys with their deletion policy. Printed, or written to --output.
25
+ Render it with an IDE plugin, or "plantuml -tsvg model.puml" (a PNG is cut at 4096 pixels).
26
+
27
+ ramdb2-cli query <profile> '<graphql>' [--variables '<json>'] | --file <query.graphql>
28
+ Sends a GraphQL query to the server of the profile (~/.config/ramdb2-cli/<profile>.json), with a token
29
+ renewed when it expires and kept in ~/.cache/ramdb2-cli. The password comes from RAMDB2_CLI_PASSWORD,
30
+ or is asked. Profile: { "url": ..., "login": ..., "auth": { "query": "query($login: String!,
31
+ $password: String!) { newToken(login: $login, password: $password) }" } }
32
+
33
+ ramdb2-cli new <folder> [--with-client] [--packages <folder>]
34
+ Creates a project on ramdb2 and ramdb2-server, ready to start: npm install, then npm start.
35
+ --with-client: one project with two npm workspaces, the server in server/ and a web site in web/
36
+ (ramdb2-client, ramdb2-vue), its classes generated from the schema of the server.
37
+ --packages: the packages folder of a ramdb2 repository, to depend on it through file: paths
38
+ (default: the packages from npm, at the version of this ramdb2-cli).
39
+
40
+ ramdb2-cli infra build [<server>...] [--config <infra.yaml>]
41
+ Writes build/<server>/ next to infra.yaml (all the servers by default): compose.yaml, the front nginx,
42
+ the Dockerfiles of each site. Generated, rewritten each time: keep build/ out of git.
43
+
44
+ ramdb2-cli convert --input <v1 preTypeDefs> --output <v2 preTypeDefs> [--force]
45
+ Converts the v1 annotations ([PERSISTENT], [GROUP=], [FIELD=]) into directives, in a new file.
46
+ `
47
+
48
+ const commands = {
49
+ infra(values, [action, ...servers]) {
50
+ if (action !== 'build') return usage('infra needs an action: build')
51
+ const infra = readInfra(values.config ?? 'infra.yaml')
52
+ for (const { server, files } of buildInfra(infra, servers)) {
53
+ console.log(`${server}: ${files.length} files`)
54
+ for (const path of files) console.log(`written ${path}`)
55
+ }
56
+ },
57
+ new(values, [dir]) {
58
+ if (dir === undefined) return usage('new needs the folder of the project')
59
+ const withClient = values['with-client'] ?? false
60
+ const { files } = newProject({ dir, packages: values.packages, withClient })
61
+ for (const path of files) console.log(`written ${path}`)
62
+ console.log(withClient
63
+ ? `\nNext: cd ${dir} && npm install, set TOKEN_SECRET in server/.env, then npm run server and npm run web (see README.md)`
64
+ : `\nNext: cd ${dir} && npm install && npm start`)
65
+ },
66
+ async query(values, [profile, text]) {
67
+ const source = values.file === undefined ? text : readFileSync(values.file, 'utf8')
68
+ if (profile === undefined || source === undefined) return usage('query needs a profile and a query (or --file)')
69
+ const variables = values.variables === undefined ? undefined : JSON.parse(values.variables)
70
+ const { status, body } = await query({ profile, query: source, variables })
71
+ console.log(typeof body === 'string' ? body : JSON.stringify(body, null, 2))
72
+ if (status >= 400 || body?.errors !== undefined) process.exitCode = 1
73
+ },
74
+ plantuml(values) {
75
+ if (values.schema === undefined) return usage('plantuml needs --schema')
76
+ const source = plantuml(values.schema)
77
+ if (values.output === undefined) process.stdout.write(source)
78
+ else {
79
+ writeFileSync(values.output, source)
80
+ console.log(`written ${values.output}`)
81
+ }
82
+ },
83
+ generate(values) {
84
+ if (values.schema === undefined || values.dest === undefined) return usage('generate needs --schema and --dest')
85
+ report(generate({ schema: values.schema, dest: values.dest }))
86
+ },
87
+ client(values) {
88
+ if (values.schema === undefined || values.dest === undefined) return usage('client needs --schema and --dest')
89
+ report(generateClient({ schema: values.schema, dest: values.dest }))
90
+ },
91
+ convert(values) {
92
+ if (values.input === undefined || values.output === undefined) return usage('convert needs --input and --output')
93
+ if (existsSync(values.output) && !values.force) return usage(`${values.output} exists: add --force to replace it`)
94
+ const result = convert(readFileSync(values.input, 'utf8'))
95
+ writeFileSync(values.output, result.source)
96
+ console.log(`${result.types} persistent types converted into ${values.output}`)
97
+ for (const warning of result.warnings) console.log(`warning ${warning}`)
98
+ },
99
+ }
100
+
101
+ function report({ written, kept, warnings }) {
102
+ for (const path of written) console.log(`written ${path}`)
103
+ for (const path of kept) console.log(`kept ${path} (written by hand)`)
104
+ for (const warning of warnings) console.log(`warning ${warning}`)
105
+ }
106
+
107
+ function usage(message) {
108
+ console.error(`${message}\n\n${HELP}`)
109
+ process.exitCode = 1
110
+ }
111
+
112
+ const { values, positionals } = parseArgs({
113
+ allowPositionals: true,
114
+ options: {
115
+ schema: { type: 'string', multiple: true },
116
+ dest: { type: 'string' },
117
+ input: { type: 'string' },
118
+ output: { type: 'string' },
119
+ force: { type: 'boolean' },
120
+ packages: { type: 'string' },
121
+ 'with-client': { type: 'boolean' },
122
+ variables: { type: 'string' },
123
+ file: { type: 'string' },
124
+ config: { type: 'string' },
125
+ help: { type: 'boolean', short: 'h' },
126
+ },
127
+ })
128
+
129
+ const command = commands[positionals[0]]
130
+ if (values.help || command === undefined) {
131
+ console.log(HELP)
132
+ } else {
133
+ try {
134
+ await command(values, positionals.slice(1))
135
+ } catch (error) {
136
+ console.error(['SchemaError', 'InfraError'].includes(error.name) || error.message.startsWith('No profile') ? error.message : error)
137
+ process.exitCode = 1
138
+ }
139
+ }