create-protobase 0.48.0 → 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/env-file.js CHANGED
@@ -13,10 +13,10 @@ const withDatabasePort = (example, port) => {
13
13
  url.port = String(port);
14
14
  return replaceSetting(example, "DATABASE_URL", url.toString());
15
15
  };
16
- /** A new project's .env: its .env.example with `secret` as BETTER_AUTH_SECRET in place of the placeholder. */
16
+ /** A new project's .env: its .env.example with `secret` as PROTOBASE_SECRET in place of the placeholder. */
17
17
  const envFile = (example, secret) => {
18
- setting(example, "BETTER_AUTH_SECRET");
19
- return replaceSetting(example, "BETTER_AUTH_SECRET", secret);
18
+ setting(example, "PROTOBASE_SECRET");
19
+ return replaceSetting(example, "PROTOBASE_SECRET", secret);
20
20
  };
21
21
  //#endregion
22
22
  export { databaseUrl, envFile, withDatabasePort };
@@ -4,11 +4,11 @@ DATABASE_URL=postgres://protobase:protobase@localhost:55432/protobase
4
4
 
5
5
  # Admin store (Better Auth users, sessions, signing keys): the `auth` schema of DATABASE_URL, created by `db:migrate`.
6
6
  # Public URL of the API, for cookies and as the issuer of the login tokens (use the https tunnel URL when tunnelling).
7
- BETTER_AUTH_URL=http://localhost:5173
7
+ PROTOBASE_URL=http://localhost:5173
8
8
  # Signs cookies and encrypts the token keys. Generate your own: openssl rand -base64 32
9
- BETTER_AUTH_SECRET=change-me-generate-with-openssl-rand-base64-32
9
+ PROTOBASE_SECRET=change-me-generate-with-openssl-rand-base64-32
10
10
  # Extra comma separated origins allowed to call the auth endpoints (a dev tunnel needs its exact host here, such as https://my-tunnel.trycloudflare.com).
11
- # TRUSTED_ORIGINS=
11
+ # PROTOBASE_TRUSTED_ORIGINS=
12
12
  # Mail for password reset and emailed sign-in and two-factor codes: the SMTP server (smtp:// with STARTTLS, or smtps://) and the sender. Without them those are off.
13
13
  # PROTOBASE_SMTP_URL=smtp://user:password@localhost:1025
14
14
  # PROTOBASE_MAIL_FROM=noreply@example.com
@@ -0,0 +1,26 @@
1
+ import { sql } from 'kysely'
2
+ import type { AuthHooks } from '@protobase/server'
3
+
4
+ // The ERP's records name their organization by core.organizations' integer id, so a new organization takes the next
5
+ // value of that table's sequence, and gets its row there with the ERP's own settings once it is made.
6
+ export const generateOrganizationId: AuthHooks['generateOrganizationId'] = async ({ db }) => {
7
+ const { rows } = await sql<{ id: string }>`select nextval(pg_get_serial_sequence('core.organizations', 'id'))::text as id`.execute(db)
8
+ return rows[0]!.id
9
+ }
10
+
11
+ export const onOrganizationCreated: AuthHooks['onOrganizationCreated'] = async ({ organization }, { db }) => {
12
+ await sql`insert into core.organizations (id, name, slug, country_code, currency_code) values (${Number(organization.id)}, ${organization.name}, ${organization.slug}, 'NL', 'EUR') on conflict (id) do nothing`.execute(db)
13
+ }
14
+
15
+ export const organizationHooks: AuthHooks['organizationHooks'] = {
16
+ afterUpdateOrganization: async ({ organization }, { db }) => {
17
+ if (organization) await sql`update core.organizations set name = ${organization.name}, slug = ${organization.slug} where id = ${Number(organization.id)}`.execute(db)
18
+ },
19
+ }
20
+
21
+ // Orders name their owner by core.users' integer id, so a new user takes the next value of that table's sequence; their
22
+ // row there comes with their first membership (db/migrations/019_auth_users.sql).
23
+ export const generateUserId: AuthHooks['generateUserId'] = async ({ db }) => {
24
+ const { rows } = await sql<{ id: string }>`select nextval(pg_get_serial_sequence('core.users', 'id'))::text as id`.execute(db)
25
+ return rows[0]!.id
26
+ }
@@ -1,6 +1,6 @@
1
1
  import { describe, expect, it } from 'vitest'
