@protobase/cli 0.88.0 → 0.88.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.88.0";
2
+ var version = "0.88.2";
3
3
  //#endregion
4
4
  export { version };
@@ -1,4 +1,4 @@
1
- import { projectFiles, projectFunctions, projectJobs, projectNotifications, projectOptions, projectResources, projectWebhooks, projectWorkflows } from "./project-parts.js";
1
+ import { projectDerived, projectFiles, projectFunctions, projectJobs, projectNotifications, projectOptions, projectResources, projectWebhooks, projectWorkflows } from "./project-parts.js";
2
2
  import { userTablesOn } from "./user-tables-config.js";
3
3
  import { buildAppAuth, buildAuthenticator, checkCallsOptions, checkPushRelayOptions, checkStatusOptions, workflowPlugins } from "@protobase/server/internal";
4
4
  //#region src/config/build-project.ts
@@ -66,6 +66,7 @@ const buildProject = async (config, database) => {
66
66
  projectMailer(config)
67
67
  ]);
68
68
  const jobs = projectJobs(config);
69
+ const derived = projectDerived(config);
69
70
  const identity = config.themeColor || config.backgroundColor ? {
70
71
  ...config.themeColor && { themeColor: config.themeColor },
71
72
  ...config.backgroundColor && { backgroundColor: config.backgroundColor }
@@ -74,6 +75,7 @@ const buildProject = async (config, database) => {
74
75
  config: resources,
75
76
  authenticate: await projectAuthenticate(config, auth),
76
77
  jobs,
78
+ derived,
77
79
  ...auth && { auth },
78
80
  ...functions && { functions },
79
81
  ...files && { files },
@@ -25,6 +25,7 @@ const conventionModules = (projectDir) => {
25
25
  ];
26
26
  return [
27
27
  ...inFolder("jobs"),
28
+ ...inFolder("derived"),
28
29
  ...inFolder("hooks"),
29
30
  ...inFolder("files"),
30
31
  ...inFolder("workflows/plugins"),
@@ -68,6 +68,22 @@ const projectJobs = (config) => Object.entries(config.jobs).map(([name, { declar
68
68
  ...timezone && { timezone }
69
69
  }, async () => (await load()).default);
70
70
  });
71
+ /**
72
+ * The compute functions of the derived values, each the default export of derived/<resource>.<name>.ts in a config's
73
+ * folder, by that name, loaded on its first run.
74
+ */
75
+ const projectDerived = (config) => {
76
+ const all = config.sources.flatMap(({ files, label }) => files.folder("derived").map((file) => ({
77
+ name: file.slice(8, -3),
78
+ value: files.module(file),
79
+ label
80
+ })));
81
+ checkUnique("The derived value", all);
82
+ return Object.fromEntries(all.map(({ name, value: load }) => {
83
+ let compute;
84
+ return [name, async (key, context) => (await (compute ??= load().then((module) => module.default)))(key, context)];
85
+ }));
86
+ };
71
87
  /** The API functions of every config's functions/ folder by name, each its file's default export. */
72
88
  const projectFunctions = async (config) => {
73
89
  const all = config.sources.flatMap(({ files, label }) => Object.entries(files.functions).map(([name, load]) => ({
@@ -235,4 +251,4 @@ const projectNotifications = async (config) => {
235
251
  });
236
252
  };
237
253
  //#endregion
238
- export { lastModule, mergedModule, projectAssistantTools, projectFiles, projectFunctions, projectJobs, projectMcpTools, projectNotifications, projectOptions, projectResources, projectRoles, projectWebhooks, projectWorkflows, projectWriteHooks };
254
+ export { lastModule, mergedModule, projectAssistantTools, projectDerived, projectFiles, projectFunctions, projectJobs, projectMcpTools, projectNotifications, projectOptions, projectResources, projectRoles, projectWebhooks, projectWorkflows, projectWriteHooks };
package/dist/dev/entry.js CHANGED
@@ -7,7 +7,7 @@ import { devRealtimePrune } from "./dev-prune.js";
7
7
  import { devDatabase, loadDevConfig } from "./project.js";
8
8
  import { withDevServiceWorker } from "./service-worker-route.js";
9
9
  import { setMissing, supabaseEnv } from "./supabase-env.js";
10
- import { apiKeySettings, assistantSettings, authSchemaDrift, authStoreTables, checkAi, checkAuthSchema, checkCalls, checkChanges, checkChannelSends, checkComments, checkComputed, checkNotificationsSchema, checkPushRelaySchema, checkQueryRunner, checkRealtimeRelay, checkResourcesOutsideAuthStore, checkStatusSchema, checkUserTablesSchema, checkWebhooksSchema, checkWorkflowsSchema, configExports, hasUsers, relayed, sqlSends } from "@protobase/server";
10
+ import { apiKeySettings, assistantSettings, authSchemaDrift, authStoreTables, checkAi, checkAuthSchema, checkCalls, checkChanges, checkChannelSends, checkComments, checkComputed, checkDerived, checkNotificationsSchema, checkPushRelaySchema, checkQueryRunner, checkRealtimeRelay, checkResourcesOutsideAuthStore, checkStatusSchema, checkUserTablesSchema, checkWebhooksSchema, checkWorkflowsSchema, configExports, hasUsers, relayed, sqlSends } from "@protobase/server";
11
11
  import { upgradeWebSocket } from "@hono/node-server";
12
12
  import { Hono } from "hono";
13
13
  //#region src/dev/entry.ts
@@ -25,6 +25,7 @@ if (project.auth && !store.__protobaseAuthSchemaChecked) {
25
25
  if (project.auth) await checkResourcesOutsideAuthStore(db, resources.map((resource) => resource.toModel()), project.auth);
26
26
  await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
27
27
  await checkComments(db, resources.map((resource) => resource.toModel()));
28
+ await checkDerived(db, resources.map((resource) => resource.toModel()));
28
29
  await checkCalls(db, project.calls, project.events);
29
30
  await checkComputed(db, resources.map((resource) => resource.toModel()));
30
31
  if (assistantSettings(project.options?.assistant, process.env)?.kind === "built-in") await checkQueryRunner(db, project.auth ? authStoreTables(project.auth) : {
@@ -1,5 +1,5 @@
1
1
  import { authMigrationTitle } from "../auth/migration-file.js";
2
- import { authSchemaMigration, callsMigration, changesMigration, channelSendsMigration, commentsMigration, computedMigration, isCaptured, jobsSchemaMigration, notificationsMigration, ownedDefinitionsMigration, pushRelayMigration, queryRunnerMigration, realtimeRelayMigration, relayed, sqlSends, statusMigration, userTablesMigration, webhooksMigration, workflowsMigration } from "@protobase/server";
2
+ import { authSchemaMigration, callsMigration, changesMigration, channelSendsMigration, commentsMigration, computedMigration, derivedMigration, isCaptured, jobsSchemaMigration, notificationsMigration, ownedDefinitionsMigration, pushRelayMigration, queryRunnerMigration, realtimeRelayMigration, relayed, sqlSends, statusMigration, userTablesMigration, webhooksMigration, workflowsMigration } from "@protobase/server";
3
3
  //#region src/migration/parts.ts
4
4
  /** Every feature the project's config enables, in the order their files are written. */
5
5
  const migrationParts = (project) => {
@@ -31,6 +31,11 @@ const migrationParts = (project) => {
31
31
  title: "The role the assistant's read-only queries run as, which reads only the resources' tables",
32
32
  sql: () => queryRunnerMigration(project.db, project.models, project.authTables)
33
33
  }] : [],
34
+ ...project.models.some((model) => model.derived) ? [{
35
+ name: "derived",
36
+ title: "The state of the resources' derived values and what they read",
37
+ sql: () => derivedMigration(project.db, project.models)
38
+ }] : [],
34
39
  ...comments ? [{
35
40
  name: "comments",
36
41
  title: "The comments table of the resources with comments",
@@ -42,6 +42,7 @@ const projectAdmin = (project, db, ui, reporter, upgradeWebSocket, userTables) =
42
42
  ...project.app && { app: project.app },
43
43
  ...ui?.icons && { icons: ui.icons },
44
44
  jobs: project.jobs,
45
+ ...project.derived && { derived: project.derived },
45
46
  subscriptions,
46
47
  ...ui && {
47
48
  bundlePlugins: ui.plugins,
@@ -9,7 +9,7 @@ import { startCleanupTimer } from "./cleanup-timer.js";
9
9
  import { closeSockets } from "./close-sockets.js";
10
10
  import { servedRelease } from "./mobile-release.js";
11
11
  import pg from "pg";
12
- import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkCalls, checkChanges, checkChannelSends, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkPushRelaySchema, checkQueryRunner, checkRealtimeRelay, checkResourcesOutsideAuthStore, checkStatusSchema, checkUserTablesSchema, checkWebhooksSchema, checkWorkflowsSchema, configExports, createFileCleanup, relayed, sqlSends, startJobs } from "@protobase/server";
12
+ import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkCalls, checkChanges, checkChannelSends, checkComments, checkComputed, checkDerived, checkJobsSchema, checkNotificationsSchema, checkPushRelaySchema, checkQueryRunner, checkRealtimeRelay, checkResourcesOutsideAuthStore, checkStatusSchema, checkUserTablesSchema, checkWebhooksSchema, checkWorkflowsSchema, configExports, createFileCleanup, relayed, sqlSends, startJobs } from "@protobase/server";
13
13
  import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
14
14
  //#region src/serve/lifecycle.ts
15
15
  const listen = (server, port) => new Promise((resolve, reject) => {
@@ -31,6 +31,7 @@ const startServe = async ({ config, env, openDb = (url) => openAppDatabase(pg, u
31
31
  if (env.startupChecks && project.auth) await checkResourcesOutsideAuthStore(db, resources.map((resource) => resource.toModel()), project.auth);
32
32
  if (env.startupChecks) await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
33
33
  if (env.startupChecks) await checkComments(db, resources.map((resource) => resource.toModel()));
34
+ if (env.startupChecks) await checkDerived(db, resources.map((resource) => resource.toModel()));
34
35
  if (env.startupChecks) await checkCalls(db, project.calls, project.events);
35
36
  if (env.startupChecks) await checkComputed(db, resources.map((resource) => resource.toModel()));
36
37
  if (env.startupChecks && assistantSettings(project.options?.assistant, process.env)?.kind === "built-in") await checkQueryRunner(db, project.auth ? authStoreTables(project.auth) : {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.88.0",
3
+ "version": "0.88.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": {
@@ -43,13 +43,13 @@
43
43
  "dependencies": {
44
44
  "@better-auth/core": "^1.7.12",
45
45
  "@hono/node-server": "^2.1.3",
46
- "@protobase/config": "0.88.0",
47
- "@protobase/layout": "0.88.0",
48
- "@protobase/query": "0.88.0",
49
- "@protobase/schema": "0.88.0",
50
- "@protobase/server": "0.88.0",
51
- "@protobase/ui": "0.88.0",
52
- "@protobase/workflows": "0.88.0",
46
+ "@protobase/config": "0.88.2",
47
+ "@protobase/layout": "0.88.2",
48
+ "@protobase/query": "0.88.2",
49
+ "@protobase/schema": "0.88.2",
50
+ "@protobase/server": "0.88.2",
51
+ "@protobase/ui": "0.88.2",
52
+ "@protobase/workflows": "0.88.2",
53
53
  "@react-email/render": "^2.1.0",
54
54
  "@scalar/hono-api-reference": "^0.12.10",
55
55
  "@sentry/vite-plugin": "^11.10.0",
@@ -88,6 +88,7 @@ Reference:
88
88
  - When filling fields with a model → read [AI fields and actions](references/reference/ai.md)
89
89
  - When letting people without an account create records → read [Public forms](references/reference/forms.md)
90
90
  - When running background jobs → read [Jobs](references/reference/jobs.md)
91
+ - When a value worked out from other records should stay current by itself, recomputed when what it read changes or a time rule flips → read [Derived values](references/reference/derived.md)
91
92
  - When writing or running workflows, their steps and their runs → read [Workflows](references/reference/workflows.md)
92
93
  - When adding trigger or step types to workflows → read [Workflow plugins](references/reference/workflow-plugins.md)
93
94
  - When sending email → read [Email](references/reference/email.md)
@@ -8,6 +8,7 @@ Pages of your own, built from blocks in a JSX layout.
8
8
  - [Layout checks](../reference/layouts.md#what-a-layout-may-hold): The build refuses a layout with code, unknown props or unknown fields, and names the file and place.
9
9
  - [Conditions](../reference/layouts.md#conditions): Part of a page shows only while a condition on a record or a count holds.
10
10
  - [App addresses](../reference/layouts.md#addresses): Links to lists, records, create forms and pages are typed addresses that can carry filters and prefilled values.
11
+ - [Component fallbacks](../reference/custom-components.md#fallbacks): A custom component declares what a client that cannot draw it shows instead, or nothing, and the web shows it too when the component is missing or throws.
11
12
  - [Per-user pages](../reference/layouts.md#access): Each user gets the page without the parts, fields and actions they cannot use.
12
13
  - [Layout blocks](../reference/blocks.md#layout): Pages, responsive grids, cards and links.
13
14
  - [Full-width pages](../reference/blocks.md#page): A page fills the whole area beside the sidebar instead of a centred column, for a dashboard with many blocks.
@@ -18,4 +18,5 @@ React to changes, deliver them to other systems, and run work in the background.
18
18
  - [Recurring jobs](../reference/jobs.md#recurring-jobs): Jobs run on a cron schedule in a chosen time zone.
19
19
  - [Failed jobs page](../reference/jobs.md#failed-jobs-page): Admins see jobs that failed for good and retry or delete them.
20
20
  - [Worker process](../reference/jobs.md#where-jobs-run): Jobs and event deliveries run beside the API, or in a worker process of their own from the same bundle.
21
+ - [Derived values](../reference/derived.md) (experimental): A TypeScript function's result stays current by itself; Protobase records what it read and recomputes it when that changes or when a time rule flips.
21
22
  - [Jobs on hosts that sleep](../reference/jobs.md#hosts-that-sleep): A host that stops idle apps can wake them when a job is due.
@@ -6,7 +6,7 @@ React components, field types, pages and handlers of your own, loaded as plugins
6
6
 
7
7
  - [Custom components](../reference/custom-components.md#components): Your own React components used by name in layouts, reading data under the user's access.
8
8
  - [Custom list displays](../reference/custom-components.md#list-displays): Draw a list with your own component while the list page keeps loading, filters, search and paging.
9
- - [Custom record sections](../reference/custom-components.md#record-sections): Your own component on a record page, beside its sections.
9
+ - [Custom record sections](../reference/custom-components.md#record-sections): Your own component on a record page, beside its sections, with sections to show instead where it cannot be drawn.
10
10
  - [Custom record cards](../reference/custom-components.md#record-cards): Draw each card with your own component, with the built-in card as the fallback.
11
11
  - [Custom field types](../reference/plugins.md#field-types): Register how a kind of value is shown and edited, and pick it per field in a view.
12
12
  - [Custom create pages](../reference/custom-components.md#create-pages): Replace a resource's create form with your own page, such as a booking flow.
@@ -139,6 +139,7 @@ The other files belong to an option, and are described with it:
139
139
  | `assistant/tools.ts` | [`assistant`](config/admin-app.md#assistant) |
140
140
  | `mcp/tools.ts` | [`mcpEndpoint`](config/api.md#mcpendpoint) |
141
141
  | `jobs/<name>.ts` | [`jobs`](config/jobs-and-events.md#jobs) |
142
+ | `derived/<resource>.<name>.ts` | a resource's [`.derived()`](derived.md#declaring-a-derived-value) |
142
143
  | `webhooks/owner-roles.ts` | [`webhooks`](config/jobs-and-events.md#webhooks) |
143
144
  | `workflows/saved-by-roles.ts` | [`workflows`](config/jobs-and-events.md#workflows) |
144
145
  | `workflows/plugins/<name>.ts` | [`workflows.plugins`](config/jobs-and-events.md#workflowsplugins) |
@@ -76,6 +76,17 @@ A component that shows markdown, such as a chat message, uses `Markdown` from `@
76
76
 
77
77
  `protobase build` fails when the config declares a component that `protobase.ui.tsx` does not export, naming it; while you work, `protobase dev` draws a warning in its place. A component a plugin provides is declared with the plugin's name, `component('DraftOrders', { plugin: 'sales-tools' })`, and the build does not look for it in `protobase.ui.tsx`. A component that throws while drawing shows a warning in its own place, not a blank app. The object form, `defineUi({ components: { OrdersPerDay } })`, still works, and a name given both ways must be the same component.
78
78
 
79
+ ### Fallbacks
80
+
81
+ A client that cannot draw a component, such as a native app without React or the admin app without the plugin that provides it, draws the component's fallback in its place. Declare it with `component()`, as elements or `[]` to draw nothing:
82
+
83
+ ```tsx
84
+ export const SeatChart = component('SeatChart', { fallback: <Progress label="Seats" value="seats_used" max="plan.seats" /> })
85
+ export const Confetti = component('Confetti', { fallback: [] })
86
+ ```
87
+
88
+ The admin app draws the fallback too when the component is missing or throws while drawing; `protobase dev` also shows the warning above it. Without a fallback, the warning stands in the component's place, as above. A [record section](#record-sections) takes `fallback` in `l.custom`.
89
+
79
90
  ### Fields and resources in props
80
91
 
81
92
  A prop that names a field is a field reference, `fieldRef('plan.name')` from `@protobase/layout`, read from the record around the element or the resource its `resource` prop names. The component gets the plain name (`'plan.name'`), and the names are checked when the server starts. A `resource` prop names a resource the way a block's does.
@@ -140,6 +151,12 @@ export const CustomerRepairs = ({ limit }: { limit: number }) => {
140
151
 
141
152
  A list that should stay live polls: `useList('repairs', { refetchInterval: 5000 })` refetches every 5 seconds. It is TanStack Query's `refetchInterval`, so it also takes `false` to stop, or a function of the query, and pauses while the tab is in the background.
142
153
 
154
+ `fallback` gives what shows in the section's place, its title included, where the component cannot be drawn: sections and related tables in the main column, sidebar maps in the sidebar, or `[]` for nothing. `/api/meta` sends it with what the user cannot see left out, as [fallbacks](#fallbacks) of composed pages. <gap>A sidebar section cannot fall back to sections or related tables because drawing those in the sidebar is not implemented.</gap>
155
+
156
+ ```ts
157
+ l.custom(CustomerRepairs, { title: 'Earlier repairs', props: { limit: 5 }, fallback: [l.section('Customer', [r.customer_id])] })
158
+ ```
159
+
143
160
  ## Full-area record pages
144
161
 
145
162
  A view can make a component the whole record page with [`.record({ component })`](ui-config.md#full-area-record-pages). It gets the record from `useLayoutRecord()`, as a record section does, and fills the area beside the sidebar and under the top bar, where the page does not scroll: a list in it scrolls in a box of its own with `min-h-0 flex-1 overflow-y-auto`, and what follows the list stays at the bottom. It links to the record's standard page, which keeps the form, the related records, Edit and Delete:
@@ -0,0 +1,109 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from docs/website/src/content/docs/reference/derived.mdx: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Derived values
4
+
5
+ A TypeScript function's result kept current by itself, recomputed when what it read changes or when a time rule flips.
6
+
7
+ :::caution[Experimental]
8
+ Derived values may change in any release. They cannot fill a list of rows in another resource yet, cannot see the reads inside a database function or view they call, show `recalculating` rather than `stale` after a failed run, and their status cannot be read through the REST API; [Limits](#limits) has the detail.
9
+ :::
10
+
11
+ A **derived value** is worked out from other records for each record of a resource, such as a verdict on an objective from its tasks. You write a small TypeScript function that reads records and the clock; Protobase records what it read, computes it again when a change touches that or when a time check flips, and stores the result. No timer is involved, and a value that did not change is not written. It works on any Postgres, with no extension.
12
+
13
+ ```ts title="config/objectives.ts"
14
+ import { f, resource } from '@protobase/schema'
15
+
16
+ export const objectives = resource('objectives')
17
+ .table('objectives')
18
+ .fields({ id: f.integer().readOnly(), title: f.text(), verdict: f.enum(['done', 'open', 'late']).optional().readOnly() })
19
+ .primaryKey((r) => r.id)
20
+ .derived('verdict', { into: (r) => r.verdict, reads: ['tasks'] })
21
+
22
+ export const tasks = resource('tasks')
23
+ .table('tasks')
24
+ .fields({ id: f.integer().readOnly(), objectiveId: f.integer(), status: f.enum(['open', 'closed']), createdAt: f.timestamp().readOnly() })
25
+ .primaryKey((r) => r.id)
26
+ ```
27
+
28
+ ```ts title="derived/objectives.verdict.ts"
29
+ import type { DerivedCompute } from '@protobase/server'
30
+
31
+ // "late" once an open task is older than two hours, "open" while any is open, else "done".
32
+ export default (async (key, { db, clock }) => {
33
+ const open = await db.selectFrom('tasks').select(['created_at']).where('objective_id', '=', Number(key)).where('status', '=', 'open').execute()
34
+ if (open.length === 0) return 'done'
35
+ return open.some((task) => clock.olderThan(task.created_at, '2 hours')) ? 'late' : 'open'
36
+ }) satisfies DerivedCompute
37
+ ```
38
+
39
+ ## Declaring a derived value
40
+
41
+ [`.derived(name, spec)`](https://docs.protobase.net/api/schema/interfaces/resourcebuilder/#derived) on the resource whose records get a value. Its compute function is the default export of `derived/<resource>.<name>.ts`, typed with `DerivedCompute` from `@protobase/server`.
42
+
43
+ | Key | |
44
+ | --- | --- |
45
+ | `into: (r) => r.field` | The read-only field of the record the value goes into. |
46
+ | `into: { resource, field }` | A field of another resource's record of the same key, added when it has none. Its other fields need defaults. |
47
+ | `job` | A job of the config, enqueued with `{ resource, key, value }` each time the value changes, in place of `into` or beside it. |
48
+ | `reads` | The other resources the function reads. Their changes are captured as events' are. |
49
+ | `track: false` | Analyses none of its queries: only the dependencies the function names and its clock count. |
50
+
51
+ The function gets the record's key as its URL has it, and returns the value as JSON can hold it; `undefined` is `null`. Beside the key it gets:
52
+
53
+ | | |
54
+ | --- | --- |
55
+ | `db` | The app's database. Each query sent through it is analysed, raw SQL included; while it is, a write throws, since the function only reads. |
56
+ | `clock` | The time; see [The clock](#the-clock). |
57
+ | `depends(resource, where?)` | Names a dependency itself: every record of the resource, or those whose fields hold these values, such as `depends('tasks', { status: ['open', 'late'] })`. |
58
+ | `signal` | Aborted when the run times out or the worker shuts down. |
59
+
60
+ ## What it depends on
61
+
62
+ Each query the function sends is parsed with Postgres's own parser, however it was built. For each table it reads, Protobase keeps the query's conditions on that table: comparisons of its columns with constants and parameters, `IN`, `= ANY`, `BETWEEN` and null tests, joined with `AND`, `OR` and `NOT`, with the conditions of inner joins, and of an outer join's `ON` for its optional side. The condition is the dependency, so a new row that comes to match is caught as well as a row that leaves it. A part it cannot work out, such as a function call or a column of another table, counts as matching every row: a query it cannot read at all reads the whole table. Nested queries, `WITH` queries and both sides of a `UNION` count too. An update counts only when it changes a column the query used.
63
+
64
+ A table that is no resource of `reads` or the record's own stops the run with an error naming it: add its resource to `reads`, or name what the function depends on with `depends()` and set `track: false`.
65
+
66
+ ## The clock
67
+
68
+ | | |
69
+ | --- | --- |
70
+ | `clock.isPast(at)` | Whether the time `at` has come. |
71
+ | `clock.olderThan(at, duration)` | Whether more than `duration` has passed since `at`: milliseconds, or text such as `2 hours`. |
72
+ | `clock.now()` | When the function runs. |
73
+
74
+ Each check that has not flipped yet records the moment it will; the value is computed again then. `now()` records nothing, so a value that shows the time itself is not kept current.
75
+
76
+ ## When it runs
77
+
78
+ - **A new record** is computed once it is created, and a value declared for records that exist already computes each of them once, from the migration that adds it.
79
+ - **A change** that touches a recorded read, through the API or not, marks the value stale in the dispatch of [captured changes](events.md#how-changes-are-captured), and its run waits a second, so a burst of changes runs it once.
80
+ - **A change that lands while the function runs** makes the result stale before it is kept: it is dropped, and the value is computed again.
81
+ - **The value is written only when it differs**, so an unchanged value raises no event, live update or notification.
82
+ - A deleted record's value is dropped.
83
+
84
+ Runs are `derived.compute` jobs, four at a time per worker, retried like any [job](jobs.md) when the function throws.
85
+
86
+ ## State
87
+
88
+ `protobase migration` adds a `derived` schema, applied with the project's other migrations, and `protobase dev` and `protobase serve` do not start without it:
89
+
90
+ | Table | |
91
+ | --- | --- |
92
+ | `derived.values` | A row per record and value: `status` (`current`, `stale` or `recalculating`), `value` as JSON, `computed_at`, and `flips_at`, the clock's next flip. |
93
+ | `derived.reads` | What each record's value read: the resource, the condition, and the fields it used. |
94
+ | `derived.declared` | The values whose records the migrations have computed once. |
95
+
96
+ ## Limits
97
+
98
+ - <gap>A derived value cannot fill a list of rows in another resource, such as one row per item that needs attention, because syncing a set of rows is not implemented.</gap>
99
+ - <gap>A derived value cannot see the reads inside a database function or view it calls, because reading their definitions is not implemented.</gap> Name them with `depends()`.
100
+ - <gap>A derived value whose function threw cannot show `stale` until its retry runs, because marking a failed run is not implemented; it shows `recalculating` meanwhile.</gap>
101
+ - <gap>A derived value's status cannot be read through the REST API, because serving `derived.values` as a resource is not implemented.</gap>
102
+
103
+ ## Reusing the detection
104
+
105
+ The matching of committed changes against recorded reads is not tied to derived values. The same records of which conditions a reader depends on could later drive other features, each weighed on its own and possibly not worth it:
106
+
107
+ - **Live pages:** a list page's query recorded as a read, so the page refreshes only when a change can alter what it shows, instead of on every change of the resource.
108
+ - **Notifications:** a saved condition, such as "tasks assigned to me that are late", recorded once, so a change or a clock flip that makes a record match notifies its subscriber.
109
+ - **Job queues:** a job whose input is a query, run again when a change touches what it read, as `derived.compute` is.
@@ -75,7 +75,7 @@ Filters use the language of [access rules](access.md) and views, on any field, f
75
75
  - **What leaves nothing:** an update that changes no field, an update that ends where it started, an insert deleted in the same transaction, a rolled-back transaction or savepoint, and a change to a column that is not a field.
76
76
  - **A delete and an insert of the same key** in one transaction is an update.
77
77
  - **Soft deletes:** setting the soft delete field is a delete, clearing it an undelete.
78
- - Time passing is not a change. Something that should happen when a date is reached is a scheduled job.
78
+ - Time passing is not a change. Something that should happen when a date is reached is a scheduled job, or a [derived value](derived.md#the-clock) whose clock check flips then.
79
79
 
80
80
  ## How changes are captured
81
81
 
@@ -83,7 +83,7 @@ Filters use the language of [access rules](access.md) and views, on any field, f
83
83
 
84
84
  - **`changes.outbox`**, one row per changed row, written in the writer's transaction, so it commits or rolls back with the change. A dispatch job reads the committed rows and deletes them once their events are delivered or queued.
85
85
  - **`changes.capture()`**, the trigger function. It runs as its owner, with a fixed search path, so a role that writes the table needs no rights on `changes`: another service writing as its own role keeps working once a resource has events.
86
- - **Two triggers per resource with events, history or [live updates](live.md)**, on its table: `<table>_changes` for inserts and deletes, and `<table>_changes_update` for updates that change the row.
86
+ - **Two triggers per resource with events, history, [live updates](live.md) or [derived values](derived.md), or read by a derived value**, on its table: `<table>_changes` for inserts and deletes, and `<table>_changes_update` for updates that change the row.
87
87
 
88
88
  The first row a transaction captures also enqueues a `changes.dispatch` job with `jobs.enqueue()`, in the same transaction, so a resource with events needs the [`jobs` schema](jobs.md#the-jobs-schema) too. Dispatch jobs run one at a time, in the app's workers. After a write through the API commits, or an API function returns, the server has its own worker look for that job at once, so its events usually go out within milliseconds; a write from elsewhere waits for the next poll, two seconds at most.
89
89
 
@@ -45,6 +45,14 @@ Every element compiles to `{ type, props, children }`, and a custom component al
45
45
 
46
46
  Children are elements and text. `null`, `undefined` and booleans render nothing and numbers become text, as in React, so `{isBeta && <Card />}` and `.map()` over a constant list work. Fragments are flattened. An element may be a prop value too: `actions={<Action name="cancel" />}` or a list of them.
47
47
 
48
+ A custom component declared with a [fallback](custom-components.md#fallbacks) carries it on each of its elements as `fallback`, elements and text like children, or `[]` to draw nothing:
49
+
50
+ ```json
51
+ { "type": "SeatChart", "props": {}, "children": [], "custom": true, "fallback": [{ "type": "Progress", "props": { "label": "Seats", "value": "seats_used", "max": "plan.seats" }, "children": [] }] }
52
+ ```
53
+
54
+ A client that cannot draw the component, such as one without React, draws the fallback instead, and the checks read it like the rest of the tree.
55
+
48
56
  ## What a layout may hold
49
57
 
50
58
  A prop is a string, a finite number, a boolean, `null`, or an array or plain object of those (elements included). It is JSON in the end, so the rules are checked twice:
@@ -133,4 +141,4 @@ Every block reads the regular API with the user's token, so the access rules app
133
141
  - `ModalForm` needs create or update permission and keeps only the fields they may write;
134
142
  - an `Action` missing from their view of the resource is left out, and so is a `Show` that names something they cannot see.
135
143
 
136
- Custom components are kept: they get only their props, and fetch through the same API.
144
+ Custom components are kept: they get only their props, and fetch through the same API. A custom component's fallback loses what the user cannot use like the rest of the tree, and a fallback left with nothing is sent as `[]`, so a client still draws nothing in the component's place.
@@ -659,7 +659,7 @@ export const repairsView = filtered
659
659
  | `l.tab(title, items)` | A tab holding main-column items; a view's tabs show as one strip on the read view and the form. See [Tabs](#tabs). |
660
660
  | `l.sidebar(fields, { when? })` | A summary card beside it, read-only, each value on one line, cut off with an ellipsis when it does not fit and shown whole on hover. The record's created and updated times show in a Details card below it, but for those the summary lists. `when` also takes a [condition](#form-and-read-view). |
661
661
  | `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). |
662
- | `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. |
662
+ | `l.custom(Component, { title?, props?, sidebar?, when?, fallback? })` | 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. `fallback` shows in its place where it cannot be drawn. |
663
663
  | `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). |
664
664
  | `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). |
665
665
  | `l.gallery(title, { image?, photos?, when? })` | The record's photos as tiles, opening a lightbox. See [Galleries](#galleries). |