@protobase/cli 0.40.10 → 0.41.0
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/dist/build/deploy-bundle.js +2 -0
- package/dist/bundle/manifest.js +4 -1
- package/dist/cli/package.js +1 -1
- package/dist/mobile/api-origin-page.js +11 -0
- package/dist/mobile/fingerprint.js +13 -7
- package/dist/mobile/pinned-packages.js +7 -2
- package/dist/mobile/run.js +3 -7
- package/dist/mobile/web-part.js +17 -10
- package/dist/serve/app.js +3 -2
- package/dist/serve/bundle-site.js +2 -1
- package/dist/serve/env.js +4 -1
- package/dist/serve/lifecycle.js +14 -1
- package/dist/serve/mobile-release.js +41 -0
- package/dist/serve/serve-dir.js +5 -1
- package/dist/serve/site-files.js +21 -0
- package/dist/serve/static-site.js +6 -3
- package/package.json +6 -6
- package/skills/protobase/references/features/access.md +6 -5
- package/skills/protobase/references/features/build-and-run.md +5 -2
- package/skills/protobase/references/features/data-model.md +6 -3
- package/skills/protobase/references/features/releases.md +2 -1
- package/skills/protobase/references/features/start-a-project.md +3 -2
- package/skills/protobase/references/getting-started.md +6 -2
- package/skills/protobase/references/guides/deploy.md +5 -1
- package/skills/protobase/references/reference/access.md +2 -0
- package/skills/protobase/references/reference/api.md +1 -1
- package/skills/protobase/references/reference/cli.md +16 -2
- package/skills/protobase/references/reference/data-config.md +8 -4
- package/skills/protobase/references/reference/versioning.md +5 -1
|
@@ -10,6 +10,7 @@ import { buildIcons } from "./app-icons.js";
|
|
|
10
10
|
import { checkUi } from "./ui-check.js";
|
|
11
11
|
import { checkViews } from "./view-check.js";
|
|
12
12
|
import { protobaseFolder } from "../project/protobase-folder.js";
|
|
13
|
+
import { pinnedNative } from "../mobile/pinned-packages.js";
|
|
13
14
|
import { existsSync } from "node:fs";
|
|
14
15
|
import path from "node:path";
|
|
15
16
|
import { cp, readFile, rm, writeFile } from "node:fs/promises";
|
|
@@ -87,6 +88,7 @@ const buildDeployBundle = async ({ projectDir, outDir, bun, extensions = [], sou
|
|
|
87
88
|
plugins,
|
|
88
89
|
shell,
|
|
89
90
|
icons,
|
|
91
|
+
native: pinnedNative,
|
|
90
92
|
...packages.length > 0 ? { nodeModules: bundleNodeModules } : {},
|
|
91
93
|
...migrations ? { migrations } : {}
|
|
92
94
|
};
|
package/dist/bundle/manifest.js
CHANGED
|
@@ -19,15 +19,17 @@ const isObject = (value) => typeof value === "object" && value !== null && !Arra
|
|
|
19
19
|
const isFieldTypes = (value) => isObject(value) && Object.values(value).every(isStringList);
|
|
20
20
|
const isPlugin = (value) => isObject(value) && typeof value.name === "string" && typeof value.path === "string" && Number.isInteger(value.api) && typeof value.protobase === "string" && (value.fields === void 0 || isFieldTypes(value.fields));
|
|
21
21
|
const isShell = (value) => isObject(value) && typeof value.protobase === "string" && Number.isInteger(value.pluginApi) && isStringList(value.paths);
|
|
22
|
+
const isVersions = (value) => isObject(value) && Object.values(value).every((item) => typeof item === "string");
|
|
22
23
|
const isIcons = (value) => isObject(value) && typeof value.favicon === "boolean" && isStringList(value.png) && value.png.every((icon) => icon in pngIcons);
|
|
23
24
|
const parseManifest = (value, file) => {
|
|
24
25
|
const manifest = value;
|
|
25
26
|
if (manifest?.version !== 3) throw new Error(`${file} is not a version 3 bundle manifest; rebuild it with \`protobase build\``);
|
|
26
|
-
const { server, public: publicDir, api, spa, plugins, theme, shell, icons, nodeModules, migrations } = manifest;
|
|
27
|
+
const { server, public: publicDir, api, spa, plugins, theme, shell, icons, native, nodeModules, migrations } = manifest;
|
|
27
28
|
if (typeof server !== "string" || typeof publicDir !== "string" || typeof spa !== "string" || typeof theme !== "string" || !isStringList(api)) throw new Error(`${file} needs server, public, spa and theme paths and an api list`);
|
|
28
29
|
if (!Array.isArray(plugins) || !plugins.every(isPlugin)) throw new Error(`${file} needs a plugins list, each with a name, path, api and protobase`);
|
|
29
30
|
if (!isShell(shell)) throw new Error(`${file} needs a shell with its protobase version, pluginApi and paths`);
|
|
30
31
|
if (icons !== void 0 && !isIcons(icons)) throw new Error(`${file} has icons that are not a favicon flag and a list of PNG icons`);
|
|
32
|
+
if (native !== void 0 && !isVersions(native)) throw new Error(`${file} has a native that is not a map of package names to versions`);
|
|
31
33
|
if (nodeModules !== void 0 && typeof nodeModules !== "string") throw new Error(`${file} has a nodeModules that is no path`);
|
|
32
34
|
if (migrations !== void 0 && typeof migrations !== "string") throw new Error(`${file} has a migrations that is no path`);
|
|
33
35
|
return {
|
|
@@ -40,6 +42,7 @@ const parseManifest = (value, file) => {
|
|
|
40
42
|
theme,
|
|
41
43
|
shell,
|
|
42
44
|
...icons && { icons },
|
|
45
|
+
...native && { native },
|
|
43
46
|
...nodeModules === void 0 ? {} : { nodeModules },
|
|
44
47
|
...migrations === void 0 ? {} : { migrations }
|
|
45
48
|
};
|
package/dist/cli/package.js
CHANGED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { apiOriginMeta } from "@protobase/schema/internal";
|
|
2
|
+
//#region src/mobile/api-origin-page.ts
|
|
3
|
+
const escapeAttribute = (value) => value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
4
|
+
/** The page naming the API origin the shell calls, in the `<meta>` tag the shell reads (see `apiOriginMeta`). */
|
|
5
|
+
const withApiOrigin = (html, origin) => {
|
|
6
|
+
const at = html.indexOf("</head>");
|
|
7
|
+
if (at < 0) throw new Error("The shell's index.html has no </head> to name the API origin in");
|
|
8
|
+
return `${html.slice(0, at)}<meta name="${apiOriginMeta}" content="${escapeAttribute(origin)}">${html.slice(at)}`;
|
|
9
|
+
};
|
|
10
|
+
//#endregion
|
|
11
|
+
export { withApiOrigin };
|
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
//#region src/mobile/fingerprint.ts
|
|
3
|
-
/**
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Names the app's native code: the native packages @protobase/mobile pins, name → version (`pinnedNative`), and the
|
|
5
|
+
* project's `mobile.plugins`, name → the spec it gives. A release of the app's files runs only on a binary of the same
|
|
6
|
+
* fingerprint. It holds no Protobase version, so a Protobase release that pins the same native packages keeps
|
|
7
|
+
* binaries on live updates. A plugin's spec counts, not the version npm installed: its floor is what the app's files
|
|
8
|
+
* need of it, so raise the floor when they start using a newer native feature, which changes the fingerprint.
|
|
9
|
+
*/
|
|
10
|
+
const nativeFingerprint = (pinned, plugins = {}) => {
|
|
11
|
+
const entries = Object.entries({
|
|
12
|
+
...pinned,
|
|
13
|
+
...plugins
|
|
14
|
+
}).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
15
|
+
return createHash("sha256").update(JSON.stringify(entries)).digest("hex").slice(0, 16);
|
|
10
16
|
};
|
|
11
17
|
//#endregion
|
|
12
18
|
export { nativeFingerprint };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { installedPackage } from "./installed-package.js";
|
|
2
1
|
import { dependencies, name } from "./package.js";
|
|
2
|
+
import { installedPackage } from "./installed-package.js";
|
|
3
3
|
//#region src/mobile/pinned-packages.ts
|
|
4
4
|
/**
|
|
5
5
|
* The packages @protobase/mobile pins, itself included, which `mobile.plugins` may neither pin again nor compile into
|
|
@@ -7,6 +7,11 @@ import { dependencies, name } from "./package.js";
|
|
|
7
7
|
* @protobase/mobile of its own version, the one it installs.
|
|
8
8
|
*/
|
|
9
9
|
const pinnedPackages = /* @__PURE__ */ new Set([name, ...Object.keys(dependencies)]);
|
|
10
|
+
/**
|
|
11
|
+
* The native packages @protobase/mobile pins, name → exact version, which a native fingerprint names. Never its
|
|
12
|
+
* @protobase/* packages, whose version is Protobase's: every Protobase release would cut the binaries off updates.
|
|
13
|
+
*/
|
|
14
|
+
const pinnedNative = Object.fromEntries(Object.entries(dependencies).filter(([name]) => !name.startsWith("@protobase/")));
|
|
10
15
|
const liveUpdate = "@capawesome/capacitor-live-update";
|
|
11
16
|
/** Why the plugin `key`, a package that is or names `name`, may not be listed; `undefined` when it may. */
|
|
12
17
|
const pinnedProblem = (key, name = key) => {
|
|
@@ -24,4 +29,4 @@ const checkInstalledPlugins = (dir, keys) => {
|
|
|
24
29
|
}
|
|
25
30
|
};
|
|
26
31
|
//#endregion
|
|
27
|
-
export { checkInstalledPlugins, pinnedPackages, pinnedProblem };
|
|
32
|
+
export { checkInstalledPlugins, pinnedNative, pinnedPackages, pinnedProblem };
|
package/dist/mobile/run.js
CHANGED
|
@@ -1,15 +1,14 @@
|
|
|
1
|
+
import { checkInstalledPlugins, pinnedNative } from "./pinned-packages.js";
|
|
2
|
+
import { nativeFingerprint } from "./fingerprint.js";
|
|
1
3
|
import { withoutAndroidSigning } from "./android-signing.js";
|
|
2
4
|
import { runChild } from "./child-process.js";
|
|
3
5
|
import { apiUrl, checkReleaseUrl, httpAllowances } from "./api-origin.js";
|
|
4
6
|
import { capRunArgs } from "./cap-run-args.js";
|
|
5
|
-
import { installedPackage } from "./installed-package.js";
|
|
6
7
|
import { capacitorRunner } from "./capacitor.js";
|
|
7
8
|
import { buildWebPart, placeholderWebPart } from "./web-part.js";
|
|
8
9
|
import { capacitorConfig, writeCapacitorConfig } from "./capacitor-config.js";
|
|
9
10
|
import { childEnv, envFileKeys, projectEnvFiles } from "./child-env.js";
|
|
10
|
-
import { nativeFingerprint } from "./fingerprint.js";
|
|
11
11
|
import { generatePlatform } from "./generate.js";
|
|
12
|
-
import { checkInstalledPlugins } from "./pinned-packages.js";
|
|
13
12
|
import { checkMobileConfig } from "./mobile-config.js";
|
|
14
13
|
import { loadMobileProject } from "./load-project.js";
|
|
15
14
|
import { mobileSpec, prepareWorkspace, workspaceDir, workspacePackageJson } from "./workspace.js";
|
|
@@ -43,10 +42,7 @@ const prepare = async ({ projectDir, platform, api, extensions, live, release },
|
|
|
43
42
|
onWarning: (message) => process.stderr.write(`warning: ${message}\n`)
|
|
44
43
|
});
|
|
45
44
|
else await placeholderWebPart(ws);
|
|
46
|
-
const fingerprint = nativeFingerprint(
|
|
47
|
-
mobile: installedPackage(ws, "@protobase/mobile").version,
|
|
48
|
-
plugins: plugins.map((key) => [key, installedPackage(ws, key).version])
|
|
49
|
-
});
|
|
45
|
+
const fingerprint = nativeFingerprint(pinnedNative, mobile.plugins);
|
|
50
46
|
const appName = project.auth?.appName ?? defaultAppName;
|
|
51
47
|
await writeCapacitorConfig(ws, capacitorConfig({
|
|
52
48
|
appId: mobile.appId,
|
package/dist/mobile/web-part.js
CHANGED
|
@@ -1,19 +1,25 @@
|
|
|
1
1
|
import { bundleLayout } from "../bundle/manifest.js";
|
|
2
2
|
import { buildDeployBundle } from "../build/deploy-bundle.js";
|
|
3
|
+
import { withApiOrigin } from "./api-origin-page.js";
|
|
4
|
+
import { siteFiles } from "../serve/site-files.js";
|
|
3
5
|
import path from "node:path";
|
|
4
6
|
import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
7
|
+
import { releaseManifest } from "@protobase/server";
|
|
8
|
+
import { releaseManifestFile } from "@protobase/schema/internal";
|
|
9
|
+
const writeReleaseManifest = async (web) => {
|
|
10
|
+
const files = await Promise.all((await siteFiles({
|
|
11
|
+
publicDir: web,
|
|
12
|
+
spa: bundleLayout.spa
|
|
13
|
+
})).map(async ({ href, file }) => ({
|
|
14
|
+
href,
|
|
15
|
+
content: new Uint8Array(await readFile(file))
|
|
16
|
+
})));
|
|
17
|
+
await writeFile(path.join(web, releaseManifestFile), JSON.stringify(releaseManifest(files)));
|
|
12
18
|
};
|
|
13
19
|
/**
|
|
14
20
|
* The app's files: the deploy bundle's `public/` (the shell, the project's UI plugins, theme and favicon), its
|
|
15
|
-
* index.html naming the API origin. The bundle is built beside it and removed, so
|
|
16
|
-
* packages never sit where Capacitor copies from.
|
|
21
|
+
* index.html naming the API origin, and the updater's manifest of them. The bundle is built beside it and removed, so
|
|
22
|
+
* its server config module and packages never sit where Capacitor copies from.
|
|
17
23
|
*/
|
|
18
24
|
const buildWebPart = async ({ projectDir, ws, extensions, apiOrigin, build = buildDeployBundle, onWarning }) => {
|
|
19
25
|
const bundle = path.join(ws, "bundle");
|
|
@@ -39,6 +45,7 @@ const buildWebPart = async ({ projectDir, ws, extensions, apiOrigin, build = bui
|
|
|
39
45
|
});
|
|
40
46
|
const index = path.join(web, bundleLayout.spa);
|
|
41
47
|
await writeFile(index, withApiOrigin(await readFile(index, "utf8"), apiOrigin));
|
|
48
|
+
await writeReleaseManifest(web);
|
|
42
49
|
};
|
|
43
50
|
/** A stand-in for the app's files with `--live`, where the app opens `protobase dev` and never shows them. */
|
|
44
51
|
const placeholderWebPart = async (ws) => {
|
|
@@ -51,4 +58,4 @@ const placeholderWebPart = async (ws) => {
|
|
|
51
58
|
await writeFile(path.join(web, bundleLayout.spa), "<!doctype html><title>protobase dev</title>\n");
|
|
52
59
|
};
|
|
53
60
|
//#endregion
|
|
54
|
-
export { buildWebPart, placeholderWebPart
|
|
61
|
+
export { buildWebPart, placeholderWebPart };
|
package/dist/serve/app.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { isApiPath } from "../bundle/manifest.js";
|
|
2
2
|
import { serveStaticSite } from "./static-site.js";
|
|
3
|
-
import { jobsDrainApp, webauthnPath } from "@protobase/server";
|
|
3
|
+
import { jobsDrainApp, mobileReleaseApp, webauthnPath } from "@protobase/server";
|
|
4
4
|
import { Hono } from "hono";
|
|
5
5
|
import { logger } from "hono/logger";
|
|
6
6
|
//#region src/serve/app.ts
|
|
7
|
-
const createServeApp = ({ admin, requestLog, site, jobs, drainToken }) => {
|
|
7
|
+
const createServeApp = ({ admin, requestLog, site, jobs, drainToken, mobile }) => {
|
|
8
8
|
const app = new Hono();
|
|
9
9
|
if (requestLog) app.use(logger());
|
|
10
10
|
app.get("/health", (c) => c.json({ status: "ok" }));
|
|
@@ -13,6 +13,7 @@ const createServeApp = ({ admin, requestLog, site, jobs, drainToken }) => {
|
|
|
13
13
|
runtime: jobs,
|
|
14
14
|
token: drainToken
|
|
15
15
|
}));
|
|
16
|
+
if (mobile) app.route("/", mobileReleaseApp(mobile));
|
|
16
17
|
app.route("/", admin);
|
|
17
18
|
return app;
|
|
18
19
|
};
|
|
@@ -3,7 +3,8 @@ import path from "node:path";
|
|
|
3
3
|
const bundleSite = (dir, manifest) => ({
|
|
4
4
|
publicDir: path.resolve(dir, manifest.public),
|
|
5
5
|
spa: manifest.spa,
|
|
6
|
-
api: manifest.api
|
|
6
|
+
api: manifest.api,
|
|
7
|
+
...manifest.native && { native: manifest.native }
|
|
7
8
|
});
|
|
8
9
|
//#endregion
|
|
9
10
|
export { bundleSite };
|
package/dist/serve/env.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { readTrustedProxies } from "./client-address.js";
|
|
2
|
+
import { readSigningKey } from "@protobase/server";
|
|
2
3
|
//#region src/serve/env.ts
|
|
3
4
|
const defaultPort = 8787;
|
|
4
5
|
const readBoolean = (env, name, fallback) => {
|
|
@@ -12,6 +13,7 @@ const readServeEnv = (env) => {
|
|
|
12
13
|
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error(`PORT must be a port number, not "${env.PORT}"`);
|
|
13
14
|
const minutes = env.PROTOBASE_FILES_CLEANUP_MINUTES ? Number(env.PROTOBASE_FILES_CLEANUP_MINUTES) : 60;
|
|
14
15
|
if (!Number.isInteger(minutes) || minutes < 0) throw new Error(`PROTOBASE_FILES_CLEANUP_MINUTES must be a whole number of minutes, not "${env.PROTOBASE_FILES_CLEANUP_MINUTES}"`);
|
|
16
|
+
const mobileSigningKey = readSigningKey(env);
|
|
15
17
|
const connections = env.PROTOBASE_DB_CONNECTIONS ? Number(env.PROTOBASE_DB_CONNECTIONS) : void 0;
|
|
16
18
|
if (connections !== void 0 && (!Number.isInteger(connections) || connections < 1)) throw new Error(`PROTOBASE_DB_CONNECTIONS must be a whole number of connections, at least 1, not "${env.PROTOBASE_DB_CONNECTIONS}"`);
|
|
17
19
|
return {
|
|
@@ -23,7 +25,8 @@ const readServeEnv = (env) => {
|
|
|
23
25
|
runJobs: readBoolean(env, "PROTOBASE_JOBS", true),
|
|
24
26
|
startupChecks: readBoolean(env, "PROTOBASE_STARTUP_CHECKS", true),
|
|
25
27
|
...env.PROTOBASE_JOBS_DRAIN_TOKEN && { drainToken: env.PROTOBASE_JOBS_DRAIN_TOKEN },
|
|
26
|
-
trustedProxies: readTrustedProxies(env.PROTOBASE_TRUSTED_PROXIES)
|
|
28
|
+
trustedProxies: readTrustedProxies(env.PROTOBASE_TRUSTED_PROXIES),
|
|
29
|
+
...mobileSigningKey && { mobileSigningKey }
|
|
27
30
|
};
|
|
28
31
|
};
|
|
29
32
|
//#endregion
|
package/dist/serve/lifecycle.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { protobaseVersion } from "../version/version.js";
|
|
1
2
|
import { apiWebSocketServer } from "../project/api-websocket-server.js";
|
|
2
3
|
import { withClientAddress } from "./client-address.js";
|
|
3
4
|
import { projectAdmin } from "../project/project-admin.js";
|
|
@@ -5,6 +6,7 @@ import { createPgDb } from "../project/pg-db.js";
|
|
|
5
6
|
import { createServeApp } from "./app.js";
|
|
6
7
|
import { startCleanupTimer } from "./cleanup-timer.js";
|
|
7
8
|
import { closeSockets } from "./close-sockets.js";
|
|
9
|
+
import { servedRelease } from "./mobile-release.js";
|
|
8
10
|
import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkQueryRunner, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
|
|
9
11
|
import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
|
|
10
12
|
import pg from "pg";
|
|
@@ -43,12 +45,23 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
|
|
|
43
45
|
work: env.runJobs,
|
|
44
46
|
onError: (error) => console.error(error)
|
|
45
47
|
}) : void 0;
|
|
48
|
+
const release = project.mobile ? await servedRelease({
|
|
49
|
+
site,
|
|
50
|
+
mobile: project.mobile,
|
|
51
|
+
issuer: project.auth?.issuer,
|
|
52
|
+
signingKey: env.mobileSigningKey
|
|
53
|
+
}) : void 0;
|
|
54
|
+
const mobile = project.mobile && {
|
|
55
|
+
...release && { release },
|
|
56
|
+
serverVersion: protobaseVersion
|
|
57
|
+
};
|
|
46
58
|
const app = createServeApp({
|
|
47
59
|
admin,
|
|
48
60
|
requestLog: env.requestLog,
|
|
49
61
|
site,
|
|
50
62
|
...jobs && { jobs },
|
|
51
|
-
...env.drainToken && { drainToken: env.drainToken }
|
|
63
|
+
...env.drainToken && { drainToken: env.drainToken },
|
|
64
|
+
...mobile && { mobile }
|
|
52
65
|
});
|
|
53
66
|
const sockets = apiWebSocketServer();
|
|
54
67
|
const server = createAdaptorServer({
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { nativeFingerprint } from "../mobile/fingerprint.js";
|
|
2
|
+
import { withApiOrigin } from "../mobile/api-origin-page.js";
|
|
3
|
+
import { siteFiles } from "./site-files.js";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { composeRelease } from "@protobase/server";
|
|
6
|
+
//#region src/serve/mobile-release.ts
|
|
7
|
+
const loopback = [
|
|
8
|
+
"localhost",
|
|
9
|
+
"127.0.0.1",
|
|
10
|
+
"[::1]"
|
|
11
|
+
];
|
|
12
|
+
/**
|
|
13
|
+
* The API origin a release names, the auth issuer's (`baseURL`), as the app's own files do by default: https, or plain
|
|
14
|
+
* http to this machine only, as `protobase mobile` allows it. `undefined` for any other, which no app calls.
|
|
15
|
+
*/
|
|
16
|
+
const releaseOrigin = (issuer) => {
|
|
17
|
+
if (issuer === void 0 || !URL.canParse(issuer)) return void 0;
|
|
18
|
+
const url = new URL(issuer);
|
|
19
|
+
if (url.protocol === "https:" || url.protocol === "http:" && loopback.includes(url.hostname)) return url.origin;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* The release of the app's files a server offers its mobile app: every file the site serves, its SPA page naming the
|
|
23
|
+
* API origin as the app's own files do, for binaries of the fingerprint of the site's native packages and the project's
|
|
24
|
+
* plugins. None without a mobile section, without the site's files (the API alone, whose files a host serves), a
|
|
25
|
+
* site that names no native packages (a bundle built before them) or an API origin an app calls.
|
|
26
|
+
*/
|
|
27
|
+
const servedRelease = async ({ site, mobile, issuer, signingKey }) => {
|
|
28
|
+
const origin = releaseOrigin(issuer);
|
|
29
|
+
if (!mobile || !site?.native || !origin) return void 0;
|
|
30
|
+
const files = await Promise.all((await siteFiles(site)).map(async ({ href, file }) => ({
|
|
31
|
+
href,
|
|
32
|
+
content: href === site.spa ? new TextEncoder().encode(withApiOrigin(await readFile(file, "utf8"), origin)) : new Uint8Array(await readFile(file))
|
|
33
|
+
})));
|
|
34
|
+
return {
|
|
35
|
+
...composeRelease(files, signingKey),
|
|
36
|
+
fingerprint: nativeFingerprint(site.native, mobile.plugins),
|
|
37
|
+
origin
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
//#endregion
|
|
41
|
+
export { releaseOrigin, servedRelease };
|
package/dist/serve/serve-dir.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { readManifest } from "../bundle/manifest.js";
|
|
2
2
|
import { installedShellDir } from "../build/shell.js";
|
|
3
|
+
import { pinnedNative } from "../mobile/pinned-packages.js";
|
|
3
4
|
import { serveBundle } from "./serve-bundle.js";
|
|
4
5
|
import { bundleSite } from "./bundle-site.js";
|
|
5
6
|
import { servedShell, shellVariable } from "./served-shell.js";
|
|
@@ -11,7 +12,10 @@ const serveBundleDir = async (dir, env, out) => {
|
|
|
11
12
|
const { shell, note } = await servedShell(manifest, own);
|
|
12
13
|
const site = {
|
|
13
14
|
...bundleSite(dir, manifest),
|
|
14
|
-
...shell && {
|
|
15
|
+
...shell && {
|
|
16
|
+
shell,
|
|
17
|
+
native: pinnedNative
|
|
18
|
+
}
|
|
15
19
|
};
|
|
16
20
|
const server = await serveBundle(path.join(dir, manifest.server), env, out, site);
|
|
17
21
|
out(` app ${note}\n`);
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { siteRoot } from "./static-site.js";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { readdir } from "node:fs/promises";
|
|
4
|
+
//#region src/serve/site-files.ts
|
|
5
|
+
const filesIn = async (dir) => (await readdir(dir, {
|
|
6
|
+
recursive: true,
|
|
7
|
+
withFileTypes: true
|
|
8
|
+
})).filter((entry) => entry.isFile()).map((entry) => path.relative(dir, path.join(entry.parentPath, entry.name)).split(path.sep).join("/"));
|
|
9
|
+
/**
|
|
10
|
+
* Every file the site serves: its path inside the app's files, such as `assets/index-abc123.js`, and the file on disk,
|
|
11
|
+
* from the folder `serveStaticSite` serves that path from, so a server of its own shell lists the shell's.
|
|
12
|
+
*/
|
|
13
|
+
const siteFiles = async (site) => {
|
|
14
|
+
const roots = [site.publicDir, ...site.shell ? [site.shell.dir] : []];
|
|
15
|
+
return (await Promise.all(roots.map(async (root) => (await filesIn(root)).filter((href) => siteRoot(site, `/${href}`) === root).map((href) => ({
|
|
16
|
+
href,
|
|
17
|
+
file: path.join(root, href)
|
|
18
|
+
}))))).flat();
|
|
19
|
+
};
|
|
20
|
+
//#endregion
|
|
21
|
+
export { siteFiles };
|
|
@@ -42,18 +42,21 @@ const fileResponse = async (root, file) => new Response(await readFile(file), {
|
|
|
42
42
|
} });
|
|
43
43
|
const isNavigation = (request) => (request.headers.get("accept") ?? "").includes("text/html");
|
|
44
44
|
const isUnder = (paths, pathname) => paths.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
|
|
45
|
-
|
|
45
|
+
/** The folder the site serves the URL path `pathname` from: its own shell's, for the shell's paths and the root, else publicDir. */
|
|
46
|
+
const siteRoot = ({ publicDir, shell }, pathname) => shell && (pathname === "/" || isUnder(shell.paths, pathname)) ? shell.dir : publicDir;
|
|
47
|
+
const serveStaticSite = async (site, request) => {
|
|
48
|
+
const { publicDir, spa, shell } = site;
|
|
46
49
|
if (request.method !== "GET" && request.method !== "HEAD") return new Response("Method Not Allowed", {
|
|
47
50
|
status: 405,
|
|
48
51
|
headers: { allow: "GET, HEAD" }
|
|
49
52
|
});
|
|
50
53
|
const pathname = new URL(request.url).pathname;
|
|
51
54
|
const appDir = shell?.dir ?? publicDir;
|
|
52
|
-
const root =
|
|
55
|
+
const root = siteRoot(site, pathname);
|
|
53
56
|
const file = await fileFor(root, pathname);
|
|
54
57
|
if (file) return fileResponse(root, file);
|
|
55
58
|
if (isNavigation(request)) return fileResponse(appDir, path.join(appDir, spa));
|
|
56
59
|
return new Response("Not Found", { status: 404 });
|
|
57
60
|
};
|
|
58
61
|
//#endregion
|
|
59
|
-
export { frameHeaders, serveStaticSite };
|
|
62
|
+
export { frameHeaders, serveStaticSite, siteRoot };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.41.0",
|
|
4
4
|
"description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -36,11 +36,11 @@
|
|
|
36
36
|
"@better-auth/core": "^1.7.12",
|
|
37
37
|
"@hono/node-server": "^2.1.3",
|
|
38
38
|
"@hono/vite-dev-server": "^0.26.1",
|
|
39
|
-
"@protobase/layout": "0.
|
|
40
|
-
"@protobase/query": "0.
|
|
41
|
-
"@protobase/schema": "0.
|
|
42
|
-
"@protobase/server": "0.
|
|
43
|
-
"@protobase/ui": "0.
|
|
39
|
+
"@protobase/layout": "0.41.0",
|
|
40
|
+
"@protobase/query": "0.41.0",
|
|
41
|
+
"@protobase/schema": "0.41.0",
|
|
42
|
+
"@protobase/server": "0.41.0",
|
|
43
|
+
"@protobase/ui": "0.41.0",
|
|
44
44
|
"@react-email/render": "^2.1.0",
|
|
45
45
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
46
46
|
"@tailwindcss/vite": "^4.3.3",
|
|
@@ -5,12 +5,13 @@
|
|
|
5
5
|
Decide who may read and change which records and fields.
|
|
6
6
|
|
|
7
7
|
- [Roles and capabilities](../reference/access.md#capabilities): Roles defined in code grant capabilities per resource and action. A project with roles denies anything not granted.
|
|
8
|
-
- [Field and row limits](../reference/access.md#capabilities): A role can be limited to listed fields and to rows that match a filter. A field added later stays hidden from that role until it is listed.
|
|
8
|
+
- [Field and row limits](../reference/access.md#capabilities): A role can be limited to listed fields and to rows that match a filter. A field added later stays hidden from that role until it is listed, and the server does not start with a limit on a field or resource that does not exist.
|
|
9
|
+
- [Capability checks](../reference/access.md#wildcards-in-has-can-and-holds): Your code asks whether a user holds one capability, or all of a wildcard such as `vms.*`, and a check that could pass by accident is refused.
|
|
9
10
|
- [Field rules](../reference/access.md#field-rules-or-field-lists): Single fields, such as a cost price, can be hidden from every role that lacks a given capability.
|
|
10
|
-
- [Owned records](../reference/data-config.md#access): Users can be limited to the records they own, through an owner field.
|
|
11
|
+
- [Owned records](../reference/data-config.md#access): Users can be limited to the records they own, or that their team owns, through an owner field. The server does not start when that field cannot hold the users' ids.
|
|
11
12
|
- [Rules on the stored record](../reference/data-config.md#access): A rule can read the record as it is stored, such as one that refuses changes to a locked invoice.
|
|
12
|
-
- [Write-only fields](../reference/access.md#write-only-fields): A role can set a field it can never read back, such as a secret only a worker reads.
|
|
13
|
+
- [Write-only fields](../reference/access.md#write-only-fields): A role can set a field it can never read back, such as a secret only a worker reads. The admin app edits it only where the layout names it, with no stored value to reveal.
|
|
13
14
|
- [Access through a parent record](../reference/access.md#records-that-belong-to-another): Writing a child record can require access to the record it belongs to.
|
|
14
|
-
- [Anonymous access](../reference/access.md#anonymous-access): Visitors without an account can read listed fields of chosen records, such as a public product catalog.
|
|
15
|
+
- [Anonymous access](../reference/access.md#anonymous-access): Visitors without an account can read listed fields of chosen records, such as a public product catalog, and send the public forms you open to them.
|
|
15
16
|
- [Public browsing](../reference/access.md#browsing-the-admin-app): With anonymous access on, visitors browse what they may read in the admin app without signing in, read-only, with a Sign in button.
|
|
16
|
-
- [Checked on every request](../reference/api.md#access): The server applies the caller's operations, fields and rows to every request, on lists, record pages, composed pages and the API alike.
|
|
17
|
+
- [Checked on every request](../reference/api.md#access): The server applies the caller's operations, fields and rows to every request, on lists, record pages, composed pages and the API alike. Each record says what the caller may change in it, so the admin app offers no edit the server would refuse.
|
|
@@ -4,14 +4,17 @@
|
|
|
4
4
|
|
|
5
5
|
Develop, build and run an app, on servers, in containers and on phones.
|
|
6
6
|
|
|
7
|
+
- [Node and Bun](../reference/cli.md#how-it-runs): The `protobase` command runs on Node 22.12 or later or on Bun, and a bundle runs on both unless it is built for Bun only.
|
|
7
8
|
- [Dev server](../reference/cli.md#dev): The admin app and the API on one port, with changes shown without a restart.
|
|
8
9
|
- [Migrations from config](../reference/cli.md#migration): Writes the SQL migrations for what the config turns on, as files of the project.
|
|
9
10
|
- [User and organization commands](../reference/cli.md#users): Create users, set roles and manage organizations from the terminal.
|
|
10
11
|
- [Encryption commands](../reference/cli.md#encryption-status): Report and fix plaintext or old-key values of encrypted fields.
|
|
11
|
-
- [One bundle](../reference/cli.md#build): `protobase build` writes one folder with everything the app needs, without a database or secrets.
|
|
12
|
+
- [One bundle](../reference/cli.md#build): `protobase build` writes one folder with everything the app needs, without a database or secrets. It fails on a view that filters, sorts or searches by a field its resource does not allow.
|
|
13
|
+
- [Source maps](../reference/cli.md#source-maps): The bundle and plugins can carry source maps with debug ids, for an error tracker to read browser stack frames.
|
|
12
14
|
- [Extensions](../reference/cli.md#extensions): A host adds its own tools and widgets to every app it builds.
|
|
13
15
|
- [Native packages](../reference/cli.md#native-packages): npm packages with native add-ons are bundled for Linux.
|
|
14
|
-
- [Serve runtime](../reference/cli.md#serve): Runs a bundle, with a health check, startup checks, jobs and a clean shutdown.
|
|
16
|
+
- [Serve runtime](../reference/cli.md#serve): Runs a bundle, set by environment variables, with a health check, startup checks, jobs and a clean shutdown.
|
|
17
|
+
- [Migrations at update time](../guides/deploy.md#migrations): The bundle carries the project's migrations, and the runtime applies them in one transaction before the new version serves.
|
|
15
18
|
- [Single-file runtime](../reference/cli.md#build-serve): The runtime as one file, so a host needs only Bun and that file.
|
|
16
19
|
- [Separate worker](../reference/cli.md#worker): Jobs and event delivery in their own process.
|
|
17
20
|
- [Container images](../guides/deploy.md#images): A runtime image for each release, for amd64 and arm64.
|
|
@@ -4,8 +4,10 @@
|
|
|
4
4
|
|
|
5
5
|
Describe the tables of an existing Postgres database as resources, with their fields, keys and rules.
|
|
6
6
|
|
|
7
|
-
- [Resources](../reference/data-config.md#resource): Each table of an existing Postgres database is described as a resource in TypeScript, with its fields, key and rules. Nothing in the database changes.
|
|
8
|
-
- [
|
|
7
|
+
- [Resources](../reference/data-config.md#resource): Each table or view of an existing Postgres database is described as a resource in TypeScript, with its fields, key and rules. Nothing in the database changes.
|
|
8
|
+
- [Snake case names](../reference/data-config.md#resource): Scaffold names resources and fields after their tables and columns, such as `stock_moves` and `moved_at`, and the built-in resources are named the same way, so the names in URLs and the API match the database.
|
|
9
|
+
- [Field types](../reference/data-config.md#field-types): Text, numbers, exact decimals, booleans, dates, timestamps, UUIDs, enums, JSON, relations, currencies, countries and files, each mapped to Postgres column types and checked.
|
|
10
|
+
- [Field options](../reference/data-config.md#field-options): A field can be optional, read-only, given a default by the app or the database, filterable and sortable where an index serves it, known by other names, and read from a column of another name.
|
|
9
11
|
- [Composite keys and relations](../reference/data-config.md#keys-and-relations): Records can have keys of several columns, and relations can point at them. The admin shows a related record by its name and links to it.
|
|
10
12
|
- [Soft delete](../reference/data-config.md#resource): Deleting a record marks it with a timestamp instead of removing it. Lists leave it out, and it can be restored.
|
|
11
13
|
- [Tenants](../reference/data-config.md#resource): A tenant column keeps each organization's records apart. Every query is limited to the caller's tenant, and new records get it set.
|
|
@@ -14,6 +16,7 @@ Describe the tables of an existing Postgres database as resources, with their fi
|
|
|
14
16
|
- [Record validation](../reference/data-config.md#resource): A rule over the whole record runs on every create and update and reports each problem on the field it concerns.
|
|
15
17
|
- [Rollups and formulas](../reference/data-config.md#rollups-and-formulas) (beta): Fields that hold counts, sums, averages, minimums or maximums of related records, or values calculated from the record's own numbers, kept current by the database.
|
|
16
18
|
- [Sensitive fields](../reference/data-config.md#sensitive-fields): Values such as bank account numbers are left out of every response and shown masked. A permitted user reveals one value at a time, and each reveal is audited.
|
|
17
|
-
- [Encrypted fields](../reference/data-config.md#encrypted-fields): A sensitive text field is encrypted with the app's own key before it is stored, so dumps, backups and SQL readers see only ciphertext.
|
|
19
|
+
- [Encrypted fields](../reference/data-config.md#encrypted-fields): A sensitive text field is encrypted with the app's own key before it is stored, so dumps, backups and SQL readers see only ciphertext. A command encrypts the values a column already holds.
|
|
18
20
|
- [Encryption key rotation](../reference/data-config.md#the-key): The encryption key can be replaced without downtime. CLI commands re-encrypt stored values and report what is left.
|
|
21
|
+
- [Schema API reference](../reference/data-config.md#schema-api-reference): Every builder, option and type of `@protobase/schema` has a doc comment, shown in your editor and in the generated API reference, and the types the builders return are exported for helpers of your own.
|
|
19
22
|
- [Extending a config](../reference/cli.md#extending-a-config): A project can merge other configs and UI configs into its own. A name defined twice is an error, never a silent override.
|
|
@@ -4,8 +4,9 @@
|
|
|
4
4
|
|
|
5
5
|
How Protobase is released and versioned, and what a release keeps working.
|
|
6
6
|
|
|
7
|
-
- [Releases](../reference/versioning.md#releases): Every fix and feature is released when it lands, as packages and images of one version.
|
|
7
|
+
- [Releases](../reference/versioning.md#releases): Every fix and feature is released when it lands, as npm packages, published with provenance, and images of one version.
|
|
8
8
|
- [Version rules](../reference/versioning.md#versions-below-10): Semantic versioning. Below 1.0 a minor version may break.
|
|
9
9
|
- [Bundles and runtimes](../reference/versioning.md#bundles-and-runtimes): A runtime serves only bundles of a compatible version, and says why when it refuses one.
|
|
10
10
|
- [Plugins keep working](../reference/versioning.md#plugins): Plugins target a plugin API that releases keep.
|
|
11
11
|
- [Runtime updates](../reference/versioning.md#runtime-updates): Admins see whether the runtime has an update and start it from the app, when the host offers one.
|
|
12
|
+
- [New version notice](../reference/versioning.md#a-new-version-under-an-open-page): An open page keeps working when the server moves to a new Protobase version, and offers a reload.
|
|
@@ -4,11 +4,12 @@
|
|
|
4
4
|
|
|
5
5
|
Start a new app, or an admin over an existing Postgres database, and keep the config in step with it.
|
|
6
6
|
|
|
7
|
-
- [Project starter](../getting-started.md#start-an-app): `npm create protobase` starts a new app from the scratch, ERP or real estate preset and prints the next steps.
|
|
7
|
+
- [Project starter](../getting-started.md#start-an-app): `npm create protobase` starts a new app from the scratch, ERP or real estate preset and prints the next steps. Each preset has an `AGENTS.md` with rules for coding agents.
|
|
8
8
|
- [Example apps](../getting-started.md#run-the-erp-example): Seeded example apps on Postgres: an ERP, real estate property management and a public property portal.
|
|
9
|
-
- [Scaffold from a database](../reference/cli.md#scaffold): Reads your Postgres tables and writes the data config for them, with field types, keys, relations, enums, soft delete, tenants and search filled in.
|
|
9
|
+
- [Scaffold from a database](../reference/cli.md#scaffold): Reads your Postgres tables and writes the data config for them, with field types, keys, relations, enums, soft delete, tenants and search filled in, and with `--ui` a first view of each.
|
|
10
10
|
- [Safe re-scaffolding](../reference/cli.md#re-running): Running scaffold again adds only the columns that are not declared yet and leaves your own config code as it is.
|
|
11
11
|
- [Schema drift report](../reference/cli.md#drift-report): After each scaffold, lists declared fields whose column is gone, whose type changed or whose enum values differ, with a suggested fix.
|
|
12
12
|
- [Doctor](../reference/cli.md#doctor): Checks every resource and view against the database, including reads that lack an index, and prints the fix for each problem.
|
|
13
13
|
- [Admin without a view](../guides/table-to-admin.md#1-the-table-as-it-is): A table with an empty view already gives a working admin with every column, sorting, paging, a record page and a New button.
|
|
14
14
|
- [Agent skills](../reference/cli.md#skill): `protobase skill install` writes agent skills that match the installed version into the project, for the coding agents that work on it.
|
|
15
|
+
- [Docs as Markdown](../getting-started.md#docs-as-markdown): Every docs page is also Markdown at its address plus `.md`, for coding agents and chat assistants.
|
|
@@ -10,13 +10,17 @@ An app's own React code, its components, field types and actions, is a [plugin](
|
|
|
10
10
|
|
|
11
11
|
## Start an app
|
|
12
12
|
|
|
13
|
-
`npm create protobase my-app` asks which preset to start from, scratch (the default), the ERP or real estate, writes the project into `my-app`, with the `@protobase` packages in the range of the latest release's major, and prints the next steps: install it with Bun, point `.env` at a Postgres database, migrate it, load the preset's base data, if it has any, create a user and run `bun run dev`. `--preset <name>` picks one without asking; without a terminal it takes scratch. It needs Node 22.12 or later.
|
|
13
|
+
`npm create protobase my-app` asks which preset to start from, scratch (the default), the ERP or real estate, writes the project into `my-app`, with the `@protobase` packages in the range of the latest release's major, and prints the next steps: install it with Bun, point `.env` at a Postgres database, migrate it, load the preset's base data, if it has any, create a user and run `bun run dev`. `--preset <name>` picks one without asking; without a terminal it takes scratch. It needs Node 22.12 or later. Each preset has an `AGENTS.md` with the rules for a coding agent that changes the app, such as a new migration file for every schema change.
|
|
14
14
|
|
|
15
15
|
```sh
|
|
16
16
|
npm create protobase my-app
|
|
17
17
|
npm create protobase my-app -- --preset real-estate
|
|
18
18
|
```
|
|
19
19
|
|
|
20
|
+
## Docs as Markdown
|
|
21
|
+
|
|
22
|
+
Every page of these docs is also Markdown at its address plus `.md`: `https://docs.protobase.net/reference/cli/` is also `https://docs.protobase.net/reference/cli.md`. The code a page shows from example files is written out in it, and its live demos are left out, so a coding agent or a chat assistant reads the page whole. In a project, [`protobase skill install`](reference/cli.md#skill) gives coding agents the docs of the installed version.
|
|
23
|
+
|
|
20
24
|
The rest of this page works in a clone of this repository, on its examples.
|
|
21
25
|
|
|
22
26
|
## Setup
|
|
@@ -51,7 +55,7 @@ bun run --cwd examples/real-estate dev # http://localhost:5173
|
|
|
51
55
|
|
|
52
56
|
## Run the property portal example
|
|
53
57
|
|
|
54
|
-
`examples/property-portal` is a public portal of homes for sale and for rent in the Netherlands and Spain
|
|
58
|
+
`examples/property-portal` is a public portal of homes for sale and for rent in the Netherlands and Spain. Visitors browse and filter the listings without signing in, through the [anonymous role](reference/access.md#anonymous-access); members save searches of the listings that mail them new homes, and keep favorites and notes that only they see. The seed makes two members, `anna@portal.example` and `bram@portal.example`, and an admin, `admin@portal.example`, all with the password `property-portal-demo`.
|
|
55
59
|
|
|
56
60
|
```sh
|
|
57
61
|
bun run db:up && bun run --cwd examples/property-portal db:migrate && bun run --cwd examples/property-portal db:seed --scale small
|
|
@@ -28,7 +28,11 @@ dist/
|
|
|
28
28
|
plugins and the app's version
|
|
29
29
|
```
|
|
30
30
|
|
|
31
|
-
The host serves `public/` itself and sends only the manifest's `api` paths to the runtime (`/api` and the two OAuth discovery documents of [MCP clients](../reference/auth.md#oauth-for-mcp-clients), and `/.well-known/webauthn`, for an app on [several origins](../reference/auth.md#several-origins)), so loading the UI never needs a running container. With the UI it sends `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'`, as `protobase serve` does, so no other site frames the app's pages. The runtime serves the API alone; `protobase serve dist` serves the whole folder the same way, to check a bundle locally. The host passes `DATABASE_URL`, `PORT` (default 8787) and optionally `PROTOBASE_DB_CONNECTIONS` (the connections the app may open, so its functions and jobs leave one to requests, see [`serve`](../reference/cli.md#serve)), `REQUEST_LOG`, `PROTOBASE_SMTP_URL` and `PROTOBASE_MAIL_FROM` (the mail server and sender for [password reset](../reference/auth.md#password-reset) and emailed sign-in codes) `PROTOBASE_APP_NAME` (the app's name in that mail, see [`appName`](../reference/auth.md#configuration)) `PROTOBASE_SIGN_IN_*` (a provider people with an account sign in with, the [platform sign-in provider](../reference/auth.md#platform-sign-in-provider)) `PROTOBASE_OPERATOR_*` (the provider its staff sign in with for [staff sign-in](../reference/auth.md#staff-sign-in)), `PROTOBASE_ORIGINS` and `PROTOBASE_PASSKEY_DOMAIN` (the app's [other origins](../reference/auth.md#several-origins) and its passkey domain) `PROTOBASE_CORS_ORIGINS` (the websites that may call its API, see [CORS](../reference/api.md#cors)), `PROTOBASE_TRUSTED_PROXIES` (the proxies in front of the runtime, whose `X-Forwarded-For` names the client the sign-in limits count, see [Client addresses](../reference/auth.md#client-addresses)) and `PROTOBASE_SENTRY_DSN` (the app's [error tracker](../reference/api.md#error-reporting)), plus the project's own settings (`BETTER_AUTH_SECRET`, ...). The runtime and the config module are plain JavaScript for Bun: no install, no TypeScript, no writes. The runtime supplies protobase and the dependencies it runs on the server (`pg`, `postgres`, `kysely`, `better-auth`, ...), so the config module carries only the project's code and the other packages it uses. The runtime serves only bundles built by a compatible Protobase version, below 1.0 the same minor (see [Versioning](../reference/versioning.md#bundles-and-runtimes)), so rebuild the bundle when the host's runtime moves to another one.
|
|
31
|
+
The host serves `public/` itself and sends only the manifest's `api` paths to the runtime (`/api` and the two OAuth discovery documents of [MCP clients](../reference/auth.md#oauth-for-mcp-clients), and `/.well-known/webauthn`, for an app on [several origins](../reference/auth.md#several-origins)), so loading the UI never needs a running container. With the UI it sends `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'`, as `protobase serve` does, so no other site frames the app's pages. The runtime serves the API alone; `protobase serve dist` serves the whole folder the same way, to check a bundle locally. The host passes `DATABASE_URL`, `PORT` (default 8787) and optionally `PROTOBASE_DB_CONNECTIONS` (the connections the app may open, so its functions and jobs leave one to requests, see [`serve`](../reference/cli.md#serve)), `REQUEST_LOG`, `PROTOBASE_SMTP_URL` and `PROTOBASE_MAIL_FROM` (the mail server and sender for [password reset](../reference/auth.md#password-reset) and emailed sign-in codes) `PROTOBASE_APP_NAME` (the app's name in that mail, see [`appName`](../reference/auth.md#configuration)) `PROTOBASE_SIGN_IN_*` (a provider people with an account sign in with, the [platform sign-in provider](../reference/auth.md#platform-sign-in-provider)) `PROTOBASE_OPERATOR_*` (the provider its staff sign in with for [staff sign-in](../reference/auth.md#staff-sign-in)), `PROTOBASE_ORIGINS` and `PROTOBASE_PASSKEY_DOMAIN` (the app's [other origins](../reference/auth.md#several-origins) and its passkey domain) `PROTOBASE_CORS_ORIGINS` (the websites that may call its API, see [CORS](../reference/api.md#cors)), `PROTOBASE_TRUSTED_PROXIES` (the proxies in front of the runtime, whose `X-Forwarded-For` names the client the sign-in limits count, see [Client addresses](../reference/auth.md#client-addresses)) and `PROTOBASE_SENTRY_DSN` (the app's [error tracker](../reference/api.md#error-reporting)), plus the project's own settings (`BETTER_AUTH_SECRET`, ...). The runtime and the config module are plain JavaScript for Bun: no install, no TypeScript, no writes. The runtime supplies protobase and the dependencies it runs on the server (`pg`, `postgres`, `kysely`, `better-auth`, ...), so the config module carries only the project's code and the other packages it uses. The runtime serves only bundles built by a compatible Protobase version, below 1.0 the same minor (see [Versioning](../reference/versioning.md#bundles-and-runtimes)), so rebuild the bundle when the host's runtime moves to another one. The manifest format and the routing rules are in the CLI reference: [`build`](../reference/cli.md#build), [`build-serve`](../reference/cli.md#build-serve) and [`serve`](../reference/cli.md#serve).
|
|
32
|
+
|
|
33
|
+
## Migrations
|
|
34
|
+
|
|
35
|
+
Serving never changes the database: the bundle carries the project's `db/migrations` as `migrations/`, and the runtime's `migrate <bundle>` applies the pending ones, the app's and the auth schema's, before a new version serves, with no other writes while it runs. It applies them in one transaction behind a lock, recorded in `public.schema_migrations` as the presets' `db:migrate` does, so a database either script migrated is current for the other. A file that would end that transaction (`BEGIN`, `COMMIT`, `ROLLBACK`) or cannot run in one (`create index concurrently`) is refused, and a refused or failing file leaves the database unchanged. The runtime refuses to start while the auth schema lacks a table or column the new version needs (see [migrations](../reference/auth.md#migrations)). [`protobase migration`](../reference/cli.md#migration) writes the files the config's features need, such as the auth and jobs schemas, as the project's own migrations, and [a self-hosted image](#a-self-hosted-image) runs `migrate` as a step of its own before the app starts.
|
|
32
36
|
|
|
33
37
|
## Images
|
|
34
38
|
|
|
@@ -26,6 +26,7 @@ defineRoles<'orders' | 'products'>({
|
|
|
26
26
|
})
|
|
27
27
|
```
|
|
28
28
|
|
|
29
|
+
- **Scopes**: `.own` gives the records whose [`.owner()`](data-config.md#resource) field holds the user's id, and `.team` those owned by the users that `teamOf` returns for them, a function given as `defineRoles(roles, { teamOf: (user) => ids })`. A scoped capability on a resource without `.owner()` fails the request.
|
|
29
30
|
- **Fields** (`['sku', 'price']`, or `fields` in an object) are an allowlist: for `<resource>.read`, `.create` or `.update`, the role reads or writes only the fields listed, so a column added later stays hidden from it until someone lists it. Key columns are always there, because records are addressed by them. A plain capability (`'products.read'`) still means every field.
|
|
30
31
|
- **Filter** is AIP-160 text, like a filter an access rule returns. It narrows the rows of the capability, together with `.own` or `.team` when the capability has one.
|
|
31
32
|
- A limit names one resource, never `*`, and fields go with `read`, `create` or `update` only; `defineRoles` refuses anything else. At startup the server refuses a field the resource does not have, a filter that does not fit it, and a limit on a name that is not a resource.
|
|
@@ -159,6 +160,7 @@ export const operations = resource('operations')
|
|
|
159
160
|
|
|
160
161
|
- **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.
|
|
161
162
|
- **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.
|
|
163
|
+
- **One column, to a key of one field.** The config does not load with a relation of several columns as a parent, and the server does not start with a parent resource the app does not have or whose key has several fields.
|
|
162
164
|
- **A null relation checks nothing.** A relation set by a column default or a trigger is checked from the record as written.
|
|
163
165
|
- **`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.
|
|
164
166
|
- **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`.
|
|
@@ -108,7 +108,7 @@ Get responses carry `permissions: { update, delete, fields }`, where `fields` ma
|
|
|
108
108
|
|
|
109
109
|
### `/meta` and OpenAPI per caller
|
|
110
110
|
|
|
111
|
-
`/meta` returns, per caller: the resources they can do anything with as restricted models (hidden fields absent, `readOnly` unless writable), the view for their roles ([`pickView`](https://docs.protobase.net/api/schema/functions/pickview/)) with every reference to a hidden field removed (columns, sort, search, filters, layout, chart, title, search result) and the [related sections](ui-config.md#related-records) they cannot use, `permissions[resource]` as `{ read, create, update, delete, conditional }`, the [user menu](user-menu.md) as `userMenu` and the [bottom bar](bottom-bar.md) of their active role as `bottomBar`, each without the resources and pages they cannot see, and the [composed pages](layouts.md#access) as `pages`, each without the elements that name what they cannot see or do, and, for a caller with the `admin` or `ai` role, the [assistant](assistant.md#who-sees-it) backend as `assistant: { url }` when the app has one, and, for a caller with the `admin` role, the [runtime updates](versioning.md#runtime-updates) endpoint as `runtime: { url }` when the app has one, and, for everyone, the style of the record page's [maps](ui-config.md#maps) as `maps: { style }` when the app has one, the [language](languages.md) of its screens as `locale` when it sets one, and the Protobase version the server runs as `protobaseVersion`. When that version changes under an open page, the admin app keeps what the page shows, stops reading `/meta`, and offers to reload the page, asking first while a form holds unsaved changes or a save is under way. `conditional` lists the operations allowed only for some records (a row filter or a record-level rule decides). A view's sidebar group ([`nav.recent`](sidebar.md#recent-records)) is dropped when it uses a field they cannot read. The ETag hashes all of it, so it differs per user and per roles. The OpenAPI document is generated the same way: record and body schemas have only the readable and writable fields, and methods the caller may not use are left out. Its `servers` are relative to the document (`v1` for the resources, `.` for the system endpoints), and `/api/docs` loads `openapi.json` beside it, so both are right on any host and under any prefix the API is reached at.
|
|
111
|
+
`/meta` returns, per caller: the resources they can do anything with as restricted models (hidden fields absent, `readOnly` unless writable, [write-only](access.md#write-only-fields) fields marked `writeOnly`), the view for their roles ([`pickView`](https://docs.protobase.net/api/schema/functions/pickview/)) with every reference to a hidden field removed (columns, sort, search, filters, layout, chart, title, search result) and the [related sections](ui-config.md#related-records) they cannot use, `permissions[resource]` as `{ read, create, update, delete, conditional }`, the [user menu](user-menu.md) as `userMenu` and the [bottom bar](bottom-bar.md) of their active role as `bottomBar`, each without the resources and pages they cannot see, and the [composed pages](layouts.md#access) as `pages`, each without the elements that name what they cannot see or do, and, for a caller with the `admin` or `ai` role, the [assistant](assistant.md#who-sees-it) backend as `assistant: { url }` when the app has one, and, for a caller with the `admin` role, the [runtime updates](versioning.md#runtime-updates) endpoint as `runtime: { url }` when the app has one, and, for everyone, the style of the record page's [maps](ui-config.md#maps) as `maps: { style }` when the app has one, the [language](languages.md) of its screens as `locale` when it sets one, and the Protobase version the server runs as `protobaseVersion`. When that version changes under an open page, the admin app keeps what the page shows, stops reading `/meta`, and offers to reload the page, asking first while a form holds unsaved changes or a save is under way. `conditional` lists the operations allowed only for some records (a row filter or a record-level rule decides). A view's sidebar group ([`nav.recent`](sidebar.md#recent-records)) is dropped when it uses a field they cannot read. The ETag hashes all of it, so it differs per user and per roles. The OpenAPI document is generated the same way: record and body schemas have only the readable and writable fields, and methods the caller may not use are left out. Its `servers` are relative to the document (`v1` for the resources, `.` for the system endpoints), and `/api/docs` loads `openapi.json` beside it, so both are right on any host and under any prefix the API is reached at.
|
|
112
112
|
|
|
113
113
|
## Sensitive fields and audit
|
|
114
114
|
|
|
@@ -106,6 +106,7 @@ One process, one port: Vite serves the admin app from `@protobase/ui`'s `src/app
|
|
|
106
106
|
- **Database:** the URL comes from the variable named by `--env`, read from the environment or the nearest `.env` at or above the project. The connection is checked before anything starts; if it fails, the command names host, port and reason (and points to its `db:up` script when it has one). The project needs `pg` installed, because the API connects with Kysely over the project's own `pg`.
|
|
107
107
|
- **Cache:** Vite's dependency cache is `node_modules/.vite`; two dev servers sharing it can disturb each other's optimisation, so pass `--cache-dir` for a second one (the integration test does).
|
|
108
108
|
- **Login:** real sign-in only, with the `authenticate` and `auth` exported by `protobase.config.ts` (see [Login with Better Auth](auth.md)). A project without an authenticator fails at startup with a message pointing there, one whose auth schema is behind with the tables and columns it lacks (see [`auth migration`](#auth-migration)), and one with a resource whose [events](events.md) or [history](history.md) lack their triggers, or whose [comments](comments.md) lack their table, or whose [rollup and formula fields](data-config.md#rollups-and-formulas) lack their columns or triggers, which it checks again on every reload (see [`migration`](#migration)), and one with an [AI field or action](ai.md#the-model) and no model key; there is no development login. Create the first admin with `protobase users create`.
|
|
109
|
+
- **Mobile releases:** see [below](#mobile-releases).
|
|
109
110
|
- **Jobs:** with [jobs](jobs.md) in the config it runs them in its process, once the jobs schema checks out (see [`migration`](#migration)); an edited job runs its new code from the next job on.
|
|
110
111
|
- **Tunnels and other hosts:** Vite only answers `localhost` by default. `--allowed-hosts .trycloudflare.com,app.example.com` adds Host headers (a leading dot matches all subdomains). Hot reload needs no extra setting: the Vite client takes protocol, host and port from the page, so behind an HTTPS tunnel it connects over `wss` on 443 as long as the tunnel forwards WebSockets.
|
|
111
112
|
- **Project discovery**, by convention: `config/index.ts` exports the resources (and views), and every `config/*/ui.ts` export that is not already exported by the index is added as a view. Each `functions/<name>.ts` (or `functions/<name>/index.ts`) is an [API function](../guides/api-functions.md) at `/api/functions/<name>`. A `protobase.config.ts` in the project root replaces the convention; its default export may contain any of:
|
|
@@ -194,7 +195,9 @@ A token the [theme](theme.md) sets that the app does not read prints a `warning:
|
|
|
194
195
|
|
|
195
196
|
By default the bundle runs on Node and on Bun. `--bun` makes it a bundle for Bun only, as the Protobase images and the cloud serve it: Bun's bundler writes the config module (see [the config module](#the-config-module)), so the build needs `bun` on `PATH` and fails without it.
|
|
196
197
|
|
|
197
|
-
|
|
198
|
+
### Source maps
|
|
199
|
+
|
|
200
|
+
`--source-maps` writes a source map beside each script of the shell and the plugins, `assets/<name>-<hash>.js.map`, for an error tracker to read the browser's stack frames with. Each script ends with a `//# debugId=<uuid>` comment, and its map carries the same `debugId`; the scripts name no map, but a host serves the maps with the rest of `public/` unless it moves them out. The shell's maps come prebuilt in `@protobase/ui`'s `dist/shell-source-maps/`. Without the option the bundle has no maps. [`build-plugin --source-maps`](#build-plugin) does the same for a plugin built on its own.
|
|
198
201
|
|
|
199
202
|
### Extensions
|
|
200
203
|
|
|
@@ -221,6 +224,7 @@ By default the bundle runs on Node and on Bun. `--bun` makes it a bundle for Bun
|
|
|
221
224
|
{ "name": "app", "path": "plugins/app/plugin.json", "api": 1, "protobase": ">=0.12.0", "fields": { "steps": ["enum"] } }
|
|
222
225
|
],
|
|
223
226
|
"shell": { "protobase": "0.12.0", "pluginApi": 1, "paths": ["/index.html", "/assets", "/protobase.sw.js"] },
|
|
227
|
+
"native": { "@capacitor/core": "8.5.3", "@capacitor/ios": "8.5.3" },
|
|
224
228
|
"nodeModules": "node_modules",
|
|
225
229
|
"migrations": "migrations"
|
|
226
230
|
}
|
|
@@ -230,6 +234,7 @@ By default the bundle runs on Node and on Bun. `--bun` makes it a bundle for Bun
|
|
|
230
234
|
- `server`, `public`, `nodeModules` and `migrations` are relative to the bundle folder; `spa`, `theme` and each plugin's `path` to `public`.
|
|
231
235
|
- `plugins` are the bundle's own plugins, in the order the app merges them: the extensions', then the project's (`app`). Each names its `plugin.json`, the plugin API and Protobase versions it is built for, and the [field types](plugins.md#field-types) it registers with the storage types each shows, which the serve runtime checks the views against at startup. `/api/meta` names them to everyone, before any other plugin.
|
|
232
236
|
- `shell` is the admin app `public/` holds a copy of: its Protobase version and plugin API, and its files as URL paths. A host with a shell of its own, of a release every plugin of the bundle loads in, may serve its own for those paths instead (see [The UI](#the-ui)), so the app gets that release's fixes without a rebuild.
|
|
237
|
+
- `native` is the native packages, name to version, that `shell` runs on in the [mobile app](../guides/mobile-app.md): those `@protobase/mobile` pins. The fingerprint of the bundle's [mobile release](#mobile-releases) names them. A bundle built before it serves no mobile release.
|
|
233
238
|
- `theme` is the project's [theme](theme.md), which the app links at `/protobase.theme.css`. It is always there, empty when the project has none.
|
|
234
239
|
- `nodeModules` is present only when the config module imports [native packages](#native-packages). It is always the `node_modules` folder beside `server`, where Bun and Node resolve the module's imports from, and holds plain packages: JavaScript, `package.json` files and native binaries for linux x64 and arm64 (glibc), which the runtime loads with `dlopen`. A host keeps it next to the server module and must not mount it `noexec` (an add-on there then fails with `failed to map segment from shared object`). Its binaries link nothing but glibc, `libstdc++.so.6`, `libgcc_s.so.1` and libraries in the bundle itself, so the run image must have those three. Without `nodeModules`, the server module is the only file the runtime reads.
|
|
235
240
|
- `migrations` is present only when the project has a `db/migrations` folder: its `.sql` files, which the runtime's `migrate` applies (see [Deploy](../guides/deploy.md)). A host never serves it.
|
|
@@ -393,6 +398,7 @@ Serves the API of a bundle from `protobase build` and owns the process around it
|
|
|
393
398
|
| `PROTOBASE_STARTUP_CHECKS` | `false` skips the startup reads of the auth, changes, computed columns, webhooks and jobs schemas, which make a start slower; default `true`. Set it only to restart a bundle that already started on this database, such as when a platform wakes a sleeping app, never for a new bundle or after its migrations ran |
|
|
394
399
|
| `PROTOBASE_SHELL` | `protobase serve <bundle>` only: a shell folder, such as the `/opt/protobase/shell` of a protobase image or `@protobase/ui`'s `dist/shell`, to serve the bundle's app from (see [its own shell](#serve)) |
|
|
395
400
|
| `PROTOBASE_TRUSTED_PROXIES` | the proxies in front of the server, addresses or CIDR ranges, comma separated: a request from one of them names its client in `X-Forwarded-For`; without it the client is the connection's address ([Client addresses](auth.md#client-addresses)) |
|
|
401
|
+
| `PROTOBASE_MOBILE_SIGNING_KEY` | an RSA private key of at least 2048 bits, PEM, its newlines real or written `\n`, that signs every file of the [mobile release](#mobile-releases) in `X-Signature`, for an app whose updater checks signatures with the matching public key; another kind of key, or a shorter one, stops startup |
|
|
396
402
|
| `PROTOBASE_JOBS_DRAIN_TOKEN` | the operator's bearer token for `POST /api/jobs/drain`, which [runs the due jobs](jobs.md#hosts-that-sleep) of a host that lets the app sleep; without it there is no such endpoint |
|
|
397
403
|
|
|
398
404
|
Better Auth and other settings are the project's own variables (`BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, ...), read by its config. `protobase serve` also loads the nearest `.env`, like `dev`; the runtime takes the environment as it is.
|
|
@@ -406,6 +412,13 @@ Better Auth and other settings are the project's own variables (`BETTER_AUTH_SEC
|
|
|
406
412
|
- **Host modules:** under Bun, the runtime registers [the modules it supplies](#the-config-module) as virtual modules, so the bundle needs no `node_modules` for them. `protobase serve`, on Node or Bun, resolves them from the `node_modules` next to the bundle, so keep the bundle inside the project. Native packages load from the bundle's own `node_modules/` under both.
|
|
407
413
|
- **Read-only hosts:** nothing is written: no install (`--no-install`), and for a bundle built with `--bun` no transpiling and so no transpiler cache. A bundle with `node_modules/` needs its folder mounted without `noexec`, since its add-ons are mapped as executable code.
|
|
408
414
|
|
|
415
|
+
### Mobile releases
|
|
416
|
+
|
|
417
|
+
With a `mobile` section, the server serves the [mobile app](../guides/mobile-app.md) a newer copy of its files, for its live updater, so the app gets UI changes without a store release. The release is what the server serves the web, composed at startup: every file of `public/`, with the server's own shell where `protobase serve` uses it, and `index.html` naming the API origin, the auth `baseURL` (https, or plain http to `localhost`, `127.0.0.1` or `[::1]`). There is none when the server serves the API alone, has no such `baseURL`, or the bundle names no `native`.
|
|
418
|
+
|
|
419
|
+
- `GET /api/mobile/release?fingerprint=<native fingerprint>&shell_version=<x.y.z>` answers `{ "bundleId", "url", "required" }`: the release's id, a hash of its files, and its absolute base URL, both `null` when the release does not run on the asking binary, whose native fingerprint must equal the release's. `required` is true when the shell the app runs no longer works with the server's API: below 1.0 another minor, from 1.0 another major. A missing fingerprint or a shell version that is no x.y.z version gets 400.
|
|
420
|
+
- `GET /api/mobile/releases/<bundleId>?href=<file>` serves the release's file `<file>`, such as `assets/index-abc123.js`, and with `href=capawesome-live-update-manifest.json` its manifest, a JSON array of `{ "href", "checksum", "sizeInBytes" }`. Each comes with its sha256 in hex in `X-Checksum` and, with `PROTOBASE_MOBILE_SIGNING_KEY`, its signature in `X-Signature`. Any other file, or another release's id, gets 404.
|
|
421
|
+
|
|
409
422
|
## `worker`
|
|
410
423
|
|
|
411
424
|
```sh
|
|
@@ -538,7 +551,8 @@ Builds the project in the current directory as an iOS or Android app with Capaci
|
|
|
538
551
|
- `build` makes a signed release, an `.aab` (Android) or `.ipa` (iOS), and copies it to `--out`, which ignores itself in git when the command creates it, as `<appId>-<version>-<build number>`. Android signs through Gradle with the keystore, alias and passwords in `PROTOBASE_ANDROID_KEYSTORE`, `PROTOBASE_ANDROID_KEY_ALIAS`, `PROTOBASE_ANDROID_KEYSTORE_PASSWORD` and `PROTOBASE_ANDROID_KEY_PASSWORD`; iOS runs Capacitor's build with `--team`, and `--certificate` with `--profile` for manual signing.
|
|
539
552
|
- A release calls an https server that is not this machine, and `--app-version` (one to three numbers) and `--build-number` (1 to 2100000000) are required.
|
|
540
553
|
- npm and Capacitor get the CLI's environment without any variable named in the current directory's `.env*` files, nor the four `PROTOBASE_ANDROID_*` signing variables, which only Gradle gets, and with `CI=true`, which keeps Capacitor's telemetry off.
|
|
541
|
-
- It prints the workspace, the API origin and the native fingerprint, which the app also sends in its user agent as `ProtobaseNative/<fingerprint>`: a hash of the `@protobase/mobile`
|
|
554
|
+
- It prints the workspace, the API origin and the native fingerprint, which the app also sends in its user agent as `ProtobaseNative/<fingerprint>`: a hash of the native packages `@protobase/mobile` pins, at their versions, and the section's `plugins`, at the versions they give. A [mobile release](#mobile-releases) runs only on a binary of its own fingerprint. A Protobase release that pins the same native packages keeps it; raise a plugin's version when the app's files start using a newer native feature of it, which changes it.
|
|
555
|
+
- The app's files carry the live updater's manifest of them, so an update downloads only the files that changed.
|
|
542
556
|
|
|
543
557
|
## `token`
|
|
544
558
|
|
|
@@ -60,7 +60,7 @@ export const repairs = resource('repairs')
|
|
|
60
60
|
| `.primaryKey((r) => r.id)` | The key, one field or a list (`(r) => [r.order_id, r.line_no]`). Required; records are addressed by it. |
|
|
61
61
|
| `.softDelete((r) => r.deleted_at)` | A nullable timestamp or date: deleting sets it, lists leave such rows out, `:undelete` clears it. See [REST API](api.md#routes). |
|
|
62
62
|
| `.tenant((r) => r.organization_id)` | The column that separates tenants: every query is limited to the caller's tenant, creates set it, and a request body may not. |
|
|
63
|
-
| `.owner((r) => r.owner_id)` | The field holding the owning user's id, which `.own` capabilities filter on (see [Access](#access)). |
|
|
63
|
+
| `.owner((r) => r.owner_id)` | The field holding the owning user's id, which `.own` and `.team` capabilities filter on (see [Access](#access)). The server does not start when its column cannot hold the signed-in users' ids, such as an integer column with Better Auth's text ids; see [user ids](auth.md#roles-and-access-in-the-api). |
|
|
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
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). |
|
|
@@ -70,7 +70,7 @@ export const repairs = resource('repairs')
|
|
|
70
70
|
| `.history()` | Keeps every change of its records with who made it, shown on the record page and listed for admins as Activity. See [Record history](history.md). |
|
|
71
71
|
| `.comments()` | Lets whoever may read a record comment on it and @mention others who may, who are emailed; shown on the record page and listed for admins. See [Record comments](comments.md). |
|
|
72
72
|
|
|
73
|
-
Field and resource names are snake_case by convention, like the columns: they are the names in URLs, the API, filters and sorts as written (`/stock_moves?order_by=moved_at desc`). The column is the snake_case of the name unless `.column()` says otherwise, so a camelCase name such as `movedAt` maps to `moved_at` too.
|
|
73
|
+
Field and resource names are snake_case by convention, like the columns: they are the names in URLs, the API, filters and sorts as written (`/stock_moves?order_by=moved_at desc`). The column is the snake_case of the name unless `.column()` says otherwise, so a camelCase name such as `movedAt` maps to `moved_at` too. [`protobase scaffold`](cli.md#scaffold) writes snake_case names, and the built-in resources, such as `failed_jobs` and `webhook_subscriptions`, have them too. Nothing checks the convention: a resource or field may have any name.
|
|
74
74
|
|
|
75
75
|
## Field types
|
|
76
76
|
|
|
@@ -198,7 +198,7 @@ Empty values of `field` are left out, as in SQL. The migration adds the column,
|
|
|
198
198
|
|
|
199
199
|
`.formula(expression)` is a Postgres generated column. The expression reads the record's number fields, and takes numbers, `+ - * /`, parentheses, `coalesce(a, b, ...)` and `round(x)` or `round(x, digits)`. It is computed exactly as decimals, so `7 / 2` is 3.5, and is stored as the field's type, so an integer field rounds the result. A formula that reads an optional field is `.optional()` too, unless `coalesce()` gives that field a value. A formula cannot read another formula. When the expression changes, the migration drops the column and adds it again, so an index on it must be created again in the same migration.
|
|
200
200
|
|
|
201
|
-
Neither field can be written through the API, have a default, or be sensitive. The server does not start while a declared column, function or trigger is missing or out of date, with a message that names the fields; the migration fixes that. It stops with an error, without writing anything, when the column already exists as the project's own: a plain column where a formula is declared, a generated column it did not write, or a rollup column of another type.
|
|
201
|
+
Neither field can be written through the API, have a default, or be sensitive, an AI field, a file, or the key, tenant, owner or soft delete field, and a formula cannot read a sensitive field. The server does not start while a declared column, function or trigger is missing or out of date, with a message that names the fields; the migration fixes that. It stops with an error, without writing anything, when the column already exists as the project's own: a plain column where a formula is declared, a generated column it did not write, or a rollup column of another type.
|
|
202
202
|
|
|
203
203
|
## Sensitive fields
|
|
204
204
|
|
|
@@ -310,12 +310,16 @@ export const partOrders = resource('part_orders')
|
|
|
310
310
|
|
|
311
311
|
A relation's value in the API is the other record's key. The admin shows the other record's name instead (its view's `title`, else a field such as `name` or `number`) and links to it. The create form and the record's form pick it from a list, with a link beside it on the record's form; a relation the user may not change, the record's own key and a relation to a record with a key of several columns stay links.
|
|
312
312
|
|
|
313
|
+
## Schema API reference
|
|
314
|
+
|
|
315
|
+
Every builder, option and type that `@protobase/schema` exports has a doc comment, which your editor shows as you write a config, and the [schema API reference](https://docs.protobase.net/api/schema/) lists them with their types. The types the builders return, such as [`ResourceBuilder`](https://docs.protobase.net/api/schema/interfaces/resourcebuilder/), [`Field`](https://docs.protobase.net/api/schema/interfaces/field/) and [`RecordOf`](https://docs.protobase.net/api/schema/type-aliases/recordof/), are exported, so a helper of your own that takes or returns them is typed too.
|
|
316
|
+
|
|
313
317
|
## Access
|
|
314
318
|
|
|
315
319
|
Without rules everyone who can sign in may do everything. Rules come in three kinds, and the [Access](access.md) reference explains the defaults:
|
|
316
320
|
|
|
317
321
|
- **Per operation** (`list`, `read`, `create`, `update`, `delete`): `.access({ update: rule })`. A rule returns `true`, `false`, or an AIP-160 filter that limits the rows, like row-level security. A rule that reads the record (`record.status`) is checked against the stored row.
|
|
318
|
-
- **Per row**: a filter from a rule, or a `.own` capability with `.owner(...)`.
|
|
322
|
+
- **Per row**: a filter from a rule, or a `.own` or `.team` capability with `.owner(...)`: `.own` gives the records whose owner is the user, `.team` those owned by the users that `defineRoles(roles, { teamOf: (user) => ids })` returns for them.
|
|
319
323
|
- **Per field**: `.access({ read, create, update })` on the field. Field rules see only the user, never a record, so the fields a user can read are the same for every row.
|
|
320
324
|
|
|
321
325
|
[`defineRoles`](https://docs.protobase.net/api/schema/functions/defineroles/) turns roles into capabilities (`work_orders.update.own`, `money.read`, `*`), and `roles.can(...)` and `roles.is(...)` make rules of them; `.and()` and `.or()` combine rules.
|
|
@@ -88,4 +88,8 @@ The app sends the signed-in user's API token as `Authorization: Bearer <token>`
|
|
|
88
88
|
It may also send `updateStage` (`job` or `build`) and `updateStartedAt` while an update runs, and `lastUpdate`, `{ toVersion, outcome, errorCode, message, finishedAt }` with `outcome` one of `succeeded`, `unchanged` or `failed` and `message` plain text for the app's owner. A host that leaves them out gets the dialog without them.
|
|
89
89
|
- `POST {url}/update`: applies `latest` now, `202` with the same body; `409` when the app is on it already or an update is running. A refusal's message, as `{ error: { code, message } }` or a problem's `detail`, is shown as it is.
|
|
90
90
|
|
|
91
|
-
The app reads the status on load and every half hour, every 5 seconds while an update runs. It shows the button only while `updateAvailable` and `indicator` are both true; the button opens the two versions, when the policy updates or how far the running update is, how the last update ended, and **Update now**. When and whether to update is the host's setting.
|
|
91
|
+
The app reads the status on load and every half hour, every 5 seconds while an update runs. It shows the button only while `updateAvailable` and `indicator` are both true; the button opens the two versions, when the policy updates or how far the running update is, how the last update ended, and **Update now**. When and whether to update is the host's setting. `createRuntimeClient({ url, token })` of `@protobase/client` calls the same endpoint from code, with `status()` and `update()`.
|
|
92
|
+
|
|
93
|
+
## A new version under an open page
|
|
94
|
+
|
|
95
|
+
`/api/meta` names the Protobase version the server runs as `protobaseVersion`. When a page that is open finds that the server moved to another version, it keeps what it shows and stops reading `/api/meta`, so nothing changes under the user until they reload. The app then offers the reload: in a sidebar shown at full width, a banner above the profile with the app's name, that it was updated, and a click that reloads; otherwise a notice with **Reload**, which stays until it is closed, and a **Reload page** button in the top bar. The reload asks first while a form holds unsaved changes or a save is under way.
|