2
2
  import type { WriteEvent } from '@protobase/server'
3
- import { overdueCheck } from './jobs'
3
+ import { overdueCheck } from './schedule-overdue-check'
4
4
 
5
5
  const event = (operation: WriteEvent['operation'], after?: Record<string, unknown>, resource = 'invoices') =>
6
6
  ({ operation, resource: { name: resource }, user: { id: 1, roles: [] }, ...(after && { after }) }) as unknown as WriteEvent
@@ -0,0 +1,16 @@
1
+ import { enqueueJob, type PipelineHook, type WriteEvent } from '@protobase/server'
2
+
3
+ const day = 86_400_000
4
+
5
+ /** For a sent invoice, the check that it is paid: the day after it is due, one waiting check per invoice. */
6
+ export const overdueCheck = (event: WriteEvent) => {
7
+ if (event.resource.name !== 'invoices' || event.operation === 'delete' || event.after?.status !== 'sent') return undefined
8
+ const invoiceId = String(event.after.id)
9
+ return { invoiceId, runAt: new Date(Date.parse(String(event.after.due_at)) + day), key: `invoice:${invoiceId}` }
10
+ }
11
+
12
+ // In the write's own transaction: the invoice and the check of its payment commit together or not at all.
13
+ export default (async (event, trx) => {
14
+ const check = overdueCheck(event)
15
+ if (check) await enqueueJob(trx, 'mark-invoice-overdue', { invoiceId: check.invoiceId }, { runAt: check.runAt, key: check.key, mode: 'replace' })
16
+ }) satisfies PipelineHook
@@ -0,0 +1,7 @@
1
+ import { sql } from 'kysely'
2
+ import type { JobRun } from '@protobase/server'
3
+
4
+ // Declared in protobase.config.ts: an invoice still sent and unpaid once its due date has passed becomes overdue.
5
+ export default (async ({ invoiceId }, { db }) => {
6
+ await sql`update sales.invoices set status = 'overdue' where id = ${invoiceId} and status = 'sent' and due_at < current_date`.execute(db)
7
+ }) satisfies JobRun<{ invoiceId: string }>
@@ -0,0 +1,8 @@
1
+ import { sql } from 'kysely'
2
+ import type { JobRun } from '@protobase/server'
3
+
4
+ // Declared in protobase.config.ts: every night, the sent invoices that passed their due date, such as imported ones
5
+ // that never had a check enqueued.
6
+ export default (async (_, { db }) => {
7
+ await sql`update sales.invoices set status = 'overdue' where status = 'sent' and due_at < current_date`.execute(db)
8
+ }) satisfies JobRun
@@ -16,11 +16,12 @@
16
16
  "dev": "protobase dev"
17
17
  },
