@protobase/cli 0.28.0 → 0.28.2

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.
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.28.0";
2
+ var version = "0.28.2";
3
3
  //#endregion
4
4
  export { version };
@@ -106,6 +106,20 @@ const galleryShapes = (item, owner, models) => {
106
106
  }
107
107
  }];
108
108
  };
109
+ const recordChartShapes = (item, owner, models) => {
110
+ const target = models[item.resource];
111
+ const field = target?.fields[item.field];
112
+ if (!target || !field || !target.fields[item.at]) return [];
113
+ return [{
114
+ resource: target.name,
115
+ request: `GET /${target.name}:aggregate?group_by=${item.at}&filter=${field.name} = …`,
116
+ from: `chart "${item.title}" on the ${owner} record page`,
117
+ query: {
118
+ filter: compare(field),
119
+ groupBy: item.at
120
+ }
121
+ }];
122
+ };
109
123
  const displayShapes = (model, view, models) => (view.list?.displays ?? []).flatMap((display) => {
110
124
  if (display.kind === "map") {
111
125
  const latitude = model.fields[display.latitude];
@@ -240,7 +254,7 @@ const listShapes = (model, view, list, models) => [
240
254
  ];
241
255
  /**
242
256
  * The reads a view's pages make: its list in its order, the filter widgets and their counts, its chart per value, its displays' maps,
243
- * board columns and photos, the records of its related sections and the photos of its galleries, the recent records in the sidebar, a saved search's new records and the records sorted by hand.
257
+ * board columns and photos, the records of its related sections and charts and the photos of its galleries, the recent records in the sidebar, a saved search's new records and the records sorted by hand.
244
258
  */
245
259
  const viewShapes = (view, models) => {
246
260
  const model = models[view.resource];
@@ -249,7 +263,7 @@ const viewShapes = (view, models) => {
249
263
  return [
250
264
  ...listShapes(model, view, list, models),
251
265
  ...(view.lists ?? []).flatMap((named) => listShapes(model, viewOfList(view, named.name), `${list} "${named.name}"`, models)),
252
- ...layoutItems(view.layout).flatMap((item) => item.kind === "related" ? relatedShapes(item, model.name, models) : item.kind === "gallery" ? galleryShapes(item, model.name, models) : []),
266
+ ...layoutItems(view.layout).flatMap((item) => item.kind === "related" ? relatedShapes(item, model.name, models) : item.kind === "gallery" ? galleryShapes(item, model.name, models) : item.kind === "chart" ? recordChartShapes(item, model.name, models) : []),
253
267
  ...recentShapes(model, view),
254
268
  ...searchesShapes(view, models),
255
269
  ...handOrderShapes(model, view, list, models)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.28.0",
3
+ "version": "0.28.2",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -35,11 +35,11 @@
35
35
  "dependencies": {
36
36
  "@hono/node-server": "^2.1.3",
37
37
  "@hono/vite-dev-server": "^0.26.1",
38
- "@protobase/layout": "0.28.0",
39
- "@protobase/query": "0.28.0",
40
- "@protobase/schema": "0.28.0",
41
- "@protobase/server": "0.28.0",
42
- "@protobase/ui": "0.28.0",
38
+ "@protobase/layout": "0.28.2",
39
+ "@protobase/query": "0.28.2",
40
+ "@protobase/schema": "0.28.2",
41
+ "@protobase/server": "0.28.2",
42
+ "@protobase/ui": "0.28.2",
43
43
  "@react-email/render": "^2.1.0",
44
44
  "@scalar/hono-api-reference": "^0.12.10",
45
45
  "@tailwindcss/vite": "^4.3.3",
@@ -108,6 +108,51 @@ Each item has `id`, `name`, `slug`, `price` and `image`, of published products o
108
108
 
109
109
  A field rule goes from the field to the roles: `cost_price` above is hidden from every role that reads products but those holding `costs.read`. Use it for the few sensitive columns of a resource that many roles read, such as a screening result (`f.text().access({ read: roles.can('screening.read') })`). A field list goes from the role to the fields: use it for a role that should see only some columns, such as an integration or anonymous visitors, so a new column stays hidden from it. When both apply, a field needs both.
110
110
 
111
+ ## Records that belong to another
112
+
113
+ A record often belongs to another one through a relation, such as an operation to the VM it runs on, and who may write it follows from who may change that VM. `.parent((r) => r.vm_id, 'update')` says so: writing an operation needs `update` on the record `vm_id` points at, `'read'` needing only to see it, as for a comment on a ticket. A member below may run operations on their own VMs only, with no rule of your own:
114
+
115
+ ```ts title="docs-examples/reference/child-records.ts"
116
+ import { defineRoles, f, resource } from '@protobase/schema'
117
+
118
+ // Virtual machines and the operations run on them: a member creates an operation only on a VM they may update.
119
+
120
+ export const roles = defineRoles<'vms' | 'operations'>({
121
+ admin: ['*'],
122
+ member: ['vms.read', 'vms.update.own', 'operations.read', 'operations.create'],
123
+ })
124
+
125
+ /** virt.vms, each owned by the user who made it. */
126
+ export const vms = resource('vms')
127
+ .table('virt.vms')
128
+ .fields({
129
+ id: f.integer().readOnly().filterable().dbDefault(),
130
+ name: f.text().filterable(),
131
+ owner_id: f.text().readOnly().filterable(),
132
+ })
133
+ .primaryKey((r) => r.id)
134
+ .owner((r) => r.owner_id)
135
+
136
+ /** virt.operations: writing one needs `update` on the VM its `vm_id` points at. */
137
+ export const operations = resource('operations')
138
+ .table('virt.operations')
139
+ .fields({
140
+ id: f.integer().readOnly().filterable().dbDefault(),
141
+ vm_id: f.relation('vms').filterable(),
142
+ kind: f.enum(['start', 'stop', 'reboot']),
143
+ })
144
+ .primaryKey((r) => r.id)
145
+ .parent((r) => r.vm_id, 'update')
146
+ ```
147
+
148
+ - **Every write is checked.** Creating a record checks the parent it names; changing it, the parent it points at and the one it moves to; deleting and undeleting it, the parent it points at. So a record cannot be created under an allowed parent and then moved under another. It holds for `/api/v1` and its batches, and for everything that writes through them: forms, [API functions](../guides/api-functions.md)) and the assistant.
149
+ - **The caller's own rules decide.** The parent is read as the caller would read it, with its tenant, row filters, soft delete and record-level rules; for `update`, also its update row filter and record-level update rule, given an empty input. A parent the caller cannot see, may not update, that is soft deleted or does not exist gets the same `403` as a refused create (`You may not create this operations record`), and nothing is written: the answer does not tell which VM ids exist.
150
+ - **A null relation checks nothing.** A relation set by a column default or a trigger is checked from the record as written.
151
+ - **`update` follows the parent's own parents**, so with VMs under `.parent((r) => r.folder_id, 'update')` an operation needs update on the VM's folder too. A write that would put a record under itself, or under a cycle already in the data, is refused. A `read` parent is not followed further.
152
+ - **Several parents** are each checked with their own access, also two of one resource, such as a transfer that reads its `source_vm_id` and updates its `target_vm_id`.
153
+ - **The parent is locked until the write commits** (`FOR NO KEY UPDATE`), so a VM handed to someone else or deleted at the same moment is waited for and checked again. That is the cost: writes of records under one parent, and through an `update` parent under one ancestor, run one after another. The server's database role needs `UPDATE` on the parent's table to take the lock. Two writes that lock the same records in opposite orders, such as two batches writing under VM A then B and B then A, can deadlock: Postgres rolls one back, which answers `409` and writes nothing, and the client sends it again.
154
+ - The record page and `/api/meta` count the check, so the admin app offers no Edit or Delete the server would refuse. `/rest/v1` does not use Protobase's access rules at all, so this check is not part of it.
155
+
111
156
  ## Restricted model and row filters
112
157
 
113
158
  [`resolveAccess`](https://docs.protobase.net/api/schema/functions/resolveaccess/)) returns everything a request may do. Use [`restrictModel(model, access)`](https://docs.protobase.net/api/schema/functions/restrictmodel/)) for everything user-facing (checking filters and sorts, queries, OpenAPI, `/meta`): hidden fields are gone, so they cannot be referenced, searched, sorted or leaked. Key columns always stay, because records are addressed by them.
@@ -47,8 +47,8 @@ Under `/api/v1`:
47
47
  | `POST /{resource}/{key}:undelete` | restores a soft-deleted record ([AIP-164](https://google.aip.dev/164)); `If-Match` optional; `409` when not deleted, `400` on hard-delete resources |
48
48
  | `POST /api/v1:batchWrite` | many writes in one transaction, see [Batch writes](#batch-writes) |
49
49
  | `GET /{resource}:facets?field=&filter=&limit=&label=` | `{ field, facets: [{ value, count }] }`, the `limit` most frequent values (100 by default, at most 1,000), never all of them; with `label`, a relation's facets carry the related record's name as `label`, as in [Related names](#related-names) |
50
- | `GET /{resource}:aggregate?group_by=&sum=&average=&filter=` | `{ group_by, groups: [{ value, count, sum }] }`: the records the whole filter finds, per value of `group_by`, each with its count and, with `sum` or `average` (one of the two), that of a numeric field, `null` when no record of the group has one. Values come largest first, the first `limit` (100 by default, at most 1,000), with `label` as in `:facets`. A date or timestamp `group_by` is bucketed like `:series` instead (`granularity` `hour` to `year`, `range` or `from` and `to`, `time_zone`), empty buckets included, and each `value` is the bucket's start; the response adds `granularity` and `time_zone`. With `split_by` (a filterable field of values), a date `group_by` also splits each bucket: the response adds `split_by` and `splits` (the `split_limit` largest values over the range, 8 by default and at most 100, ranked by the sum, else by count; `split_label` names a relation's values), and each group lists its `splits` with their count and sum or average. Unlike `:facets`, the filter's terms on `group_by` apply too, so the groups add up to what the filter finds |
51
- | `GET /{resource}:series?field=&range=&granularity=&time_zone=&filter=` | `range` is `7d`, `30d`, `90d`, `1y`, `all`, or `from` and `to` (ISO) |
50
+ | `GET /{resource}:aggregate?group_by=&sum=&average=&maximum=&filter=` | `{ group_by, groups: [{ value, count, sum }] }`: the records the whole filter finds, per value of `group_by`, each with its count and, with `sum`, `average` or `maximum` (one of them), that of a numeric field, `null` when no record of the group has one. Values come largest first, the first `limit` (100 by default, at most 1,000), with `label` as in `:facets`. A date or timestamp `group_by` is bucketed like `:series` instead (`granularity` `minute`, `5_minutes`, `15_minutes` or `hour` to `year`, `range` or `from` and `to`, `time_zone`), empty buckets included, and each `value` is the bucket's start; the response adds `granularity` and `time_zone`. With `split_by` (a filterable field of values), a date `group_by` also splits each bucket: the response adds `split_by` and `splits` (the `split_limit` largest values over the range, 8 by default and at most 100, ranked by the sum, else by count; `split_label` names a relation's values), and each group lists its `splits` with their count and sum, average or maximum. Unlike `:facets`, the filter's terms on `group_by` apply too, so the groups add up to what the filter finds |
51
+ | `GET /{resource}:series?field=&range=&granularity=&time_zone=&filter=` | `range` is `1h`, `24h`, `7d`, `30d`, `90d`, `1y`, `all`, or `from` and `to` (ISO); `granularity` `minute`, `5_minutes`, `15_minutes`, `hour`, `day` (the default), `week` or `month`. Buckets of minutes start on the clock's multiples of them |
52
52
  | `GET /{resource}:histogram?field=&buckets=&filter=` | equal-width buckets of a numeric field |
53
53
  | `GET /{resource}:map?latitude=&longitude=&zoom=&filter=&order_by=&fields=&labels=&photos=&photos_order_by=` | the records in a map's view, the bounding box being in `filter` (`lat >= 51.9 AND lat <= 52.1 AND lng >= 4.2 AND lng <= 4.5`), as `{ items, buckets, total_size }`; see [Maps](#maps) |
54
54
  | `GET /{resource}:seek?position=&order_by=&filter=&page_size=&fields=&labels=&photos=&photos_order_by=` | the page at a row position (scrollbar jumps), with `next_page_token` and `prev_page_token`; same items as a list |
@@ -63,6 +63,7 @@ export const repairs = resource('repairs')
63
63
  | `.owner((r) => r.owner_id)` | The field holding the owning user's id, which `.own` capabilities filter on (see [Access](#access)). |
64
64
  | `.search((r) => [r.number, r.name])` | The fields that `search("...")` and bare words in a filter match, and what the admin's [global search](client.md#global-search)) looks in. Every word of the text must appear in one of them, ignoring case, and part of a word is enough: `port` finds "Portfolio". `r.phone.digitsEnd()` matches only the end of a field's digits instead, ignoring spaces, `+` and dashes, and only words written like phone numbers: `9623`, `47069623` and `+31 6 47069623` find "+31 6 47069623", `4706` and `+316` do not. Each field needs a pg_trgm index (`using gin (name gin_trgm_ops)`), a `digitsEnd` one on `regexp_replace(phone, '[^0-9]', '', 'g')`, or the API refuses the search. |
65
65
  | `.position((r) => r.position, { within?, after? })` | The integer field holding the records' order by hand, 1 the first, which a list's **Reorder** button changes by dragging; with `within: (r) => r.invoice_id`, a filterable relation, each parent's records have an order of their own, sorted in its related section; with `after`, a record never ranks above the records it depends on. The field must be sortable. See [Reordering by hand](ui-config.md#reordering-by-hand)) and [Ranked after what they depend on](ui-config.md#ranked-after-what-they-depend-on)). |
66
+ | `.parent((r) => r.vm_id, 'update')` | The relation whose record each record belongs to, and the access on it (`'read'` or `'update'`) that creating, changing, deleting and undeleting a record needs, checked with the caller's own rules on that resource. The relation is one column, to a resource with a key of one field. See [Records that belong to another](access.md#records-that-belong-to-another)). |
66
67
  | `.validate((record) => issues)` | A rule over the whole record, run after the field checks on every create and update. It returns `[{ field, message }]` or `undefined`; issues answer `400` with the field named. |
67
68
  | `.access({ ... })` | Rules per operation. See [Access](#access). |
68
69
  | `.events((e, r) => [...])` | What changes of its records mean, such as `orders.created`, captured in the database for every write. See [Events](events.md)). |
@@ -603,6 +603,7 @@ export const repairsView = filtered
603
603
  | `l.related(title, { ... })` | A table or cards of the records of another resource that point at this one, in the main column. See [Related records](#related-records). |
604
604
  | `l.custom(Component, { title?, props?, sidebar?, when? })` | A [custom component](custom-components.md#record-sections)) where it is listed: in the main column under `title`, or with `sidebar: true` as a sidebar card. |
605
605
  | `l.map(title, { latitude, longitude, zoom?, sidebar?, when? })` | A map with a pin at the record's position, in the main column or with `sidebar: true` as a sidebar card. See [Maps](#maps). |
606
+ | `l.chart(title, { resource, field, at, series, range?, help?, when? })` | Line graphs of numbers of the records that point at this one, such as a machine's samples, over the last hour, day or week. See [Charts of related records](#charts-of-related-records). |
606
607
  | `l.gallery(title, { image?, photos?, when? })` | The record's photos as tiles, opening a lightbox. See [Galleries](#galleries). |
607
608
  | `l.history(title?, { limit?, when? })` | The record's changes, newest first, with who made each and the fields before and after; needs `.history()` on the resource, and a view without a layout shows it last by itself. See [Record history](history.md#on-the-record-page)). |
608
609
  | `l.comments(title?, { when? })` | The record's comments, oldest first, with a box to write one that @mentions people; needs `.comments()` on the resource, and a view without a layout shows it last by itself. See [Record comments](comments.md#on-the-record-page)). |
@@ -637,7 +638,7 @@ The open groups are in the address, as `?open=<title>` once per group, so a link
637
638
 
638
639
  ### Tabs
639
640
 
640
- `l.tab(title, items)` splits the record page into tabs. A tab holds any main-column item: sections, groups, related tables, custom components, maps, galleries, history and comments. It refuses a sidebar item, another tab, and a custom component or map with `sidebar: true`, since the sidebar stays beside the tabs on every tab.
641
+ `l.tab(title, items)` splits the record page into tabs. A tab holds any main-column item: sections, groups, related tables, custom components, maps, charts, galleries, history and comments. It refuses a sidebar item, another tab, and a custom component or map with `sidebar: true`, since the sidebar stays beside the tabs on every tab.
641
642
 
642
643
  A view's tabs stand together in the layout and show as one strip; items before them show above the strip and items after them below it, on every tab. Tab titles are unique among a view's tabs, and group titles are unique across the whole layout, groups inside tabs too. The read view and the form show the same tabs.
643
644
 
@@ -877,6 +878,29 @@ l.related('Waiting on you', {
877
878
 
878
879
  An action that `actions` names must be a named action of `resource`'s view. The cards have no display switch or **Reorder**; View all opens the list as a table section would.
879
880
 
881
+ ### Charts of related records
882
+
883
+ `l.chart(title, options)` draws line graphs of numeric fields of the records that point at the record on the page, over a timestamp of theirs, as a virtual machine's page graphs its CPU and network from the samples an app keeps of it, about one a minute. The section has a switch between the last **Hour**, per minute, the last **Day**, per 5 minutes, and the last **Week**, per hour, and one between the **Average** and the **Maximum** of each bucket. A bucket without a sample is a gap in the line, never 0. Each series is a line of its own colour, with a legend when there are several, and the tooltip shows each value with its field's prefix, suffix and decimals; the axis has one scale, so a chart holds series of one unit, such as bytes in and out.
884
+
885
+ | Option | |
886
+ | --- | --- |
887
+ | `resource` | The records charted, such as `host_samples`. Required. |
888
+ | `field` | The filterable relation on `resource` that holds this record's key. Required. |
889
+ | `at` | The filterable timestamp field of `resource` the records are placed by. Required. |
890
+ | `series` | The numeric fields of `resource` it draws, one line each, labelled as `resource`'s view labels them. At least one. |
891
+ | `range` | The range it opens on: `1h` (the default), `24h` or `7d`. |
892
+ | `help`, `when` | A line under the title, and whether it shows on the form, the read view or both. |
893
+
894
+ ```ts
895
+ view<typeof hosts>('hosts').layout((r) => [
896
+ l.section('Host', [r.name, r.address]),
897
+ l.chart('CPU', { resource: 'host_samples', field: 'host_id', at: 'sampled_at', series: ['cpu_percent'] }),
898
+ l.chart('Network', { resource: 'host_samples', field: 'host_id', at: 'sampled_at', series: ['net_in', 'net_out'], help: 'Bytes per second.' }),
899
+ ])
900
+ ```
901
+
902
+ Each series is read through [`:aggregate`](api.md)), grouped by `at` with `field = <this record's key>` as its filter, so the user's access applies as on the list, and a user who cannot read `field`, `at` or any series gets no chart (one who cannot read some series gets the others). That filter and grouping need an index on `(field, at)`, such as `create index on host_samples (host_id, sampled_at)`, which [`protobase doctor`](cli.md#doctor)) checks. A `field` that is no relation to this resource, an `at` that is no timestamp or not filterable, or a series that is no number or is sensitive stops the server at startup. Keeping the samples, and removing old ones, is the app's own work.
903
+
880
904
  ## Actions and views per role
881
905
 
882
906
  ```ts title="docs-examples/bike-shop/step-5.ts"