@protobase/cli 0.88.1 → 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.1";
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.1",
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.1",
47
- "@protobase/layout": "0.88.1",
48
- "@protobase/query": "0.88.1",
49
- "@protobase/schema": "0.88.1",
50
- "@protobase/server": "0.88.1",
51
- "@protobase/ui": "0.88.1",
52
- "@protobase/workflows": "0.88.1",
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)
@@ -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.
@@ -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) |
@@ -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