@protobase/cli 0.47.0 → 0.48.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.
Files changed (45) hide show
  1. package/dist/build/config-bundle.js +2 -2
  2. package/dist/build/plugin-build.js +2 -2
  3. package/dist/build/serve-runtime.js +1 -1
  4. package/dist/build/shell.js +2 -2
  5. package/dist/cli/package.js +1 -1
  6. package/dist/dev/api-child.js +50 -0
  7. package/dist/dev/api-forward.js +70 -0
  8. package/dist/dev/api-process.d.ts +19 -0
  9. package/dist/dev/api-process.js +80 -0
  10. package/dist/dev/api-support.d.ts +3 -0
  11. package/dist/dev/api-support.js +3 -0
  12. package/dist/dev/api-vite.d.ts +9 -0
  13. package/dist/dev/api-vite.js +33 -0
  14. package/dist/dev/api-websockets.js +1 -23
  15. package/dist/dev/app-server.js +70 -0
  16. package/dist/dev/auth-drift-lines.js +8 -0
  17. package/dist/dev/dev-jobs.d.ts +6 -0
  18. package/dist/dev/entry.d.ts +5 -0
  19. package/dist/dev/entry.js +8 -2
  20. package/dist/dev/run.js +36 -94
  21. package/dist/dev/server-package.js +39 -0
  22. package/dist/encryption/register.js +7 -6
  23. package/dist/files/register.js +5 -2
  24. package/dist/main.js +6 -3
  25. package/dist/migration/register.js +4 -4
  26. package/dist/mobile/register.js +3 -4
  27. package/dist/notifications/print-vapid-keys.js +1 -1
  28. package/dist/organizations/register.js +6 -1
  29. package/dist/project/api-websocket-server.d.ts +9 -0
  30. package/dist/project/extensions.d.ts +8 -0
  31. package/dist/project/favicon-link.js +1 -1
  32. package/dist/project/load-data-config.js +1 -1
  33. package/dist/scaffold/plan.js +7 -3
  34. package/dist/scaffold/protobase-tables.js +8 -13
  35. package/dist/scaffold/run.js +1 -1
  36. package/dist/serve/lifecycle.js +3 -2
  37. package/dist/skill/register.js +1 -1
  38. package/dist/users/register.js +4 -3
  39. package/dist/users/set-disabled.js +1 -1
  40. package/package.json +7 -7
  41. package/skills/protobase/references/features/sign-in-and-accounts.md +1 -0
  42. package/skills/protobase/references/guides/deploy.md +1 -1
  43. package/skills/protobase/references/reference/auth.md +16 -12
  44. package/skills/protobase/references/reference/cli.md +9 -7
  45. package/skills/protobase/references/reference/mcp.md +1 -1
package/dist/dev/run.js CHANGED
@@ -1,59 +1,18 @@
1
1
  import { loadNearestEnvFile } from "./env.js";
2
- import { adminAppDir, adminAppMain, uiPackageDir } from "../project/admin-app.js";
3
- import { extensionImports, extensionStyles } from "../project/extensions.js";
4
- import { stopDevJobs } from "./dev-jobs.js";
5
- import { frameHeaders } from "../serve/static-site.js";
6
- import { projectUiPlugin } from "../project/project-ui.js";
7
- import { sharedModulesPlugin } from "../project/shared-modules.js";
8
- import { moduleFile } from "../module-file.js";
9
- import { layoutCheck } from "../build/layout-check.js";
10
- import { faviconLink } from "../project/favicon-link.js";
11
- import { themeLink } from "../project/theme-link.js";
2
+ import { adminAppDir, adminAppMain } from "../project/admin-app.js";
3
+ import { alsoOnIpv6, checkPortFree } from "./loopback.js";
12
4
  import { checkDatabase } from "./check-database.js";
13
- import { alsoOnIpv6, checkPortFree, devHost } from "./loopback.js";
5
+ import { authDriftLines } from "./auth-drift-lines.js";
14
6
  import { loginLine } from "./login-line.js";
15
- import { startupLogger } from "./startup-logger.js";
16
- import { isProjectFile } from "./project-files.js";
17
- import { apiWebSockets } from "./api-websockets.js";
7
+ import { apiForward } from "./api-forward.js";
8
+ import { forkApiChild } from "./api-child.js";
18
9
  import { existsSync } from "node:fs";
19
10
  import path from "node:path";
20
- import tailwindcss from "@tailwindcss/vite";
21
- import react from "@vitejs/plugin-react";
22
- import { createServer, searchForWorkspaceRoot } from "vite";
23
- import devServer from "@hono/vite-dev-server";
24
11
  //#region src/dev/run.ts
25
- const entry = moduleFile("./entry", import.meta.url);
26
12
  const requireAppFiles = (appDir) => {
27
13
  const missing = ["index.html", adminAppMain].filter((file) => !existsSync(path.join(appDir, file)));
28
14
  if (missing.length > 0) throw new Error(`The admin app is missing ${missing.join(", ")} in ${appDir}; \`protobase dev\` serves the app from there`);
29
15
  };
