@protobase/cli 0.47.1 → 0.49.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/config-bundle.js +6 -1
- package/dist/build/entry-code.js +30 -17
- package/dist/cli/package.js +1 -1
- package/dist/config/build-project.js +70 -0
- package/dist/config/called-config.js +11 -0
- package/dist/config/config-defaults.js +30 -0
- package/dist/config/env-values.js +20 -0
- package/dist/config/lazy-imports.js +18 -0
- package/dist/config/merge-config.js +72 -0
- package/dist/config/project-files.js +48 -0
- package/dist/config/project-parts.js +201 -0
- package/dist/config/read-config.js +31 -0
- package/dist/config/source-config.js +37 -0
- package/dist/dev/api-child.js +2 -1
- package/dist/dev/api-process.d.ts +1 -0
- package/dist/dev/api-process.js +5 -2
- package/dist/dev/auth-drift-lines.js +8 -0
- package/dist/dev/create-db.js +2 -2
- package/dist/dev/entry.d.ts +5 -0
- package/dist/dev/entry.js +17 -12
- package/dist/dev/project.js +23 -47
- package/dist/dev/run.js +3 -2
- package/dist/main.js +3 -3
- package/dist/migration/load-project.js +34 -34
- package/dist/migration/parts.js +2 -2
- package/dist/migration/summary.js +2 -2
- package/dist/mobile/api-origin.js +4 -4
- package/dist/mobile/load-project.js +13 -12
- package/dist/mobile/register.js +1 -1
- package/dist/mobile/run.js +1 -1
- package/dist/organizations/register.js +1 -1
- package/dist/project/error-reporter.js +3 -3
- package/dist/project/import-project-file.js +4 -2
- package/dist/project/load-bundle-project.js +16 -25
- package/dist/project/load-data-config.js +2 -2
- package/dist/project/pg-db.js +10 -4
- package/dist/project/placeholder-secret.js +2 -2
- package/dist/project/project-admin.js +12 -11
- package/dist/scaffold/plan.js +7 -3
- package/dist/scaffold/protobase-tables.js +8 -13
- package/dist/scaffold/run.js +1 -1
- package/dist/serve/create-admin.js +9 -4
- package/dist/serve/host-module-ids.js +1 -0
- package/dist/serve/host-modules.js +3 -1
- package/dist/serve/lifecycle.js +19 -14
- package/dist/serve/load-bundle.js +41 -11
- package/dist/serve/mobile-release.js +1 -1
- package/dist/serve/serve-bundle.js +3 -3
- package/dist/supabase/auth-config.js +33 -28
- package/dist/supabase/config-jobs.js +28 -27
- package/dist/supabase/config-object.js +25 -0
- package/dist/supabase/cron-job-file.js +13 -14
- package/dist/supabase/cron-jobs-write.js +6 -12
- package/dist/supabase/cron-plan.js +3 -51
- package/dist/supabase/project-files.js +4 -9
- package/dist/supabase/report.js +3 -3
- package/dist/users/load-auth.js +16 -15
- package/dist/worker/start-worker.js +18 -15
- package/package.json +8 -6
- package/skills/protobase/SKILL.md +2 -1
- package/skills/protobase/references/features/notifications.md +1 -1
- package/skills/protobase/references/features/sign-in-and-accounts.md +1 -0
- package/skills/protobase/references/features/start-a-project.md +3 -0
- package/skills/protobase/references/getting-started.md +2 -2
- package/skills/protobase/references/guides/api-functions.md +4 -4
- package/skills/protobase/references/guides/deploy.md +8 -8
- package/skills/protobase/references/guides/existing-database.md +11 -31
- package/skills/protobase/references/guides/first-plugin.md +1 -1
- package/skills/protobase/references/guides/mobile-app.md +5 -3
- package/skills/protobase/references/guides/plugin-build.md +1 -1
- package/skills/protobase/references/guides/push-notifications.md +6 -7
- package/skills/protobase/references/guides/remote-resources.md +22 -31
- package/skills/protobase/references/reference/access.md +3 -3
- package/skills/protobase/references/reference/ai.md +1 -9
- package/skills/protobase/references/reference/api.md +15 -15
- package/skills/protobase/references/reference/app-identity.md +9 -10
- package/skills/protobase/references/reference/assistant.md +6 -6
- package/skills/protobase/references/reference/auth.md +126 -96
- package/skills/protobase/references/reference/bottom-bar.md +1 -1
- package/skills/protobase/references/reference/cli.md +36 -86
- package/skills/protobase/references/reference/comments.md +0 -8
- package/skills/protobase/references/reference/config.md +152 -0
- package/skills/protobase/references/reference/data-config.md +2 -2
- package/skills/protobase/references/reference/email.md +36 -37
- package/skills/protobase/references/reference/events.md +1 -1
- package/skills/protobase/references/reference/files.md +18 -23
- package/skills/protobase/references/reference/forms.md +5 -17
- package/skills/protobase/references/reference/history.md +2 -3
- package/skills/protobase/references/reference/installable-app.md +1 -1
- package/skills/protobase/references/reference/jobs.md +53 -56
- package/skills/protobase/references/reference/languages.md +4 -2
- package/skills/protobase/references/reference/mcp.md +11 -11
- package/skills/protobase/references/reference/notifications.md +26 -24
- package/skills/protobase/references/reference/plugins.md +11 -14
- package/skills/protobase/references/reference/remote-resources.md +18 -24
- package/skills/protobase/references/reference/supabase-realtime.md +1 -1
- package/skills/protobase/references/reference/supabase-rest.md +1 -1
- package/skills/protobase/references/reference/supabase-storage.md +1 -1
- package/skills/protobase/references/reference/ui-config.md +15 -17
- package/skills/protobase/references/reference/versioning.md +1 -1
- package/skills/protobase/references/reference/webhooks.md +6 -7
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import { configExports, createAdmin
|
|
1
|
+
import { configExports, createAdmin } from "@protobase/server";
|
|
2
2
|
//#region src/project/project-admin.ts
|
|
3
3
|
/**
|
|
4
|
-
* The admin API of a project over `db`, as `dev`, `serve` and `worker`
|
|
5
|
-
* pages and subscriptions, and the rest of its config; served from a bundle, the plugins it carries, their field
|
|
6
|
-
* types and which icons are the project's own (`protobase dev` passes the project's icons alone). `jobs` are the
|
|
7
|
-
*
|
|
8
|
-
*
|
|
4
|
+
* The admin API of a built project over `db`, as `dev`, `serve` and `worker` run it: its config module's resources,
|
|
5
|
+
* views, pages and subscriptions, and the rest of its config; served from a bundle, the plugins it carries, their field
|
|
6
|
+
* types and which icons are the project's own (`protobase dev` passes the project's icons alone). `jobs` are the
|
|
7
|
+
* project's own and the delivery of its events and history. With a `reporter`, every error the API turns into a 500,
|
|
8
|
+
* and every stopped query, goes to the error tracker too, besides the project's `onUnhandledError` or the console. With
|
|
9
|
+
* the host's `upgradeWebSocket`, it serves `/api/sb/realtime/v1` too.
|
|
9
10
|
*/
|
|
10
|
-
const projectAdmin = (project,
|
|
11
|
-
const { resources, views, pages, userMenu, bottomBars, subscriptions } = configExports(config);
|
|
12
|
-
const own = jobDefinitions(project.jobs ?? {});
|
|
11
|
+
const projectAdmin = (project, db, ui, reporter, upgradeWebSocket) => {
|
|
12
|
+
const { resources, views, pages, userMenu, bottomBars, subscriptions } = configExports(project.config);
|
|
13
13
|
const unhandled = project.options?.onUnhandledError ?? ((error) => console.error(error));
|
|
14
14
|
const admin = createAdmin({
|
|
15
15
|
resources,
|
|
@@ -19,6 +19,7 @@ const projectAdmin = (project, config, db, ui, reporter, upgradeWebSocket) => {
|
|
|
19
19
|
bottomBars,
|
|
20
20
|
db,
|
|
21
21
|
authenticate: project.authenticate,
|
|
22
|
+
...project.secret && { secret: project.secret },
|
|
22
23
|
...project.auth && { auth: project.auth },
|
|
23
24
|
...project.functions && { functions: project.functions },
|
|
24
25
|
...project.files && { files: project.files },
|
|
@@ -29,7 +30,7 @@ const projectAdmin = (project, config, db, ui, reporter, upgradeWebSocket) => {
|
|
|
29
30
|
...project.mobile && { mobile: project.mobile },
|
|
30
31
|
...project.app && { app: project.app },
|
|
31
32
|
...ui?.icons && { icons: ui.icons },
|
|
32
|
-
jobs:
|
|
33
|
+
jobs: project.jobs,
|
|
33
34
|
subscriptions,
|
|
34
35
|
...ui && {
|
|
35
36
|
bundlePlugins: ui.plugins,
|
|
@@ -46,7 +47,7 @@ const projectAdmin = (project, config, db, ui, reporter, upgradeWebSocket) => {
|
|
|
46
47
|
});
|
|
47
48
|
return {
|
|
48
49
|
admin,
|
|
49
|
-
jobs: [...
|
|
50
|
+
jobs: [...project.jobs, ...admin.jobs]
|
|
50
51
|
};
|
|
51
52
|
};
|
|
52
53
|
//#endregion
|
package/dist/scaffold/plan.js
CHANGED
|
@@ -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
|
|
48
|
-
const
|
|
49
|
-
|
|
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
|
-
|
|
25
|
-
|
|
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,
|
package/dist/scaffold/run.js
CHANGED
|
@@ -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}
|
|
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,3 +1,5 @@
|
|
|
1
|
+
import { projectAuth } from "../config/build-project.js";
|
|
2
|
+
import { openAppDatabase } from "../project/pg-db.js";
|
|
1
3
|
import { readHidden } from "../users/password.js";
|
|
2
4
|
import { createUserCommand } from "../users/commands.js";
|
|
3
5
|
import { usersApi } from "../users/users-api.js";
|
|
@@ -5,14 +7,17 @@ import { checkBundleManifest } from "./bundle-manifest.js";
|
|
|
5
7
|
import { loadBundle } from "./load-bundle.js";
|
|
6
8
|
import { bundleConfigFile } from "../worker/start-worker.js";
|
|
7
9
|
import { checkAuthSchema } from "@protobase/server";
|
|
10
|
+
import pg from "pg";
|
|
8
11
|
//#region src/serve/create-admin.ts
|
|
9
12
|
const createAdminInBundle = async (bundle, email, options, out) => {
|
|
10
13
|
const file = await bundleConfigFile(bundle);
|
|
11
14
|
checkBundleManifest(file);
|
|
12
|
-
const
|
|
13
|
-
if (!
|
|
14
|
-
|
|
15
|
-
await
|
|
15
|
+
const config = await loadBundle(file);
|
|
16
|
+
if (!config.auth) throw new Error("Sign-in is off in the bundle's config (`auth: false`), so the app has no users to manage");
|
|
17
|
+
if (!process.env.DATABASE_URL) throw new Error("No database: set DATABASE_URL");
|
|
18
|
+
const auth = await projectAuth(config, openAppDatabase(pg, process.env.DATABASE_URL));
|
|
19
|
+
await checkAuthSchema(auth);
|
|
20
|
+
await createUserCommand(usersApi(auth), {
|
|
16
21
|
email,
|
|
17
22
|
role: "admin",
|
|
18
23
|
...options
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as nodeServer from "@hono/node-server";
|
|
2
2
|
import * as hono from "hono";
|
|
3
3
|
import * as server from "@protobase/server";
|
|
4
|
+
import * as layout from "@protobase/layout";
|
|
4
5
|
import * as kysely from "kysely";
|
|
5
6
|
import * as pg$1 from "pg";
|
|
6
7
|
import * as reactEmailRender from "@react-email/render";
|
|
@@ -16,11 +17,12 @@ import * as postgres$1 from "postgres";
|
|
|
16
17
|
import * as react from "react";
|
|
17
18
|
import * as reactJsxRuntime from "react/jsx-runtime";
|
|
18
19
|
import * as zod from "zod";
|
|
19
|
-
import * as
|
|
20
|
+
import * as protobaseConfig from "@protobase/config";
|
|
20
21
|
import * as query from "@protobase/query";
|
|
21
22
|
import * as schema from "@protobase/schema";
|
|
22
23
|
//#region src/serve/host-modules.ts
|
|
23
24
|
const hostModules = {
|
|
25
|
+
"@protobase/config": protobaseConfig,
|
|
24
26
|
"@protobase/schema": schema,
|
|
25
27
|
"@protobase/layout": layout,
|
|
26
28
|
"@protobase/layout/jsx-runtime": layout.jsxRuntime,
|
package/dist/serve/lifecycle.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { protobaseVersion } from "../version/version.js";
|
|
2
2
|
import { projectAdmin } from "../project/project-admin.js";
|
|
3
|
-
import {
|
|
3
|
+
import { buildProject } from "../config/build-project.js";
|
|
4
|
+
import { openAppDatabase } from "../project/pg-db.js";
|
|
4
5
|
import { apiWebSocketServer } from "../project/api-websocket-server.js";
|
|
5
6
|
import { withClientAddress } from "./client-address.js";
|
|
6
7
|
import { createServeApp } from "./app.js";
|
|
@@ -8,7 +9,7 @@ import { startCleanupTimer } from "./cleanup-timer.js";
|
|
|
8
9
|
import { closeSockets } from "./close-sockets.js";
|
|
9
10
|
import { servedRelease } from "./mobile-release.js";
|
|
10
11
|
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";
|
|
12
|
+
import { assistantSettings, authStoreTables, backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkResourcesOutsideAuthStore, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
|
|
12
13
|
import pg from "pg";
|
|
13
14
|
//#region src/serve/lifecycle.ts
|
|
14
15
|
const listen = (server, port) => new Promise((resolve, reject) => {
|
|
@@ -19,13 +20,15 @@ const listen = (server, port) => new Promise((resolve, reject) => {
|
|
|
19
20
|
});
|
|
20
21
|
});
|
|
21
22
|
const closeServer = (server) => new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
|
|
22
|
-
const startServe = async ({
|
|
23
|
-
if (!
|
|
24
|
-
|
|
25
|
-
const
|
|
26
|
-
const db = project.db ?? ownDb;
|
|
27
|
-
const { resources, views } = configExports(project.config);
|
|
23
|
+
const startServe = async ({ config, env, openDb = (url) => openAppDatabase(pg, url, env.dbConnections), site, ui, reporter }) => {
|
|
24
|
+
if (!env.databaseUrl) throw new Error("No database: set DATABASE_URL");
|
|
25
|
+
const database = openDb(env.databaseUrl);
|
|
26
|
+
const { db } = database;
|
|
28
27
|
const startJobsAndListen = async () => {
|
|
28
|
+
const project = await buildProject(config, database);
|
|
29
|
+
if (env.startupChecks && project.auth) await checkAuthSchema(project.auth);
|
|
30
|
+
const { resources, views } = configExports(project.config);
|
|
31
|
+
if (env.startupChecks && project.auth) await checkResourcesOutsideAuthStore(db, resources.map((resource) => resource.toModel()), project.auth);
|
|
29
32
|
if (env.startupChecks) await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
|
|
30
33
|
if (env.startupChecks) await checkComments(db, resources.map((resource) => resource.toModel()));
|
|
31
34
|
if (env.startupChecks) await checkComputed(db, resources.map((resource) => resource.toModel()));
|
|
@@ -38,7 +41,7 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
|
|
|
38
41
|
});
|
|
39
42
|
if (env.startupChecks && project.webhooks) await checkWebhooksSchema(db, project.webhooks);
|
|
40
43
|
if (env.startupChecks && project.notifications) await checkNotificationsSchema(db, project.notifications, project.auth);
|
|
41
|
-
const { admin, jobs: definitions } = projectAdmin(project,
|
|
44
|
+
const { admin, jobs: definitions } = projectAdmin(project, db, ui, reporter, upgradeWebSocket);
|
|
42
45
|
if (env.startupChecks && definitions.length > 0) await checkJobsSchema(db);
|
|
43
46
|
const jobs = definitions.length > 0 ? await startJobs({
|
|
44
47
|
db,
|
|
@@ -77,17 +80,19 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
|
|
|
77
80
|
return {
|
|
78
81
|
server,
|
|
79
82
|
sockets,
|
|
80
|
-
jobs
|
|
83
|
+
jobs,
|
|
84
|
+
resources,
|
|
85
|
+
files: project.files
|
|
81
86
|
};
|
|
82
87
|
};
|
|
83
|
-
const { server, sockets, jobs } = await startJobsAndListen().catch(async (error) => {
|
|
84
|
-
await
|
|
88
|
+
const { server, sockets, jobs, resources, files } = await startJobsAndListen().catch(async (error) => {
|
|
89
|
+
await db.destroy();
|
|
85
90
|
throw error;
|
|
86
91
|
});
|
|
87
92
|
const cleanup = createFileCleanup({
|
|
88
93
|
resources,
|
|
89
94
|
db,
|
|
90
|
-
...
|
|
95
|
+
...files && { files }
|
|
91
96
|
});
|
|
92
97
|
const timer = cleanup && env.filesCleanupMinutes > 0 ? startCleanupTimer(cleanup.run, env.filesCleanupMinutes, (error) => console.error(error)) : void 0;
|
|
93
98
|
const close = async () => {
|
|
@@ -97,7 +102,7 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
|
|
|
97
102
|
await backgroundSettled();
|
|
98
103
|
await timer?.stop();
|
|
99
104
|
await jobs?.stop();
|
|
100
|
-
await
|
|
105
|
+
await db.destroy();
|
|
101
106
|
};
|
|
102
107
|
return {
|
|
103
108
|
port: server.address().port,
|
|
@@ -1,17 +1,47 @@
|
|
|
1
|
+
import { mergeConfig } from "../config/merge-config.js";
|
|
2
|
+
import { withDefaults } from "../config/config-defaults.js";
|
|
3
|
+
import { calledConfig } from "../config/called-config.js";
|
|
1
4
|
import { bundleBasePath } from "../bundle/manifest.js";
|
|
2
5
|
import path from "node:path";
|
|
3
6
|
import { pathToFileURL } from "node:url";
|
|
4
7
|
//#region src/serve/load-bundle.ts
|
|
5
|
-
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
if (!isObject(project.config)) throw new Error(`${file} has no \`config\`: export it from protobase.config.ts or add config/index.ts`);
|
|
10
|
-
if (typeof project.authenticate !== "function") throw new Error("No authenticator: export `authenticate` (and `auth`) from protobase.config.ts; see https://docs.protobase.net/reference/auth/");
|
|
11
|
-
const basePath = isObject(project.options) ? project.options.basePath : void 0;
|
|
12
|
-
if (basePath !== void 0 && basePath !== "/api/v1") throw new Error(`options.basePath is ${JSON.stringify(basePath)}; a bundle's UI and manifest expect the API at ${bundleBasePath}, so remove it (see https://docs.protobase.net/reference/cli/#the-manifest)`);
|
|
13
|
-
return project;
|
|
8
|
+
/** Checks a bundle's config module: one `protobase build` wrote. */
|
|
9
|
+
const bundleModule = (module, file) => {
|
|
10
|
+
if (typeof module.own !== "object" || module.own === null || !Array.isArray(module.extensions) || typeof module.packages !== "object") throw new Error(`${file} is not a config module of \`protobase build\`; build the project again`);
|
|
11
|
+
return module;
|
|
14
12
|
};
|
|
15
|
-
const
|
|
13
|
+
const projectFiles = ({ resources, functions, modules }, packages) => ({
|
|
14
|
+
...resources && { resources },
|
|
15
|
+
functions,
|
|
16
|
+
module: (file) => modules[file],
|
|
17
|
+
package: async (name) => {
|
|
18
|
+
const load = packages[name];
|
|
19
|
+
if (!load) throw new Error(`The bundle carries no ${name}; build it again`);
|
|
20
|
+
return load();
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
/**
|
|
24
|
+
* The config a bundle carries, read again where it serves, with the environment there, merged after the extensions'
|
|
25
|
+
* configs, with the code its conventions found when it was built.
|
|
26
|
+
*/
|
|
27
|
+
const bundledConfig = async (bundle, command, root) => {
|
|
28
|
+
const configEnv = {
|
|
29
|
+
command,
|
|
30
|
+
env: process.env,
|
|
31
|
+
root
|
|
32
|
+
};
|
|
33
|
+
const sources = [];
|
|
34
|
+
for (const { config, label, files } of [...bundle.extensions, bundle.own]) sources.push({
|
|
35
|
+
config: await calledConfig(config, configEnv, label),
|
|
36
|
+
files: projectFiles(files, bundle.packages),
|
|
37
|
+
label
|
|
38
|
+
});
|
|
39
|
+
const config = withDefaults(mergeConfig(...sources), command, process.env);
|
|
40
|
+
const basePath = config.apiPath;
|
|
41
|
+
if (basePath !== void 0 && basePath !== "/api/v1") throw new Error(`apiPath is ${JSON.stringify(basePath)}; a bundle's UI and manifest expect the API at ${bundleBasePath}, so remove it (see https://docs.protobase.net/reference/cli/#the-manifest)`);
|
|
42
|
+
return config;
|
|
43
|
+
};
|
|
44
|
+
/** The config of the bundle's config module `file`, read again for `command` with the environment of this process. */
|
|
45
|
+
const loadBundle = async (file, command = "serve") => bundledConfig(bundleModule(await import(pathToFileURL(path.resolve(file)).href), file), command, path.dirname(path.resolve(file)));
|
|
16
46
|
//#endregion
|
|
17
|
-
export {
|
|
47
|
+
export { bundleModule, bundledConfig, loadBundle };
|
|
@@ -10,7 +10,7 @@ const loopback = [
|
|
|
10
10
|
"[::1]"
|
|
11
11
|
];
|
|
12
12
|
/**
|
|
13
|
-
* The API origin a release names, the
|
|
13
|
+
* The API origin a release names, the app's URL (`url`), as the app's own files do by default: https, or plain
|
|
14
14
|
* http to this machine only, as `protobase mobile` allows it. `undefined` for any other, which no app calls.
|
|
15
15
|
*/
|
|
16
16
|
const releaseOrigin = (issuer) => {
|
|
@@ -13,11 +13,11 @@ const serveBundle = async (file, env, out, site) => {
|
|
|
13
13
|
const serveEnv = readServeEnv(env);
|
|
14
14
|
checkBundleManifest(file);
|
|
15
15
|
const manifest = await readManifest(path.dirname(file));
|
|
16
|
-
const
|
|
17
|
-
const reporter = await projectErrorReporter(
|
|
16
|
+
const config = await loadBundle(file);
|
|
17
|
+
const reporter = await projectErrorReporter(config, env);
|
|
18
18
|
if (reporter) reportCrashes(reporter);
|
|
19
19
|
const server = await startServe({
|
|
20
|
-
|
|
20
|
+
config,
|
|
21
21
|
env: serveEnv,
|
|
22
22
|
site,
|
|
23
23
|
ui: bundleUi(manifest),
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { exportedConfigObject } from "./config-object.js";
|
|
1
2
|
import { existsSync } from "node:fs";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
import { readFile, writeFile } from "node:fs/promises";
|
|
5
|
+
import { Node } from "ts-morph";
|
|
4
6
|
//#region src/supabase/auth-config.ts
|
|
5
|
-
/**
|
|
7
|
+
/** The `auth` settings for Supabase's auth.users. */
|
|
6
8
|
const supabaseUsers = {
|
|
7
9
|
users: {
|
|
8
10
|
table: "users",
|
|
@@ -12,41 +14,44 @@ const supabaseUsers = {
|
|
|
12
14
|
passwordHashes: ["bcrypt"],
|
|
13
15
|
generateUserId: "uuid"
|
|
14
16
|
};
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
+
const settingsText = (indent) => [
|
|
18
|
+
"// Supabase's own auth.users as the app's user table, written by `protobase import supabase`: every foreign key,",
|
|
19
|
+
"// trigger and policy naming it keeps working. Its passwords are bcrypt hashes, its ids UUIDs, and its `role` the",
|
|
20
|
+
"// Postgres role, so the app's roles go to a column of their own.",
|
|
21
|
+
`users: { table: '${supabaseUsers.users.table}', columns: { role: '${supabaseUsers.users.columns.role}' }, metadata: '${supabaseUsers.users.metadata}' },`,
|
|
22
|
+
`passwordHashes: [${supabaseUsers.passwordHashes.map((name) => `'${name}'`).join(", ")}],`,
|
|
23
|
+
`generateUserId: '${supabaseUsers.generateUserId}',`
|
|
24
|
+
].map((line) => `${indent}${line}`).join("\n");
|
|
25
|
+
const settingsObject = `{ users: { table: '${supabaseUsers.users.table}', columns: { role: '${supabaseUsers.users.columns.role}' }, metadata: '${supabaseUsers.users.metadata}' }, passwordHashes: ['bcrypt'], generateUserId: 'uuid' }`;
|
|
17
26
|
/**
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
*/
|
|
21
|
-
export const supabaseUsers = {
|
|
22
|
-
// Supabase's \`role\` holds the Postgres role, so the app's roles go to a column of their own.
|
|
23
|
-
users: { table: '${supabaseUsers.users.table}', columns: { role: '${supabaseUsers.users.columns.role}' }, metadata: '${supabaseUsers.users.metadata}' },
|
|
24
|
-
passwordHashes: [${supabaseUsers.passwordHashes.map((name) => `'${name}'`).join(", ")}],
|
|
25
|
-
generateUserId: '${supabaseUsers.generateUserId}',
|
|
26
|
-
} satisfies Partial<CreateAuthOptions>
|
|
27
|
-
`;
|
|
28
|
-
const call = "createAuth({";
|
|
29
|
-
const importLine = "import { supabaseUsers } from './supabase-users'\n";
|
|
30
|
-
/**
|
|
31
|
-
* `auth/auth.ts` with the options spread into its one `createAuth({` call, and their import first; fails, naming what
|
|
32
|
-
* to add, otherwise.
|
|
27
|
+
* protobase.config.ts with the settings first in its `auth`, or with an `auth` of them when it has none, sign-in being
|
|
28
|
+
* on by default; fails, naming what to add, when it exports no object the import can see or its `auth` is not one.
|
|
33
29
|
*/
|
|
34
30
|
const withSupabaseUsers = (text, file) => {
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
|
|
31
|
+
const config = exportedConfigObject(text).object;
|
|
32
|
+
const refused = () => /* @__PURE__ */ new Error(`${file} must export a config with an \`auth: { ... }\` object: point it at Supabase's auth.users yourself with ${JSON.stringify(supabaseUsers)}, then import again`);
|
|
33
|
+
if (!config) throw refused();
|
|
34
|
+
const auth = config.getProperty("auth");
|
|
35
|
+
if (!auth) {
|
|
36
|
+
const last = config.getProperties().at(-1);
|
|
37
|
+
if (!last) return `${text.slice(0, config.getStart())}{ auth: ${settingsObject} }${text.slice(config.getEnd())}`;
|
|
38
|
+
return `${text.slice(0, last.getEnd())}, auth: ${settingsObject}${text.slice(last.getEnd())}`;
|
|
39
|
+
}
|
|
40
|
+
const object = Node.isPropertyAssignment(auth) ? auth.getInitializer() : void 0;
|
|
41
|
+
if (!object || !Node.isObjectLiteralExpression(object)) throw refused();
|
|
42
|
+
const first = object.getProperties()[0];
|
|
43
|
+
const indent = first ? " ".repeat(first.getStartLinePos() === first.getStart() ? 0 : first.getStart() - first.getStartLinePos()) : " ";
|
|
44
|
+
const at = object.getStart() + 1;
|
|
45
|
+
return `${text.slice(0, at)}\n${settingsText(indent)}${first ? "" : "\n"}${text.slice(at)}`;
|
|
38
46
|
};
|
|
39
|
-
/** Where the app's Better Auth
|
|
47
|
+
/** Where the app's Better Auth settings live, and what they become; fails before anything is written when it cannot. */
|
|
40
48
|
const planAuthConfig = async (projectDir) => {
|
|
41
|
-
const file = path.join(projectDir, "
|
|
42
|
-
if (!existsSync(file)) throw new Error(
|
|
49
|
+
const file = path.join(projectDir, "protobase.config.ts");
|
|
50
|
+
if (!existsSync(file)) throw new Error("The project has no protobase.config.ts with its `auth`: import into a project made by create-protobase");
|
|
43
51
|
const text = withSupabaseUsers(await readFile(file, "utf8"), path.relative(projectDir, file));
|
|
44
52
|
return {
|
|
45
53
|
file,
|
|
46
|
-
write:
|
|
47
|
-
await writeFile(path.join(path.dirname(file), "supabase-users.ts"), moduleText, { flag: "wx" });
|
|
48
|
-
await writeFile(file, text);
|
|
49
|
-
}
|
|
54
|
+
write: () => writeFile(file, text)
|
|
50
55
|
};
|
|
51
56
|
};
|
|
52
57
|
//#endregion
|
|
@@ -1,34 +1,35 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { Node
|
|
1
|
+
import { exportedConfigObject } from "./config-object.js";
|
|
2
|
+
import { Node } from "ts-morph";
|
|
3
3
|
//#region src/supabase/config-jobs.ts
|
|
4
|
-
const
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
const
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
const
|
|
12
|
-
return {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
}
|
|
4
|
+
const indentOf = (text, node) => {
|
|
5
|
+
const lineStart = text.lastIndexOf("\n", node.getStart() - 1) + 1;
|
|
6
|
+
return /^[ \t]*/.exec(text.slice(lineStart))[0];
|
|
7
|
+
};
|
|
8
|
+
const withEntries = (text, object, entries) => {
|
|
9
|
+
const last = object.getProperties().at(-1);
|
|
10
|
+
if (!last) return `${text.slice(0, object.getStart())}{ ${entries.join(", ")} }${text.slice(object.getEnd())}`;
|
|
11
|
+
const at = last.getEnd() + (text[last.getEnd()] === "," ? 1 : 0);
|
|
12
|
+
if (!object.getText().includes("\n")) return `${text.slice(0, last.getEnd())}, ${entries.join(", ")}${text.slice(last.getEnd())}`;
|
|
13
|
+
const indent = indentOf(text, last);
|
|
14
|
+
const comma = at === last.getEnd() ? "," : "";
|
|
15
|
+
return `${text.slice(0, at)}${comma}${entries.map((entry) => `\n${indent}${entry},`).join("")}${text.slice(at)}`;
|
|
16
16
|
};
|
|
17
17
|
/**
|
|
18
|
-
* `protobase.config.ts`
|
|
19
|
-
*
|
|
20
|
-
* when the file is not one it can change: it
|
|
18
|
+
* `protobase.config.ts` declaring the jobs of `declarations` (each one entry of `jobs`, such as
|
|
19
|
+
* `'purge': { schedule: '0 3 * * *' }`) named `names`: `existing` with them added to its `jobs`, or with a `jobs` of
|
|
20
|
+
* them, or a new config when there is none. `undefined` when the file is not one it can change: it exports no object it
|
|
21
|
+
* can see, its `jobs` is no object written out, or it declares one of these names already.
|
|
21
22
|
*/
|
|
22
|
-
const configWithJobs = (existing) => {
|
|
23
|
-
if (existing === void 0) return
|
|
24
|
-
const {
|
|
25
|
-
if (
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
if (
|
|
31
|
-
return
|
|
23
|
+
const configWithJobs = (existing, names, declarations) => {
|
|
24
|
+
if (existing === void 0) return `import { defineConfig } from '@protobase/config'\n\nexport default defineConfig({\n jobs: {\n${declarations.map((entry) => ` ${entry},\n`).join("")} },\n})\n`;
|
|
25
|
+
const { object } = exportedConfigObject(existing);
|
|
26
|
+
if (!object) return void 0;
|
|
27
|
+
const jobs = object.getProperty("jobs");
|
|
28
|
+
if (!jobs) return withEntries(existing, object, [`jobs: { ${declarations.join(", ")} }`]);
|
|
29
|
+
const declared = Node.isPropertyAssignment(jobs) ? jobs.getInitializer() : void 0;
|
|
30
|
+
if (!declared || !Node.isObjectLiteralExpression(declared)) return void 0;
|
|
31
|
+
if (names.some((name) => declared.getProperty(name) ?? declared.getProperty(`'${name}'`))) return void 0;
|
|
32
|
+
return withEntries(existing, declared, declarations);
|
|
32
33
|
};
|
|
33
34
|
//#endregion
|
|
34
35
|
export { configWithJobs };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { parseSource } from "../scaffold/project.js";
|
|
2
|
+
import { Node } from "ts-morph";
|
|
3
|
+
//#region src/supabase/config-object.ts
|
|
4
|
+
const returnedObject = (fn) => {
|
|
5
|
+
if (!Node.isArrowFunction(fn) && !Node.isFunctionExpression(fn)) return void 0;
|
|
6
|
+
const body = fn.getBody();
|
|
7
|
+
const expression = Node.isParenthesizedExpression(body) ? body.getExpression() : Node.isBlock(body) ? body.getStatements().flatMap((statement) => Node.isReturnStatement(statement) ? [statement.getExpression()] : []).at(-1) : body;
|
|
8
|
+
const unwrapped = expression && Node.isParenthesizedExpression(expression) ? expression.getExpression() : expression;
|
|
9
|
+
return unwrapped && Node.isObjectLiteralExpression(unwrapped) ? unwrapped : void 0;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* The config object `protobase.config.ts` exports by default: written out, passed to a call such as `defineConfig`,
|
|
13
|
+
* or returned by the config function; `undefined` when it exports none the import can see.
|
|
14
|
+
*/
|
|
15
|
+
const exportedConfigObject = (text) => {
|
|
16
|
+
const source = parseSource(text, "protobase.config.ts");
|
|
17
|
+
const exported = source.getExportAssignment((assignment) => !assignment.isExportEquals())?.getExpression();
|
|
18
|
+
const argument = Node.isCallExpression(exported) ? exported.getArguments()[0] : exported;
|
|
19
|
+
return {
|
|
20
|
+
source,
|
|
21
|
+
object: argument && (Node.isObjectLiteralExpression(argument) ? argument : returnedObject(argument))
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
//#endregion
|
|
25
|
+
export { exportedConfigObject };
|
|
@@ -2,24 +2,23 @@
|
|
|
2
2
|
const quoted = (text) => `'${text.replaceAll("\\", "\\\\").replaceAll("'", "\\'").replaceAll("\n", "\\n")}'`;
|
|
3
3
|
const templateLiteral = (text) => `\`${text.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${")}\``;
|
|
4
4
|
/**
|
|
5
|
-
*
|
|
6
|
-
* database role.
|
|
5
|
+
* What `jobs/<file>.ts` holds for a pg_cron job made a Protobase recurring job: its run, the job's SQL as the app's
|
|
6
|
+
* database role. Its schedule is in protobase.config.ts (see `cronJobDeclaration`).
|
|
7
7
|
*/
|
|
8
8
|
const cronJobModule = (job) => [
|
|
9
|
-
"import { defineJob } from '@protobase/server'",
|
|
10
9
|
"import { sql } from 'kysely'",
|
|
10
|
+
"import type { JobRun } from '@protobase/server'",
|
|
11
11
|
"",
|
|
12
|
-
`/** pg_cron's job ${job.name}, imported from Supabase: its SQL, on
|
|
13
|
-
|
|
14
|
-
`
|
|
15
|
-
|
|
16
|
-
...job.timezone ? [` timezone: ${quoted(job.timezone)},`] : [],
|
|
17
|
-
" maxAttempts: 1,",
|
|
18
|
-
" run: async (_, { db }) => {",
|
|
19
|
-
` await sql.raw(${templateLiteral(job.command)}).execute(db)`,
|
|
20
|
-
" },",
|
|
21
|
-
"})",
|
|
12
|
+
`/** pg_cron's job ${job.name}, imported from Supabase: its SQL, on the schedule protobase.config.ts declares. */`,
|
|
13
|
+
"export default (async (_, { db }) => {",
|
|
14
|
+
` await sql.raw(${templateLiteral(job.command)}).execute(db)`,
|
|
15
|
+
"}) satisfies JobRun",
|
|
22
16
|
""
|
|
23
17
|
].join("\n");
|
|
18
|
+
/**
|
|
19
|
+
* The job's declaration in protobase.config.ts's `jobs`, as the text of one entry: pg_cron ran each time once, without
|
|
20
|
+
* retrying a failed one, so the job tries once too.
|
|
21
|
+
*/
|
|
22
|
+
const cronJobDeclaration = (job) => `${quoted(job.file)}: { description: ${quoted(`pg_cron's job ${job.name}, imported from Supabase.`)}, schedule: ${quoted(job.schedule)}, ${job.timezone ? `timezone: ${quoted(job.timezone)}, ` : ""}maxAttempts: 1 }`;
|
|
24
23
|
//#endregion
|
|
25
|
-
export { cronJobModule };
|
|
24
|
+
export { cronJobDeclaration, cronJobModule };
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { ensureExports } from "../scaffold/index-file.js";
|
|
2
1
|
import { configWithJobs } from "./config-jobs.js";
|
|
3
|
-
import { cronJobModule } from "./cron-job-file.js";
|
|
2
|
+
import { cronJobDeclaration, cronJobModule } from "./cron-job-file.js";
|
|
4
3
|
import { existsSync } from "node:fs";
|
|
5
4
|
import path from "node:path";
|
|
6
5
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
@@ -10,21 +9,16 @@ const jobFile = (projectDir, job) => path.join(projectDir, "jobs", `${job.file}.
|
|
|
10
9
|
const cronJobFilesInTheWay = (projectDir, jobs) => jobs.map((job) => jobFile(projectDir, job)).filter((file) => existsSync(file));
|
|
11
10
|
const readIfThere = async (file) => existsSync(file) ? readFile(file, "utf8") : void 0;
|
|
12
11
|
/**
|
|
13
|
-
* Writes each job's
|
|
14
|
-
*
|
|
12
|
+
* Writes each job's run in `jobs/<name>.ts` and declares the jobs in protobase.config.ts's `jobs`; returns whether the
|
|
13
|
+
* config does, `false` when it cannot add them, for a person to add them to.
|
|
15
14
|
*/
|
|
16
15
|
const writeCronJobs = async (projectDir, jobs) => {
|
|
17
16
|
if (jobs.length === 0) return true;
|
|
18
|
-
await mkdir(path.join(projectDir, "jobs"), { recursive: true });
|
|
19
|
-
for (const job of jobs) await writeFile(jobFile(projectDir, job), cronJobModule(job), { flag: "wx" });
|
|
20
|
-
const index = path.join(projectDir, "jobs", "index.ts");
|
|
21
|
-
await writeFile(index, ensureExports(await readIfThere(index) ?? "", jobs.map((job) => ({
|
|
22
|
-
from: `./${job.file}`,
|
|
23
|
-
names: [job.exportName]
|
|
24
|
-
}))));
|
|
25
17
|
const configFile = path.join(projectDir, "protobase.config.ts");
|
|
26
18
|
const existing = await readIfThere(configFile);
|
|
27
|
-
const config = configWithJobs(existing);
|
|
19
|
+
const config = configWithJobs(existing, jobs.map((job) => job.file), jobs.map(cronJobDeclaration));
|
|
20
|
+
await mkdir(path.join(projectDir, "jobs"), { recursive: true });
|
|
21
|
+
for (const job of jobs) await writeFile(jobFile(projectDir, job), cronJobModule(job), { flag: "wx" });
|
|
28
22
|
if (config === void 0) return false;
|
|
29
23
|
if (config !== existing) await writeFile(configFile, config);
|
|
30
24
|
return true;
|