18
18
  "dependencies": {
19
- "@protobase/cli": "^0.48.0",
20
- "@protobase/layout": "^0.48.0",
21
- "@protobase/schema": "^0.48.0",
22
- "@protobase/server": "^0.48.0",
23
- "@protobase/ui": "^0.48.0",
19
+ "@protobase/cli": "^0.49.0",
20
+ "@protobase/config": "^0.49.0",
21
+ "@protobase/layout": "^0.49.0",
22
+ "@protobase/schema": "^0.49.0",
23
+ "@protobase/server": "^0.49.0",
24
+ "@protobase/ui": "^0.49.0",
24
25
  "better-auth": "^1.7.12",
25
26
  "jose": "^6.2.12",
26
27
  "kysely": "^0.29.6",
@@ -1,22 +1,37 @@
1
- import { defineConfig } from '@protobase/server'
2
- import * as config from './config'
3
- import * as jobs from './config/jobs'
4
- import { roles } from './config/roles'
5
- import { auth, authenticate } from './auth/auth'
1
+ import { defineConfig } from '@protobase/config'
6
2
 
3
+ // The whole app, as one object. Its code is found by its path: resources in config/, roles in config/roles.ts, each
4
+ // job's run in jobs/<name>.ts, each write hook in hooks/<name>.ts, the auth hooks in auth/hooks.ts and the API
5
+ // functions in functions/. Its address and secret are Protobase's defaults, PROTOBASE_URL and PROTOBASE_SECRET (see
6
+ // .env.example).
7
7
  export default defineConfig({
8
- config,
9
- auth,
10
- authenticate,
11
- jobs,
12
- options: {
13
- roles,
14
- writeHooks: [
15
- // In the write's own transaction: the invoice and the check of its payment commit together or not at all.
16
- async (event, trx) => {
17
- const check = jobs.overdueCheck(event)
18
- if (check) await jobs.markInvoiceOverdue.enqueue(trx, { invoiceId: check.invoiceId }, { runAt: check.runAt, key: check.key, mode: 'replace' })
19
- },
20
- ],
8
+ // The time zone of the jobs' schedules, such as the nightly overdue check.
9
+ timezone: 'Europe/Amsterdam',
10
+ auth: {
11
+ // `admin` is the superuser, in every organization; the others are held per organization (or globally, by a few).
12
+ roles: {
13
+ admin: 'Superuser',
14
+ auditor: 'Auditor',
15
+ manager: { label: 'Manager', grants: ['sales', 'accountant', 'warehouse', 'editor'] },
16
+ sales: 'Sales',
17
+ accountant: 'Accountant',
18
+ warehouse: 'Warehouse',
19
+ editor: 'Editor',
20
+ integration: 'Integration',
21
+ },
22
+ // New users and organizations take their ids from the ERP's own sequences (auth/hooks.ts).
23
+ organizations: true,
21
24
  },
25
+ jobs: {
26
+ 'mark-invoice-overdue': {
27
+ description: 'An invoice still sent and unpaid once its due date has passed becomes overdue.',
28
+ arguments: { invoiceId: 'bigint' },
29
+ },
30
+ 'mark-overdue-invoices': {
31
+ description: 'Every night, the sent invoices that passed their due date, such as imported ones that never had a check enqueued.',
32
+ schedule: '0 2 * * *',
33
+ },
34
+ },
35
+ // A sent invoice gets the check of its payment, in the write's own transaction.
36
+ writeHooks: ['schedule-overdue-check'],
22
37
  })
@@ -3,7 +3,7 @@
3
3
  DATABASE_URL=postgres://protobase:protobase@localhost:55432/real_estate
4
4
 
5
5
  # Admin store (Better Auth users, sessions, signing keys): the `auth` schema of DATABASE_URL, created by `db:migrate`.
6
- BETTER_AUTH_URL=http://localhost:5173
6
+ PROTOBASE_URL=http://localhost:5173
7
7
  # Signs cookies and encrypts the token keys. Generate your own: openssl rand -base64 32
8
- BETTER_AUTH_SECRET=change-me-generate-with-openssl-rand-base64-32
9
- # TRUSTED_ORIGINS=
8
+ PROTOBASE_SECRET=change-me-generate-with-openssl-rand-base64-32
9
+ # PROTOBASE_TRUSTED_ORIGINS=
@@ -0,0 +1,9 @@
1
+ import { sql } from 'kysely'
2
+ import type { AuthHooks } from '@protobase/server'
3
+
4
+ // Tickets name their assignee by core.users' integer id, so a new user takes the next value of that table's sequence;
5
+ // their row there comes with the account (db/migrations/013_auth_users.sql).
6
+ export const generateUserId: AuthHooks['generateUserId'] = async ({ db }) => {
7
+ const { rows } = await sql<{ id: string }>`select nextval(pg_get_serial_sequence('core.users', 'id'))::text as id`.execute(db)
8
+ return rows[0]!.id
9
+ }
@@ -16,11 +16,12 @@
16
16
  "dev": "protobase dev"
17
17
  },
18
18
  "dependencies": {
19
- "@protobase/cli": "^0.48.0",
20
- "@protobase/layout": "^0.48.0",
21
- "@protobase/schema": "^0.48.0",
22
- "@protobase/server": "^0.48.0",
23
- "@protobase/ui": "^0.48.0",
19
+ "@protobase/cli": "^0.49.0",
20
+ "@protobase/config": "^0.49.0",
21
+ "@protobase/layout": "^0.49.0",
22
+ "@protobase/schema": "^0.49.0",
23
+ "@protobase/server": "^0.49.0",
24
+ "@protobase/ui": "^0.49.0",
24
25
  "better-auth": "^1.7.12",
25
26
  "jose": "^6.2.12",
26
27
  "kysely": "^0.29.6",
@@ -1,5 +1,14 @@
1
- import * as config from './config'
2
- import { roles } from './config/roles'
3
- import { auth, authenticate } from './auth/auth'
1
+ import { defineConfig } from '@protobase/config'
4
2
 
5
- export default { config, auth, authenticate, options: { roles } }
3
+ // The whole app, as one object. Its code is found by its path: resources in config/, roles in config/roles.ts and the
4
+ // auth hooks in auth/hooks.ts. Its address and secret are Protobase's defaults, PROTOBASE_URL and PROTOBASE_SECRET (see
5
+ // .env.example).
6
+ export default defineConfig({
7
+ auth: {
8
+ // No defaultRole on purpose: every account is created with an explicit role (`protobase users create --role`).
9
+ // New users take their ids from the app's own users sequence (auth/hooks.ts).
10
+ roles: ['admin', 'manager', 'finance', 'maintenance'],
11
+ },
12
+ // Organizations are not used yet: everyone works in organization 1.
13
+ authenticate: { tenant: 1 },
14
+ })
@@ -2,7 +2,7 @@
2
2
  DATABASE_URL=postgres://protobase:protobase@localhost:55432/scratch
3
3
 
4
4
  # Admin store (Better Auth users, sessions, signing keys): the `auth` schema of DATABASE_URL, created by `db:migrate`.
5
- BETTER_AUTH_URL=http://localhost:5173
5
+ PROTOBASE_URL=http://localhost:5173
6
6
  # Signs cookies and encrypts the token keys. Generate your own: openssl rand -base64 32
7
- BETTER_AUTH_SECRET=change-me-generate-with-openssl-rand-base64-32
8
- # TRUSTED_ORIGINS=
7
+ PROTOBASE_SECRET=change-me-generate-with-openssl-rand-base64-32
8
+ # PROTOBASE_TRUSTED_ORIGINS=
@@ -13,11 +13,12 @@
13
13
  "dev": "protobase dev"
14
14
  },
15
15
  "dependencies": {
16
- "@protobase/cli": "^0.48.0",
17
- "@protobase/layout": "^0.48.0",
18
- "@protobase/schema": "^0.48.0",
19
- "@protobase/server": "^0.48.0",
20
- "@protobase/ui": "^0.48.0",
16
+ "@protobase/cli": "^0.49.0",
17
+ "@protobase/config": "^0.49.0",
18
+ "@protobase/layout": "^0.49.0",
19
+ "@protobase/schema": "^0.49.0",
20
+ "@protobase/server": "^0.49.0",
21
+ "@protobase/ui": "^0.49.0",
21
22
  "better-auth": "^1.7.12",
22
23
  "jose": "^6.2.12",
23
24
  "kysely": "^0.29.6",
@@ -1,4 +1,12 @@
1
- import * as config from './config'
2
- import { auth, authenticate } from './auth/auth'
1
+ import { defineConfig } from '@protobase/config'
3
2
 
4
- export default { config, auth, authenticate }
3
+ // The whole app, as one object; it grows as the app does. Its resources are found in config/. Its address and secret
4
+ // are Protobase's defaults, PROTOBASE_URL and PROTOBASE_SECRET (see .env.example).
5
+ export default defineConfig({
6
+ auth: {
7
+ // No defaultRole on purpose: every account is created with an explicit role (`protobase users create --role`).
8
+ roles: ['admin'],
9
+ },
10
+ // Every user works in tenant 1, which access rules can compare with an organization_id column.
11
+ authenticate: { tenant: 1 },
12
+ })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-protobase",
3
- "version": "0.48.0",
3
+ "version": "0.49.0",
4
4
  "description": "npm create protobase: starts a new Protobase project from one of its presets.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -1,65 +0,0 @@
1
- import { PostgresDialect } from 'kysely'
2
- import pg from 'pg'
3
- import { appPool, betterAuthAuthenticator, createAuth } from '@protobase/server'
4
- import { databaseUrl } from '../db/connection'
5
-
6
- const secret = process.env.BETTER_AUTH_SECRET
7
- if (!secret) throw new Error('BETTER_AUTH_SECRET is not set; generate one with `openssl rand -base64 32` and put it in .env')
8
-
9
- // The app's one pool, shared with the runtime, so the store opens no connections beyond the app's
10
- const pool = appPool(pg, databaseUrl)
11
-
12
- /** The admin store (Better Auth's users, sessions and signing keys) lives in this schema, next to the ERP's own schemas. */
13
- export const authSchema = 'auth'
14
-
15
- // The ERP's records name their organization by core.organizations' integer id, so a new organization takes the next
16
- // value of that table's sequence, and gets its row there with the ERP's own settings once it is made.
17
- const nextOrganizationId = async () => {
18
- const { rows } = await pool.query<{ id: string }>("select nextval(pg_get_serial_sequence('core.organizations', 'id'))::text as id")
19
- return rows[0]!.id
20
- }
21
-
22
- const addOrganizationRow = async ({ organization }: { organization: { id: string; name: string; slug: string } }) => {
23
- await pool.query(
24
- "insert into core.organizations (id, name, slug, country_code, currency_code) values ($1, $2, $3, 'NL', 'EUR') on conflict (id) do nothing",
25
- [Number(organization.id), organization.name, organization.slug],
26
- )
27
- }
28
-
29
- // Orders name their owner by core.users' integer id, so a new user takes the next value of that table's sequence; their
30
- // row there comes with their first membership (db/migrations/019_auth_users.sql).
31
- const nextUserId = async () => {
32
- const { rows } = await pool.query<{ id: string }>("select nextval(pg_get_serial_sequence('core.users', 'id'))::text as id")
33
- return rows[0]!.id
34
- }
35
-
36
- export const auth = createAuth({
37
- database: { dialect: new PostgresDialect({ pool }), type: 'postgres', schemaName: authSchema, transaction: true },
38
- baseURL: process.env.BETTER_AUTH_URL ?? 'http://localhost:5173',
39
- secret,
40
- // `admin` is the superuser, in every organization; the others are held per organization (or globally, by a few).
41
- roles: {
42
- admin: 'Superuser',
43
- auditor: 'Auditor',
44
- manager: { label: 'Manager', grants: ['sales', 'accountant', 'warehouse', 'editor'] },
45
- sales: 'Sales',
46
- accountant: 'Accountant',
47
- warehouse: 'Warehouse',
48
- editor: 'Editor',
49
- integration: 'Integration',
50
- },
51
- generateUserId: nextUserId,
52
- organizations: {
53
- generateId: nextOrganizationId,
54
- onCreated: addOrganizationRow,
55
- hooks: {
56
- afterUpdateOrganization: async ({ organization }) => {
57
- if (organization) await pool.query('update core.organizations set name = $2, slug = $3 where id = $1', [Number(organization.id), organization.name, organization.slug])
58
- },
59
- },
60
- },
61
- trustedOrigins: process.env.TRUSTED_ORIGINS?.split(',').filter(Boolean),
62
- })
63
-
64
- /** The organization comes from the signed-in person's session: the one they work in. */
65
- export const authenticate = betterAuthAuthenticator({ auth })
@@ -1,29 +0,0 @@
1
- import { sql } from 'kysely'
2
- import { defineJob, type WriteEvent } from '@protobase/server'
3
-
4
- /** An invoice still sent and unpaid once its due date has passed becomes overdue. */
5
- export const markInvoiceOverdue = defineJob<{ invoiceId: string }>({
6
- name: 'mark-invoice-overdue',
7
- run: async ({ invoiceId }, { db }) => {
8
- await sql`update sales.invoices set status = 'overdue' where id = ${invoiceId} and status = 'sent' and due_at < current_date`.execute(db)
9
- },
10
- })
11
-
12
- /** Every night, the sent invoices that passed their due date, such as imported ones that never had a check enqueued. */
13
- export const markOverdueInvoices = defineJob({
14
- name: 'mark-overdue-invoices',
15
- schedule: '0 2 * * *',
16
- timezone: 'Europe/Amsterdam',
17
- run: async (_, { db }) => {
18
- await sql`update sales.invoices set status = 'overdue' where status = 'sent' and due_at < current_date`.execute(db)
19
- },
20
- })
21
-
22
- const day = 86_400_000
23
-
24
- /** For a sent invoice, the check that it is paid: the day after it is due, one waiting check per invoice. */
25
- export const overdueCheck = (event: WriteEvent) => {
26
- if (event.resource.name !== 'invoices' || event.operation === 'delete' || event.after?.status !== 'sent') return undefined
27
- const invoiceId = String(event.after.id)
28
- return { invoiceId, runAt: new Date(Date.parse(String(event.after.due_at)) + day), key: `invoice:${invoiceId}` }
29
- }
@@ -1,33 +0,0 @@
1
- import { PostgresDialect } from 'kysely'
2
- import pg from 'pg'
3
- import { appPool, betterAuthAuthenticator, createAuth } from '@protobase/server'
4
- import { databaseUrl } from '../db/connection'
5
-
6
- const secret = process.env.BETTER_AUTH_SECRET
7
- if (!secret) throw new Error('BETTER_AUTH_SECRET is not set; generate one with `openssl rand -base64 32` and put it in .env')
8
-
9
- // The app's one pool, shared with the runtime, so the store opens no connections beyond the app's
10
- const pool = appPool(pg, databaseUrl)
11
-
12
- /** The admin store (Better Auth's users, sessions and signing keys) lives in this schema, next to the example's own schemas. */
13
- export const authSchema = 'auth'
14
-
15
- // Tickets name their assignee by core.users' integer id, so a new user takes the next value of that table's sequence;
16
- // their row there comes with the account (db/migrations/013_auth_users.sql).
17
- const nextUserId = async () => {
18
- const { rows } = await pool.query<{ id: string }>("select nextval(pg_get_serial_sequence('core.users', 'id'))::text as id")
19
- return rows[0]!.id
20
- }
21
-
22
- export const auth = createAuth({
23
- database: { dialect: new PostgresDialect({ pool }), type: 'postgres', schemaName: authSchema, transaction: true },
24
- baseURL: process.env.BETTER_AUTH_URL ?? 'http://localhost:5173',
25
- secret,
26
- // No defaultRole on purpose: every account is created with an explicit role (`protobase users create --role`).
27
- roles: ['admin', 'manager', 'finance', 'maintenance'],
28
- generateUserId: nextUserId,
29
- trustedOrigins: process.env.TRUSTED_ORIGINS?.split(',').filter(Boolean),
30
- })
31
-
32
- /** Organizations are not used yet: everyone works in organization 1. */
33
- export const authenticate = betterAuthAuthenticator({ auth, tenant: 1 })
@@ -1,25 +0,0 @@
1
- import { PostgresDialect } from 'kysely'
2
- import pg from 'pg'
3
- import { appPool, betterAuthAuthenticator, createAuth } from '@protobase/server'
4
- import { databaseUrl } from '../db/connection'
5
-
6
- const secret = process.env.BETTER_AUTH_SECRET
7
- if (!secret) throw new Error('BETTER_AUTH_SECRET is not set; generate one with `openssl rand -base64 32` and put it in .env')
8
-
9
- // The app's one pool, shared with the runtime, so the store opens no connections beyond the app's
10
- const pool = appPool(pg, databaseUrl)
11
-
12
- /** The admin store (Better Auth's users, sessions and signing keys) lives in this schema, next to the app's own schemas. */
13
- export const authSchema = 'auth'
14
-
15
- export const auth = createAuth({
16
- database: { dialect: new PostgresDialect({ pool }), type: 'postgres', schemaName: authSchema, transaction: true },
17
- baseURL: process.env.BETTER_AUTH_URL ?? 'http://localhost:5173',
18
- secret,
19
- // No defaultRole on purpose: every account is created with an explicit role (`protobase users create --role`).
20
- roles: ['admin'],
21
- trustedOrigins: process.env.TRUSTED_ORIGINS?.split(',').filter(Boolean),
22
- })
23
-
24
- /** Every user works in tenant 1, which access rules can compare with an organization_id column. */
25
- export const authenticate = betterAuthAuthenticator({ auth, tenant: 1 })