30
- const reloadOnProjectChange = (dirs) => ({
31
- name: "protobase-project-reload",
32
- handleHotUpdate: ({ file, server }) => {
33
- if (isProjectFile(dirs, file)) server.environments.ssr.moduleGraph.invalidateAll();
34
- }
35
- });
36
- const stopJobsOnClose = {
37
- name: "protobase-jobs",
38
- closeBundle: () => stopDevJobs()
39
- };
40
- const appDependencies = [
41
- "react",
42
- "react/jsx-runtime",
43
- "react/jsx-dev-runtime",
44
- "react-dom",
45
- "react-dom/client",
46
- "lucide-react",
47
- "zod",
48
- "@tanstack/react-query",
49
- "@tanstack/react-table",
50
- "recharts",
51
- "@sentry/browser",
52
- "maplibre-gl",
53
- "pmtiles",
54
- "fflate",
55
- "react-map-gl/maplibre"
56
- ];
57
16
  const runDev = async (options, out) => {
58
17
  loadNearestEnvFile(options.projectDir);
59
18
  const url = process.env[options.envVar];
@@ -63,65 +22,48 @@ const runDev = async (options, out) => {
63
22
  await checkDatabase(url, options.projectDir);
64
23
  if (options.port !== 0) await checkPortFree(options.port);
65
24
  const extensions = options.extensions ?? [];
66
- const projectDirs = [options.projectDir, ...extensions.map((extension) => extension.dir)];
67
25
  process.env.PROTOBASE_PROJECT = options.projectDir;
68
26
  process.env.PROTOBASE_EXTENSIONS = JSON.stringify(extensions);
69
27
  process.env.PROTOBASE_DATABASE_URL = url;
70
- const logging = startupLogger();
71
- const server = await createServer({
72
- root: appDir,
73
- configFile: false,
74
- customLogger: logging.logger,
75
- ...options.cacheDir && { cacheDir: options.cacheDir },
76
- optimizeDeps: {
77
- include: appDependencies,
78
- exclude: ["@protobase/ui"]
79
- },
80
- server: {
81
- headers: frameHeaders,
82
- host: devHost,
83
- port: options.port,
84
- strictPort: true,
85
- ...options.allowedHosts.length > 0 && { allowedHosts: options.allowedHosts },
86
- fs: { allow: [
87
- searchForWorkspaceRoot(options.projectDir),
88
- uiPackageDir,
89
- options.projectDir,
90
- ...extensions.map((extension) => extension.dir)
91
- ] }
92
- },
93
- plugins: [
94
- reloadOnProjectChange(projectDirs),
95
- apiWebSockets(entry, projectDirs),
96
- stopJobsOnClose,
97
- sharedModulesPlugin(),
98
- themeLink(options.projectDir),
99
- faviconLink(options.projectDir),
100
- projectUiPlugin(options.projectDir, extensions),
101
- extensionImports(options.projectDir, extensions),
102
- extensionStyles(extensions),
103
- layoutCheck(),
104
- react(),
105
- tailwindcss(),
106
- devServer({
107
- entry,
108
- exclude: [/^(?!\/api(\/|\?|$)|\/\.well-known\/webauthn(\?|$)|\/\.well-known\/oauth-(authorization-server|protected-resource)(\/|\?|$)|\/protobase\.sw\.js(\?|$)).*/],
109
- injectClientScript: false
110
- })
111
- ]
28
+ const onApiExit = (code) => {
29
+ process.stderr.write(`error: the API process of protobase dev ended with exit code ${code}\n`);
30
+ server.close().then(() => process.exit(code || 1));
31
+ };
32
+ const apiChild = forkApiChild({
33
+ projectDir: options.projectDir,
34
+ extensions,
35
+ ...options.cacheDir && { cacheDir: path.join(options.cacheDir, "api") }
36
+ }, onApiExit);
37
+ let apiReady = () => void 0;
38
+ const api = new Promise((resolve) => {
39
+ apiReady = resolve;
112
40
  });
41
+ const stopApiOnClose = {
42
+ name: "protobase-api-process",
43
+ closeBundle: () => apiChild.stop()
44
+ };
45
+ const stopApiAndThrow = async (error) => {
46
+ await apiChild.stop();
47
+ throw error;
48
+ };
49
+ const { createAppServer } = await import("./app-server.js");
50
+ const server = await createAppServer({
51
+ ...options,
52
+ appDir,
53
+ extensions
54
+ }, [apiForward(() => api.then((child) => child.port)), stopApiOnClose]).catch(stopApiAndThrow);
113
55
  const closeAndThrow = async (error) => {
114
56
  await server.close();
115
57
  throw error;
116
58
  };
117
- await server.listen();
59
+ await server.listen().catch(closeAndThrow);
118
60
  const address = server.httpServer?.address();
119
61
  const port = typeof address === "object" && address ? address.port : options.port;
120
62
  if (server.httpServer) await alsoOnIpv6(server.httpServer, port).catch(closeAndThrow);
121
- process.env.PROTOBASE_DEV_URL = `http://localhost:${port}`;
122
- const anyUsers = await (await server.ssrLoadModule(entry).catch(closeAndThrow)).anyUsers().catch(closeAndThrow);
123
- logging.started();
124
- out(`protobase dev ready at http://localhost:${port}\n project ${options.projectDir}\n api http://localhost:${port}/api/v1 (docs at /api/docs)\n` + loginLine(anyUsers, process.env.npm_config_user_agent));
63
+ const started = await apiChild.start(`http://localhost:${port}`).catch(closeAndThrow);
64
+ apiReady(started);
65
+ const { anyUsers, authDrift } = started;
66
+ out(`protobase dev ready at http://localhost:${port}\n project ${options.projectDir}\n api http://localhost:${port}/api/v1 (docs at /api/docs)\n` + loginLine(anyUsers, process.env.npm_config_user_agent) + authDriftLines(authDrift));
125
67
  return server;
126
68
  };
127
69
  //#endregion
@@ -0,0 +1,39 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ //#region src/dev/server-package.ts
5
+ const server = "@protobase/server";
6
+ const framework = [
7
+ "@protobase/layout",
8
+ "@protobase/query",
9
+ "@protobase/schema",
10
+ server
11
+ ];
12
+ const dependencyFields = [
13
+ "dependencies",
14
+ "devDependencies",
15
+ "optionalDependencies",
16
+ "peerDependencies"
17
+ ];
18
+ const cliDir = fileURLToPath(new URL("../..", import.meta.url));
19
+ /**
20
+ * Where the API of `protobase dev` gets @protobase/server: from the project's node_modules when its package.json lists
21
+ * it, so a project that is not installed fails as any missing package does; otherwise, with no package.json or one
22
+ * without it, the CLI's own, with the CLI's other framework packages.
23
+ */
24
+ const serverPackage = (projectDir, ownDir = cliDir) => {
25
+ const file = path.join(projectDir, "package.json");
26
+ const manifest = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
27
+ if (dependencyFields.some((field) => manifest[field]?.[server] !== void 0)) return {
28
+ from: "project",
29
+ root: projectDir,
30
+ dedupe: [server]
31
+ };
32
+ return {
33
+ from: "cli",
34
+ root: ownDir,
35
+ dedupe: framework
36
+ };
37
+ };
38
+ //#endregion
39
+ export { serverPackage };
@@ -1,6 +1,3 @@
1
- import { printStatus } from "./print-status.js";
2
- import { printApply } from "./print-apply.js";
3
- import { rebindOption } from "./rebind-option.js";
4
1
  //#region src/encryption/register.ts
5
2
  const out = (text) => void process.stdout.write(text);
6
3
  const bundleArgument = ["[bundle]", "a bundle from `protobase build` (its folder or config module); default: the project in the current directory"];
@@ -20,10 +17,14 @@ const withTools = async (bundle, work) => {
20
17
  };
21
18
  const registerEncryption = (program) => {
22
19
  const encryption = program.command("encryption").description("Check and update the stored values of encrypted fields");
23
- encryption.command("status").description("Count each encrypted field's values by key, list plaintext and unreadable ones and old values left in history; exits 1 when any need work").argument(...bundleArgument).action((bundle) => withTools(bundle, async (tools) => printStatus(await tools.status(), out)));
24
- encryption.command("apply").description("Encrypt plaintext values, move values to the current key, rebind renamed ones and remove old values from history; exits 1 when unreadable values remain").argument(...bundleArgument).option("--rebind <resource[.field]>", "rebind the values of a resource, or one field, sealed before a rename").option("--from-table <table>", "the table, as .table() named it, the values were in before").option("--from-column <column>", "the column the field's values were in before").action((bundle, flags) => {
20
+ encryption.command("status").description("Count each encrypted field's values by key, list plaintext and unreadable ones and old values left in history; exits 1 when any need work").argument(...bundleArgument).action(async (bundle) => {
21
+ const { printStatus } = await import("./print-status.js");
22
+ await withTools(bundle, async (tools) => printStatus(await tools.status(), out));
23
+ });
24
+ encryption.command("apply").description("Encrypt plaintext values, move values to the current key, rebind renamed ones and remove old values from history; exits 1 when unreadable values remain").argument(...bundleArgument).option("--rebind <resource[.field]>", "rebind the values of a resource, or one field, sealed before a rename").option("--from-table <table>", "the table, as .table() named it, the values were in before").option("--from-column <column>", "the column the field's values were in before").action(async (bundle, flags) => {
25
+ const [{ rebindOption }, { printApply }] = await Promise.all([import("./rebind-option.js"), import("./print-apply.js")]);
25
26
  const rebind = rebindOption(flags);
26
- return withTools(bundle, async (tools) => {
27
+ await withTools(bundle, async (tools) => {
27
28
  out(`Encrypting with key ${tools.kid}\n`);
28
29
  return printApply(await tools.apply(rebind ? { rebind } : {}), out);
29
30
  });
@@ -1,9 +1,12 @@
1
- import { cleanupCommand } from "./cleanup-command.js";
2
1
  //#region src/files/register.ts
3
2
  const out = (text) => process.stdout.write(text);
4
3
  const registerFiles = (program) => {
5
4
  program.command("files").description("Manage the stored files of the project in the current directory").command("cleanup").description("Delete the files whose scheduled delete is due and that no row references, such as replaced files and unused uploads").argument("[bundle]", "a bundle from `protobase build` (its folder or config module); default: the project in the current directory").action(async (bundle) => {
6
- const [{ createFileCleanup }, { loadBundleProject }] = await Promise.all([import("@protobase/server"), import("../project/load-bundle-project.js")]);
5
+ const [{ createFileCleanup }, { loadBundleProject }, { cleanupCommand }] = await Promise.all([
6
+ import("@protobase/server"),
7
+ import("../project/load-bundle-project.js"),
8
+ import("./cleanup-command.js")
9
+ ]);
7
10
  const project = await loadBundleProject(bundle, process.cwd());
8
11
  try {
9
12
  const cleanup = createFileCleanup(project);
package/dist/main.js CHANGED
@@ -2,7 +2,6 @@ import { registerAuth } from "./auth/register.js";
2
2
  import { isConnectionString, resolveConnectionUrl } from "./db/connection-url.js";
3
3
  import { parseHosts } from "./dev/hosts.js";
4
4
  import { loadNearestEnvFile } from "./dev/env.js";
5
- import { resolveExtensions } from "./project/extensions.js";
6
5
  import { placeholderSecretWarning } from "./project/placeholder-secret.js";
7
6
  import { registerOrganizations } from "./organizations/register.js";
8
7
  import { registerFiles } from "./files/register.js";
@@ -61,7 +60,7 @@ program.command("doctor").description("Check a config folder against the databas
61
60
  if (errors > 0) process.exitCode = 1;
62
61
  });
63
62
  program.command("dev").description("Serve the admin app and API for the project in the current directory").option("--port <port>", "port for the app and API", "5173").option("--env <variable>", "environment variable holding the database URL", "DATABASE_URL").option("--allowed-hosts <hosts>", "extra Host headers to accept, comma separated; a leading dot matches subdomains (.trycloudflare.com)").option("--cache-dir <dir>", "Vite's dependency cache, so parallel dev servers do not share one").option("--extend <dir>", "merge the protobase.config.ts and protobase.ui.tsx in this folder before the project's, repeatable", collect, []).action(async (opts) => {
64
- const { runDev } = await import("./dev/run.js");
63
+ const [{ runDev }, { resolveExtensions }] = await Promise.all([import("./dev/run.js"), import("./project/extensions.js")]);
65
64
  const server = await runDev({
66
65
  extensions: resolveExtensions(opts.extend),
67
66
  port: Number(opts.port),
@@ -75,9 +74,13 @@ program.command("dev").description("Serve the admin app and API for the project
75
74
  process.once("SIGTERM", () => void server.close().then(() => process.exit(0)));
76
75
  });
77
76
  program.command("build").description("Build the deploy bundle of the project in the current directory: its config module, the admin app with the project's UI as a plugin, and the manifest").option("--out <dir>", "output folder", "dist").option("--bun", "have Bun's bundler write the config module, for a bundle only Bun serves (needs bun on PATH)", false).option("--extend <dir>", "merge the protobase.config.ts and protobase.ui.tsx in this folder before the project's, repeatable", collect, []).option("--source-maps", "end each script with a //# debugId= comment and write its source map, carrying the same id, beside it", false).action(async (opts) => {
77
+ const [{ buildDeployBundle }, { manifestFile }, { resolveExtensions }] = await Promise.all([
78
+ import("./build/deploy-bundle.js"),
79
+ import("./bundle/manifest.js"),
80
+ import("./project/extensions.js")
81
+ ]);
78
82
  const extensions = resolveExtensions(opts.extend);
79
83
  const onWarning = (message) => process.stderr.write(`warning: ${message}\n`);
80
- const [{ buildDeployBundle }, { manifestFile }] = await Promise.all([import("./build/deploy-bundle.js"), import("./bundle/manifest.js")]);
81
84
  const manifest = await buildDeployBundle({
82
85
  projectDir: process.cwd(),
83
86
  outDir: path.resolve(opts.out),
@@ -1,15 +1,15 @@
1
- import { resolveExtensions } from "../project/extensions.js";
2
- import { migrationSummary } from "./summary.js";
3
1
  import path from "node:path";
4
2
  //#region src/migration/register.ts
5
3
  const out = (text) => process.stdout.write(text);
6
4
  const collect = (value, previous) => [...previous, value];
7
5
  const registerMigration = (program) => {
8
6
  program.command("migration").description("Write what the database still needs for every feature the config enables (auth, events, jobs) as the project's next SQL migrations").option("--dir <dir>", "migrations folder", "db/migrations").option("--extend <dir>", "merge the protobase.config.ts in this folder before the project's, as dev and build do, repeatable", collect, []).action(async (opts) => {
9
- const [{ loadMigrationProject }, { migrationParts }, { writeMigrations }] = await Promise.all([
7
+ const [{ loadMigrationProject }, { migrationParts }, { writeMigrations }, { migrationSummary }, { resolveExtensions }] = await Promise.all([
10
8
  import("./load-project.js"),
11
9
  import("./parts.js"),
12
- import("./write-migrations.js")
10
+ import("./write-migrations.js"),
11
+ import("./summary.js"),
12
+ import("../project/extensions.js")
13
13
  ]);
14
14
  const project = await loadMigrationProject(process.cwd(), resolveExtensions(opts.extend));
15
15
  try {
@@ -1,4 +1,3 @@
1
- import { resolveExtensions } from "../project/extensions.js";
2
1
  import { parseAppVersion, parseBuildNumber, parsePlatform, parsePort, parseSigningName, parseTeamId } from "./arguments.js";
3
2
  import path from "node:path";
4
3
  //#region src/mobile/register.ts
@@ -10,7 +9,7 @@ const registerMobile = (program) => {
10
9
  const apiHelp = "the server the app calls (default: the auth issuer, the project's baseURL)";
11
10
  const extend = "merge the protobase.config.ts and protobase.ui.tsx in this folder before the project's, repeatable";
12
11
  mobile.command("run").description("Generate the native project and run the app in a simulator, an emulator or on a device").argument("<platform>", "ios or android", parsePlatform).option(api, apiHelp).option("--target <id>", "the device or simulator to run on (default: Capacitor asks)").option("--team <id>", "iOS: your Apple Developer team id, which signs the app to run on your iPhone", parseTeamId).option("--live", "open the running protobase dev instead of the app's own files, reloading as you save", false).option("--port <port>", "the port of protobase dev, for --live", parsePort, 5173).option("--extend <dir>", extend, collect, []).action(async (chosen, opts) => {
13
- const { mobileRun } = await import("./run.js");
12
+ const [{ mobileRun }, { resolveExtensions }] = await Promise.all([import("./run.js"), import("../project/extensions.js")]);
14
13
  await mobileRun({
15
14
  projectDir: process.cwd(),
16
15
  platform: chosen,
@@ -22,7 +21,7 @@ const registerMobile = (program) => {
22
21
  }, out);
23
22
  });
24
23
  mobile.command("open").description("Generate the native project and open it in Xcode or Android Studio").argument("<platform>", "ios or android", parsePlatform).option(api, apiHelp).option("--extend <dir>", extend, collect, []).action(async (chosen, opts) => {
25
- const { mobileOpen } = await import("./run.js");
24
+ const [{ mobileOpen }, { resolveExtensions }] = await Promise.all([import("./run.js"), import("../project/extensions.js")]);
26
25
  await mobileOpen({
27
26
  projectDir: process.cwd(),
28
27
  platform: chosen,
@@ -33,7 +32,7 @@ const registerMobile = (program) => {
33
32
  mobile.command("build").description("Generate the native project and build a signed release: an .aab for Google Play, an .ipa for the App Store").argument("<platform>", "ios or android", parsePlatform).requiredOption("--app-version <version>", "the version the stores show, such as 1.2.3", parseAppVersion).requiredOption("--build-number <number>", "the build number, higher with each upload", parseBuildNumber).option(api, `${apiHelp}; https only`).option("--out <dir>", "the folder the binary goes to", "mobile-release").option("--team <id>", "iOS: your Apple Developer team id", parseTeamId).option("--certificate <name>", "iOS, manual signing: the signing certificate", parseSigningName).option("--profile <name>", "iOS, manual signing: the provisioning profile", parseSigningName).option("--extend <dir>", extend, collect, []).action(async (chosen, opts) => {
34
33
  if (chosen === "android" && (opts.team || opts.certificate || opts.profile)) throw new Error("--team, --certificate and --profile are for iOS: Android signs with the PROTOBASE_ANDROID_* variables");
35
34
  if (Boolean(opts.certificate) !== Boolean(opts.profile)) throw new Error("Manual signing takes both --certificate and --profile");
36
- const { mobileBuild } = await import("./build.js");
35
+ const [{ mobileBuild }, { resolveExtensions }] = await Promise.all([import("./build.js"), import("../project/extensions.js")]);
37
36
  const projectDir = process.cwd();
38
37
  await mobileBuild({
39
38
  projectDir,
@@ -1,4 +1,4 @@
1
- import { generateVapidKeys, vapidPrivateKeyVariable, vapidPublicKeyVariable, vapidSubjectVariable } from "@protobase/server";
1
+ import { generateVapidKeys, vapidPrivateKeyVariable, vapidPublicKeyVariable, vapidSubjectVariable } from "@protobase/server/vapid";
2
2
  //#region src/notifications/print-vapid-keys.ts
3
3
  /**
4
4
  * Prints a fresh VAPID key pair as the two environment variables Web Push reads, and on `note` how to set the third.
@@ -1,4 +1,3 @@
1
- import { addAppRoleCommand, addMemberCommand, createOrganizationCommand, listOrganizationsCommand, removeMemberCommand, setMemberRolesCommand } from "./commands.js";
2
1
  //#region src/organizations/register.ts
3
2
  const out = (text) => process.stdout.write(text);
4
3
  const projectApi = async () => {
@@ -10,10 +9,12 @@ const memberOptions = (command) => command.argument("<organization>", "its slug
10
9
  const registerOrganizations = (program) => {
11
10
  const organizations = program.command("organizations").description("Manage the organizations of the project in the current directory (with `organizations` in createAuth)");
12
11
  organizations.command("list").description("List organizations with their members and roles").action(async () => {
12
+ const { listOrganizationsCommand } = await import("./commands.js");
13
13
  await listOrganizationsCommand(await projectApi(), out);
14
14
  finish(0);
15
15
  });
16
16
  organizations.command("create").description("Create an organization; its owner holds every app role").argument("<name>").requiredOption("--owner <email>", "the user who owns it").option("--slug <slug>", "default: from the name").option("--id <id>", "keep an existing tenant value, for an app that ran as one organization").option("--members <all>", "\"all\": every other user joins; their global roles move here, superusers become owners").action(async (name, opts) => {
17
+ const { createOrganizationCommand } = await import("./commands.js");
17
18
  await createOrganizationCommand(await projectApi(), {
18
19
  name,
19
20
  owner: opts.owner,
@@ -24,6 +25,7 @@ const registerOrganizations = (program) => {
24
25
  finish(0);
25
26
  });
26
27
  memberOptions(organizations.command("add-member").description("Add a user to an organization (organization role member unless given)")).action(async (organization, email, opts) => {
28
+ const { addMemberCommand } = await import("./commands.js");
27
29
  await addMemberCommand(await projectApi(), {
28
30
  organization,
29
31
  email,
@@ -33,6 +35,7 @@ const registerOrganizations = (program) => {
33
35
  finish(0);
34
36
  });
35
37
  memberOptions(organizations.command("set-roles").description("Change a member's organization role, app roles, or both")).action(async (organization, email, opts) => {
38
+ const { setMemberRolesCommand } = await import("./commands.js");
36
39
  await setMemberRolesCommand(await projectApi(), {
37
40
  organization,
38
41
  email,
@@ -42,6 +45,7 @@ const registerOrganizations = (program) => {
42
45
  finish(0);
43
46
  });
44
47
  organizations.command("remove-member").description("Remove a member (refuses the last owner)").argument("<organization>", "its slug or id").argument("<email>").action(async (organization, email) => {
48
+ const { removeMemberCommand } = await import("./commands.js");
45
49
  await removeMemberCommand(await projectApi(), {
46
50
  organization,
47
51
  email
@@ -49,6 +53,7 @@ const registerOrganizations = (program) => {
49
53
  finish(0);
50
54
  });
51
55
  organizations.command("add-app-role").description("Give an app role to every owner of every organization, for a role added after they were made").argument("<role>").requiredOption("--to <owners>", "\"owners\"").action(async (role, opts) => {
56
+ const { addAppRoleCommand } = await import("./commands.js");
52
57
  await addAppRoleCommand(await projectApi(), {
53
58
  role,
54
59
  to: opts.to
@@ -0,0 +1,9 @@
1
+ import { WebSocketServer } from "ws";
2
+ //#region src/project/api-websocket-server.d.ts
3
+ /**
4
+ * The server of npm `ws` that upgrades the API's sockets, realtime's and the app's functions', on Node and Bun: a frame
5
+ * over its socket's cap (`maxPayloadOf`, or a function's lower `maxMessageBytes`) closes the socket with 1009 before it
6
+ * is read.
7
+ */
8
+ export declare const apiWebSocketServer: () => WebSocketServer;
9
+ //#endregion
@@ -0,0 +1,8 @@
1
+ import "vite";
2
+ //#region src/project/extensions.d.ts
3
+ export type Extension = {
4
+ dir: string;
5
+ config?: string;
6
+ ui?: string;
7
+ };
8
+ //#endregion
@@ -2,7 +2,7 @@ import { faviconFile, projectFavicon } from "../build/favicon.js";
2
2
  import { existsSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { readFile } from "node:fs/promises";
5
- import { pngIcons } from "@protobase/server";
5
+ import { pngIcons } from "@protobase/schema/png-icons";
6
6
  //#region src/project/favicon-link.ts
7
7
  /**
8
8
  * Links the project's favicon at `/protobase.favicon.svg` in the app's page, and its Apple touch icon at
@@ -2,7 +2,7 @@ import { conventionConfig } from "./convention.js";
2
2
  import { uiDirs } from "./convention-files.js";
3
3
  import { importProjectFiles } from "./import-project-file.js";
4
4
  import path from "node:path";
5
- import { configExports } from "@protobase/server";
5
+ import { configExports } from "@protobase/server/config-exports";
6
6
  //#region src/project/load-data-config.ts
7
7
  /**
8
8
  * The resources, views and pages of a config folder, as the config module has them by convention: config/index.ts and
@@ -44,9 +44,13 @@ const planScaffold = async (input) => {
44
44
  const byTable = new Map(existing.map((resource) => [resource.table, resource]));
45
45
  const wanted = (table) => matchesTarget(input.target, table) && !isExcluded(input.excludes, table);
46
46
  const tables = input.tables.filter((table) => table.kind === "table");
47
- const skipped = protobaseSchemas(tables.filter((table) => matchesTarget(input.target, table)), input.target);
48
- const isProtobase = (table) => skipped.some((schema) => schema.tables.includes(table));
49
- const inProtobaseSchema = (view) => skipped.some(({ schema }) => schema === view.schema && schema !== "public");
47
+ const protobase = protobaseSchemas(tables, input.target);
48
+ const skipped = protobase.map((found) => ({
49
+ ...found,
50
+ tables: found.tables.filter((table) => matchesTarget(input.target, table))
51
+ })).filter((found) => found.tables.length > 0);
52
+ const isProtobase = (table) => protobase.some((schema) => schema.tables.includes(table));
53
+ const inProtobaseSchema = (view) => protobase.some(({ schema }) => schema === view.schema && schema !== "public");
50
54
  const skippedViews = input.tables.filter((table) => table.kind !== "table" && wanted(table) && !byTable.has(tableKey(table)) && !inProtobaseSchema(table));
51
55
  const names = assignNames(tables.filter((table) => !isProtobase(table)), existing);
52
56
  const context = (table) => ({
@@ -1,38 +1,33 @@
1
+ import { migrationsTableName, storeTableNames } from "@protobase/server/auth-store";
1
2
  //#region src/scaffold/protobase-tables.ts
2
3
  const storeCore = [
3
- "user",
4
4
  "session",
5
5
  "account",
6
6
  "verification"
7
7
  ];
8
- const storeTables = /* @__PURE__ */ new Set([
9
- ...storeCore,
10
- "jwks",
11
- "passkey",
12
- "two_factor",
13
- "sign_in_policy",
14
- "staff_sign_in"
15
- ]);
16
- const isStoreTable = (name) => storeTables.has(name) || name.startsWith("oauth_");
17
8
  const bySchema = (tables) => {
18
9
  const groups = /* @__PURE__ */ new Map();
19
10
  for (const table of tables) groups.set(table.schema, [...groups.get(table.schema) ?? [], table]);
20
11
  return groups;
21
12
  };
13
+ const userTableOf = (schema, tables) => tables.find((table) => table.name === "session")?.foreignKeys.find((key) => key.columns.length === 1 && key.columns[0] === "user_id" && key.refSchema === schema)?.refTable;
22
14
  const authStore = (schema, tables) => {
23
15
  if (schema === "auth") return tables;
24
- if (!storeCore.every((name) => tables.some((table) => table.name === name))) return [];
25
- return schema === "public" ? tables.filter((table) => isStoreTable(table.name)) : tables;
16
+ const has = (name) => tables.some((table) => table.name === name);
17
+ const user = userTableOf(schema, tables);
18
+ if (!has(migrationsTableName) && !(storeCore.every(has) && user !== void 0)) return [];
19
+ if (schema !== "public") return tables;
20
+ return tables.filter((table) => storeTableNames.includes(table.name) || table.name === user);
26
21
  };
27
22
  const jobQueue = (schema, tables) => schema === "jobs" && ["job", "version"].every((name) => tables.some((table) => table.name === name)) ? tables : [];
28
23
  const protobaseSchemas = (tables, target) => [...bySchema(tables)].flatMap(([schema, own]) => {
29
- if (target.schema === schema) return [];
30
24
  const store = authStore(schema, own);
31
25
  if (store.length > 0) return [{
32
26
  schema,
33
27
  what: "auth store",
34
28
  tables: store
35
29
  }];
30
+ if (target.schema === schema) return [];
36
31
  const queue = jobQueue(schema, own);
37
32
  return queue.length > 0 ? [{
38
33
  schema,
@@ -12,7 +12,7 @@ const readText = (file) => readFile(file, "utf8").catch((error) => {
12
12
  if (error.code === "ENOENT") return void 0;
13
13
  throw error;
14
14
  });
15
- const skippedLine = ({ schema, what, tables }) => `skipped ${schema === "public" ? tables.map((table) => `public.${table.name}`).join(", ") : `schema ${schema}`}, Protobase's ${what}; pass "${schema}" as the target to scaffold it anyway\n`;
15
+ const skippedLine = ({ schema, what, tables }) => `skipped ${schema === "public" ? tables.map((table) => `public.${table.name}`).join(", ") : `schema ${schema}`}, Protobase's ${what}${what === "job queue" ? `; pass "${schema}" as the target to scaffold it anyway` : ""}\n`;
16
16
  const write = async ({ path: file, after }) => {
17
17
  await mkdir(path.dirname(file), { recursive: true });
18
18
  await writeFile(file, after);
@@ -1,14 +1,14 @@
1
1
  import { protobaseVersion } from "../version/version.js";
2
2
  import { projectAdmin } from "../project/project-admin.js";
3
3
  import { createPgDb } from "../project/pg-db.js";
4
- import { withClientAddress } from "./client-address.js";
5
4
  import { apiWebSocketServer } from "../project/api-websocket-server.js";
5
+ import { withClientAddress } from "./client-address.js";
6
6
  import { createServeApp } from "./app.js";
7
7
  import { startCleanupTimer } from "./cleanup-timer.js";
8
8
  import { closeSockets } from "./close-sockets.js";
9
9
  import { servedRelease } from "./mobile-release.js";
10
10
  import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
11
- import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
11
+ import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkResourcesOutsideAuthStore, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
12
12
  import pg from "pg";
13
13
  //#region src/serve/lifecycle.ts
14
14
  const listen = (server, port) => new Promise((resolve, reject) => {
@@ -26,6 +26,7 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
26
26
  const db = project.db ?? ownDb;
27
27
  const { resources, views } = configExports(project.config);
28
28
  const startJobsAndListen = async () => {
29
+ if (env.startupChecks && project.auth) await checkResourcesOutsideAuthStore(db, resources.map((resource) => resource.toModel()), project.auth);
29
30
  if (env.startupChecks) await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
30
31
  if (env.startupChecks) await checkComments(db, resources.map((resource) => resource.toModel()));
31
32
  if (env.startupChecks) await checkComputed(db, resources.map((resource) => resource.toModel()));
@@ -1,11 +1,11 @@
1
1
  import { protobaseVersion } from "../version/version.js";
2
- import { bundledSkills, installSkill } from "./install.js";
3
2
  import { join } from "node:path";
4
3
  import { fileURLToPath } from "node:url";
5
4
  //#region src/skill/register.ts
6
5
  const skillsDir = fileURLToPath(new URL("../../skills", import.meta.url));
7
6
  function registerSkill(program) {
8
7
  program.command("skill").description("the protobase agent skills").command("install [name]").description("copy the agent skills of this CLI's version, or only the one named, into the project's .agents/skills and .claude/skills").action(async (name) => {
8
+ const { bundledSkills, installSkill } = await import("./install.js");
9
9
  const skills = await bundledSkills(skillsDir);
10
10
  if (name && !skills.includes(name)) throw new Error(`no skill named ${name}; this CLI ships ${skills.join(", ")}`);
11
11
  const projectDir = process.cwd();
@@ -1,5 +1,3 @@
1
- import { addMemberCommand } from "../organizations/commands.js";
2
- import { deleteUserCommand, setRoleCommand } from "./manage.js";
3
1
  import { parseTtl } from "./ttl.js";
4
2
  import { Option } from "commander";
5
3
  import { createInterface } from "node:readline/promises";
@@ -26,10 +24,11 @@ const registerUsers = (program) => {
26
24
  users.command("create").description("Create a user; the first user is always an admin").argument("<email>").option("--name <name>", "display name").option("--role <role>", "role for users after the first (default: the project's default role; see `users roles`)").option("--password-stdin", "read the password from stdin", false).option("--generate-password", "generate a strong password and print it once", false).option("--no-password", "no password: the user signs in by emailed code, passkey or a sign-in provider").option("--github-id <id>", "link the user to this GitHub user id, so signing in with GitHub finds them whatever their address").option("--organization <organization>", "with organizations: add the user to this one (its slug or id)").option("--org-role <role>", "with --organization: owner, admin or member (default member)").option("--app-roles <roles>", "with --organization: app roles there, comma separated").addOption(new Option("--password <value>").hideHelp()).action(async (email, opts) => {
27
25
  const { readHidden, rejectPasswordArgument } = await import("./password.js");
28
26
  rejectPasswordArgument(opts.password);
29
- const [{ createUserCommand }, { usersApi }, { organizationsApi }, auth] = await Promise.all([
27
+ const [{ createUserCommand }, { usersApi }, { organizationsApi }, { addMemberCommand }, auth] = await Promise.all([
30
28
  import("./commands.js"),
31
29
  import("./users-api.js"),
32
30
  import("../organizations/api.js"),
31
+ import("../organizations/commands.js"),
33
32
  loadAuth()
34
33
  ]);
35
34
  await createUserCommand(usersApi(auth), {
@@ -53,6 +52,7 @@ const registerUsers = (program) => {
53
52
  finish(0);
54
53
  });
55
54
  users.command("delete").description("Delete a user (refuses the last admin)").argument("<email>").option("--yes", "skip the confirmation", false).action(async (email, opts) => {
55
+ const { deleteUserCommand } = await import("./manage.js");
56
56
  await deleteUserCommand(await projectApi(), {
57
57
  email,
58
58
  yes: opts.yes
@@ -60,6 +60,7 @@ const registerUsers = (program) => {
60
60
  finish(0);
61
61
  });
62
62
  users.command("set-role").description("Change a user's role, or several comma separated (refuses to demote the last admin)").argument("<email>").argument("<role>").action(async (email, role) => {
63
+ const { setRoleCommand } = await import("./manage.js");
63
64
  await setRoleCommand(await projectApi(), {
64
65
  email,
65
66
  role
@@ -1,5 +1,5 @@
1
- import { setDisabledCommand } from "./manage.js";
2
1
  import { usersApi } from "./users-api.js";
2
+ import { setDisabledCommand } from "./manage.js";
3
3
  import { checkAuthSchema } from "@protobase/server";
4
4
  //#region src/users/set-disabled.ts
5
5
  const setDisabledInProject = async (auth, options, out) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.47.0",
3
+ "version": "0.48.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": {
@@ -12,6 +12,7 @@
12
12
  "type": "module",
13
13
  "sideEffects": [
14
14
  "./dist/dev/entry.js",
15
+ "./dist/dev/api-process.js",
15
16
  "./dist/serve/main.js"
16
17
  ],
17
18
  "engines": {
@@ -38,12 +39,11 @@
38
39
  "dependencies": {
39
40
  "@better-auth/core": "^1.7.12",
40
41
  "@hono/node-server": "^2.1.3",
41
- "@hono/vite-dev-server": "^0.26.1",
42
- "@protobase/layout": "0.47.0",
43
- "@protobase/query": "0.47.0",
44
- "@protobase/schema": "0.47.0",
45
- "@protobase/server": "0.47.0",
46
- "@protobase/ui": "0.47.0",
42
+ "@protobase/layout": "0.48.0",
43
+ "@protobase/query": "0.48.0",
44
+ "@protobase/schema": "0.48.0",
45
+ "@protobase/server": "0.48.0",
46
+ "@protobase/ui": "0.48.0",
47
47
  "@react-email/render": "^2.1.0",
48
48
  "@scalar/hono-api-reference": "^0.12.10",
49
49
  "@tailwindcss/vite": "^4.3.3",