@protobase/cli 0.51.1 → 0.51.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.51.1";
2
+ var version = "0.51.3";
3
3
  //#endregion
4
4
  export { version };
@@ -122,8 +122,9 @@ const pattern = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
122
122
  /**
123
123
  * The import's first run: dumps the Supabase database's schemas and data as of one snapshot, writes the schema as
124
124
  * the project's next migration, with the extensions the project's database can create, and the columns Better Auth
125
- * needs on auth.users as the one after, then `realtime.messages` with its policies, which authorize private Realtime
126
- * channels, when the source has any, points the app's Better Auth setup at auth.users in place of the user table the
125
+ * needs on auth.users as the one after, then the realtime schema: `realtime.send()` and `realtime.broadcast_changes()`,
126
+ * which broadcast from the database, and `realtime.messages` with its policies, which authorize private Realtime
127
+ * channels, points the app's Better Auth setup at auth.users in place of the user table the
127
128
  * project's auth migrations make, removing them, and keeps the data dump, the replay of Vault's secrets, pgmq's
128
129
  * queues and pg_cron's jobs and what the report needs in `supabase-import/` for the run that loads it, once the
129
130
  * project's migrations are applied.
@@ -144,7 +145,7 @@ const runDumpPhase = async (options, out) => {
144
145
  const snapshot = exported.snapshot;
145
146
  refuseSsoUsers(await ssoUserCount((text) => reserved.unsafe(text)));
146
147
  const { manifest: source, plan, realtimePolicies: policies, replay } = await readSource(reserved, options.targetUrl);
147
- const created = await checkTarget(options.targetUrl, policies.length > 0 ? [...source.schemas, "realtime"] : source.schemas, source.tables);
148
+ const created = await checkTarget(options.targetUrl, [...source.schemas, "realtime"], source.tables);
148
149
  if (created.length > 0) out(`created the roles ${created.join(", ")} in the project's database\n`);
149
150
  await state.prepare();
150
151
  const schemaFile = path.join(state.dir, "schema.sql");
@@ -175,7 +176,7 @@ const runDumpPhase = async (options, out) => {
175
176
  await mkdir(options.migrationsDir, { recursive: true });
176
177
  const file = await writeMigration(options.migrationsDir, "supabase_schema", migration.text);
177
178
  const usersFile = await writeMigration(options.migrationsDir, "supabase_users", usersColumnsMigration());
178
- const realtimeFile = policies.length > 0 ? await writeMigration(options.migrationsDir, "supabase_realtime", realtimeMigration(policies)) : void 0;
179
+ const realtimeFile = await writeMigration(options.migrationsDir, "supabase_realtime", realtimeMigration(policies));
179
180
  await authConfig.write();
180
181
  for (const store of storeMigrations) await rm(path.join(options.migrationsDir, store));
181
182
  const packages = await writeFunctions(options.projectDir, functions);
@@ -193,7 +194,7 @@ const runDumpPhase = async (options, out) => {
193
194
  const relative = (to) => path.relative(options.projectDir, to);
194
195
  out(`wrote ${relative(path.join(options.migrationsDir, file))}, the schemas ${source.schemas.join(", ")}\n`);
195
196
  out(`wrote ${relative(path.join(options.migrationsDir, usersFile))}, the columns Better Auth needs on auth.users, and pointed ${relative(authConfig.file)} at it\n`);
196
- if (realtimeFile) out(`wrote ${relative(path.join(options.migrationsDir, realtimeFile))}, realtime.messages with its ${policies.length} policies, which authorize private Realtime channels\n`);
197
+ out(`wrote ${relative(path.join(options.migrationsDir, realtimeFile))}, realtime.send() and realtime.broadcast_changes(), which broadcast from the database, and realtime.messages with its ${policies.length} policies, which authorize private Realtime channels\n`);
197
198
  for (const store of storeMigrations) out(`removed ${relative(path.join(options.migrationsDir, store))}: auth.users replaces Protobase's own user table it made\n`);
198
199
  if (functions.functions.length > 0) out(`converted ${functions.functions.length} Edge Functions into functions/${packages.length > 0 ? `, adding ${packages.length} packages to package.json: install them` : ""}\n`);
199
200
  out(`dumped ${source.tables.length} tables' data into ${path.relative(options.projectDir, state.data)}, which git ignores\n`);
@@ -1,3 +1,4 @@
1
+ import { realtimeSchemaSql } from "./realtime-schema.js";
1
2
  import { isSupabaseRole } from "./rewrite.js";
2
3
  //#region src/supabase/realtime-policies.ts
3
4
  /**
@@ -14,25 +15,6 @@ const realtimePolicies = async (query) => {
14
15
  return policies;
15
16
  };
16
17
  const quoted = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
17
- const schema = `create schema realtime;
18
-
19
- create table realtime.messages (
20
- topic text not null,
21
- extension text not null,
22
- payload jsonb,
23
- event text,
24
- private boolean,
25
- updated_at timestamp without time zone not null default now(),
26
- inserted_at timestamp without time zone not null default now(),
27
- id uuid not null default gen_random_uuid() primary key
28
- );
29
-
30
- create function realtime.topic() returns text language sql stable as $$ select nullif(current_setting('realtime.topic', true), '')::text $$;
31
-
32
- alter table realtime.messages enable row level security;
33
- grant usage on schema realtime to anon, authenticated, service_role;
34
- grant select, insert, update, delete on realtime.messages to anon, authenticated, service_role;
35
- `;
36
18
  const policySql = (policy) => {
37
19
  const roles = policy.roles.filter((role) => !isSupabaseRole(role));
38
20
  if (roles.length === 0) return `-- Left out by protobase import supabase: the policy ${JSON.stringify(policy.name)} names only Supabase's own roles.\n`;
@@ -45,14 +27,16 @@ const policySql = (policy) => {
45
27
  ].join("");
46
28
  };
47
29
  /**
48
- * The migration that makes Supabase's `realtime.messages` and `realtime.topic()` with the source's policies on it, which
49
- * decide who may join, hear and send on a private channel of `/api/sb/realtime/v1`. The role that applies it owns the
50
- * table; the server's probes need the app's database role to own it or to bypass row security.
30
+ * The migration that makes Supabase's `realtime` schema (`realtimeSchemaSql`) with the source's policies on
31
+ * `realtime.messages`, which decide who may join, hear and send on a private channel of `/api/sb/realtime/v1`. The
32
+ * role that applies it owns the table; the server's probes, and its reads of the messages the database broadcasts,
33
+ * need the app's database role to own it or to bypass row security.
51
34
  */
52
35
  const realtimeMigration = (policies) => [
53
36
  "-- realtime.messages of a Supabase database with its row security policies, which authorize private Realtime\n",
54
- "-- channels, written by `protobase import supabase`.\n\n",
55
- schema,
37
+ "-- channels, and realtime.send() and realtime.broadcast_changes(), which broadcast from the database, written by\n",
38
+ "-- `protobase import supabase`.\n\n",
39
+ realtimeSchemaSql,
56
40
  "\n",
57
41
  ...policies.map(policySql)
58
42
  ].join("");
@@ -0,0 +1,73 @@
1
+ //#region src/supabase/realtime-schema.ts
2
+ /**
3
+ * Supabase's `realtime.messages`, unpartitioned, with the columns its policies may read, `realtime.topic()`, and
4
+ * `realtime.send()` and `realtime.broadcast_changes()` as Supabase Realtime defines them, which broadcast from the
5
+ * database: a message inserted in the table, which the server takes out of it once its transaction commits and sends to
6
+ * the channels joined on its topic. `send()` stamps a message with the clock rather than the transaction's start, so
7
+ * the messages of one transaction keep their order. The server's probes of a private channel's policies insert in
8
+ * transactions they roll back, which send nothing.
9
+ */
10
+ const realtimeSchemaSql = `create schema realtime;
11
+
12
+ create table realtime.messages (
13
+ topic text not null,
14
+ extension text not null,
15
+ payload jsonb,
16
+ event text,
17
+ private boolean,
18
+ updated_at timestamp without time zone not null default now(),
19
+ inserted_at timestamp without time zone not null default now(),
20
+ id uuid not null default gen_random_uuid() primary key
21
+ );
22
+
23
+ create index messages_broadcasts on realtime.messages (inserted_at) where extension = 'broadcast';
24
+
25
+ create function realtime.topic() returns text language sql stable as $$ select nullif(current_setting('realtime.topic', true), '')::text $$;
26
+
27
+ create function realtime.send(payload jsonb, event text, topic text, private boolean default true) returns void language plpgsql as $$
28
+ declare
29
+ generated_id uuid;
30
+ final_payload jsonb;
31
+ begin
32
+ begin
33
+ generated_id := gen_random_uuid();
34
+ if payload ? 'id' then
35
+ final_payload := payload;
36
+ else
37
+ final_payload := jsonb_set(payload, '{id}', to_jsonb(generated_id));
38
+ end if;
39
+ execute format('set local realtime.topic to %L', topic);
40
+ insert into realtime.messages (id, payload, event, topic, private, extension, inserted_at)
41
+ values (generated_id, final_payload, event, topic, private, 'broadcast', clock_timestamp());
42
+ exception
43
+ when others then
44
+ raise warning 'WarnSendingBroadcastMessage: %', sqlerrm;
45
+ end;
46
+ end;
47
+ $$;
48
+
49
+ create function realtime.broadcast_changes(topic_name text, event_name text, operation text, table_name text, table_schema text, new record, old record, level text default 'ROW') returns void language plpgsql as $$
50
+ declare
51
+ row_data jsonb := '{}'::jsonb;
52
+ begin
53
+ if level = 'STATEMENT' then
54
+ raise exception 'function can only be triggered for each row, not for each statement';
55
+ end if;
56
+ if operation = 'INSERT' or operation = 'UPDATE' or operation = 'DELETE' then
57
+ row_data := jsonb_build_object('old_record', old, 'record', new, 'operation', operation, 'table', table_name, 'schema', table_schema);
58
+ perform realtime.send(row_data, event_name, topic_name);
59
+ else
60
+ raise exception 'Unexpected operation type: %', operation;
61
+ end if;
62
+ exception
63
+ when others then
64
+ raise exception 'Failed to process the row: %', sqlerrm;
65
+ end;
66
+ $$;
67
+
68
+ alter table realtime.messages enable row level security;
69
+ grant usage on schema realtime to anon, authenticated, service_role;
70
+ grant select, insert, update, delete on realtime.messages to anon, authenticated, service_role;
71
+ `;
72
+ //#endregion
73
+ export { realtimeSchemaSql };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.51.1",
3
+ "version": "0.51.3",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -42,12 +42,12 @@
42
42
  "dependencies": {
43
43
  "@better-auth/core": "^1.7.12",
44
44
  "@hono/node-server": "^2.1.3",
45
- "@protobase/config": "0.51.1",
46
- "@protobase/layout": "0.51.1",
47
- "@protobase/query": "0.51.1",
48
- "@protobase/schema": "0.51.1",
49
- "@protobase/server": "0.51.1",
50
- "@protobase/ui": "0.51.1",
45
+ "@protobase/config": "0.51.3",
46
+ "@protobase/layout": "0.51.3",
47
+ "@protobase/query": "0.51.3",
48
+ "@protobase/schema": "0.51.3",
49
+ "@protobase/server": "0.51.3",
50
+ "@protobase/ui": "0.51.3",
51
51
  "@react-email/render": "^2.1.0",
52
52
  "@scalar/hono-api-reference": "^0.12.10",
53
53
  "@tailwindcss/vite": "^4.3.3",
@@ -10,5 +10,5 @@ Apps written for other systems that keep working on Protobase, and moving their
10
10
  - [Supabase client API](../reference/supabase-rest.md): supabase-js `from()` and `rpc()` calls keep working, under the tables' RLS policies.
11
11
  - [Supabase Auth](../reference/auth.md#supabase-js-and-supabasessr): `supabase.auth` and `@supabase/ssr` calls keep working.
12
12
  - [Supabase Storage](../reference/supabase-storage.md): supabase-js storage calls keep working, over the app's file storage.
13
- - [Supabase Realtime](../reference/supabase-realtime.md): Database changes, broadcast and presence through supabase-js channels, private ones authorized by the policies on `realtime.messages`.
13
+ - [Supabase Realtime](../reference/supabase-realtime.md): Database changes, broadcast and presence through supabase-js channels, private ones authorized by the policies on `realtime.messages`, broadcasts sent from a server without joining a channel, and broadcasts from the database with `realtime.send()` and `realtime.broadcast_changes()`.
14
14
  - [Edge Functions](../guides/api-functions.md#functions-moved-from-supabase): Functions moved from Supabase answer at their old addresses.
@@ -538,7 +538,7 @@ protobase import supabase [<connection> | --source-env <variable>] [--env DATABA
538
538
 
539
539
  Turns a Supabase project's database into the project in the current directory, in two runs with the project's migrations between them. It needs PostgreSQL's `pg_dump` and `psql` on `PATH`, of the Supabase database's major version or newer, and reads the `.env` nearest the current directory for the project's database (`--env`).
540
540
 
541
- 1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and while `auth.users` has single sign-on (SAML) users, which Supabase opens only through their identity provider and Better Auth would find by email: merge or delete them in Supabase first. It notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It converts `supabase/functions` into the project's `functions/` (see [functions moved from Supabase](../guides/api-functions.md#functions-moved-from-supabase)): `Deno.serve(handler)` and std's `serve(handler)` become `export default defineFunction({ supabase: true }, { fetch: handler })`, an existing default export is wrapped the same way, so each function also answers at `/api/sb/functions/v1/<name>`, `npm:`, `jsr:` and esm.sh imports become bare imports of packages it adds to `package.json`, `Deno.env.get(name)` becomes `process.env[name]`, `EdgeRuntime.waitUntil` becomes `waitUntil` of `@protobase/server`, a function with `verify_jwt = false` in `config.toml` becomes public (`{ public: true, supabase: true }`), and `_shared` and the like are converted beside them. It stops before anything else when `functions/` already has one of their names. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, pgsodium's security labels, the views that decrypt with it and the triggers that encrypt with it, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable's insert-blocking trigger. It then writes `NNN_supabase_users.sql`, the nullable columns Better Auth needs on `auth.users` (`name`, `email_verified`, `image`, `app_role`, `banned`, `ban_reason`, `ban_expires`) and GoTrue's `'authenticated'` as the default of `role` and `aud`. When the source has row security policies on `realtime.messages`, it writes `NNN_supabase_realtime.sql`, which makes `realtime.messages` and `realtime.topic()` with those policies, so the app's [private channels](supabase-realtime.md#private-channels) keep their access; a policy that names only Supabase's own roles is left out as a comment. It points the app at `auth.users`: the `auth` of `protobase.config.ts` gets `users: { table: 'users', columns: { role: 'app_role' }, metadata: 'raw_user_meta_data' }`, `passwordHashes: ['bcrypt']` and `generateUserId: 'uuid'`, or the config gets an `auth` of them when it has none (see [an existing users table](auth.md#an-existing-users-table)). It removes the migrations `protobase auth migration` or `protobase migration` wrote for Protobase's own user table, since `auth.users` replaces it, and stops before writing anything when the project has no `protobase.config.ts`, or one whose `auth` is not an object it can see, or when the project's database has a schema the dump creates already, such as the `auth` schema those migrations made. The project's database needs the roles `anon`, `authenticated` and `service_role` that the dump's grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes to `supabase-import/`, which it adds to `.gitignore`, since it holds every row and the users' password hashes. Where the project's database can create Vault, pgmq and pg_cron, `supabase-import/replay.sql` holds what a dump cannot carry: Vault's secrets with their values, read decrypted since only Supabase's key opens their ciphertext, pgmq's queues with their messages, since pgmq owns their tables, and pg_cron's jobs, which live in its own schema.
541
+ 1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and while `auth.users` has single sign-on (SAML) users, which Supabase opens only through their identity provider and Better Auth would find by email: merge or delete them in Supabase first. It notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It converts `supabase/functions` into the project's `functions/` (see [functions moved from Supabase](../guides/api-functions.md#functions-moved-from-supabase)): `Deno.serve(handler)` and std's `serve(handler)` become `export default defineFunction({ supabase: true }, { fetch: handler })`, an existing default export is wrapped the same way, so each function also answers at `/api/sb/functions/v1/<name>`, `npm:`, `jsr:` and esm.sh imports become bare imports of packages it adds to `package.json`, `Deno.env.get(name)` becomes `process.env[name]`, `EdgeRuntime.waitUntil` becomes `waitUntil` of `@protobase/server`, a function with `verify_jwt = false` in `config.toml` becomes public (`{ public: true, supabase: true }`), and `_shared` and the like are converted beside them. It stops before anything else when `functions/` already has one of their names. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, pgsodium's security labels, the views that decrypt with it and the triggers that encrypt with it, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable's insert-blocking trigger. It then writes `NNN_supabase_users.sql`, the nullable columns Better Auth needs on `auth.users` (`name`, `email_verified`, `image`, `app_role`, `banned`, `ban_reason`, `ban_expires`) and GoTrue's `'authenticated'` as the default of `role` and `aud`. It writes `NNN_supabase_realtime.sql`, which makes `realtime.messages`, `realtime.topic()`, and Supabase's `realtime.send()` and `realtime.broadcast_changes()`, so the app's triggers and SQL keep [broadcasting from the database](supabase-realtime.md#broadcast-from-the-database), with the source's row security policies on `realtime.messages`, so its [private channels](supabase-realtime.md#private-channels) keep their access; a policy that names only Supabase's own roles is left out as a comment. It points the app at `auth.users`: the `auth` of `protobase.config.ts` gets `users: { table: 'users', columns: { role: 'app_role' }, metadata: 'raw_user_meta_data' }`, `passwordHashes: ['bcrypt']` and `generateUserId: 'uuid'`, or the config gets an `auth` of them when it has none (see [an existing users table](auth.md#an-existing-users-table)). It removes the migrations `protobase auth migration` or `protobase migration` wrote for Protobase's own user table, since `auth.users` replaces it, and stops before writing anything when the project has no `protobase.config.ts`, or one whose `auth` is not an object it can see, or when the project's database has a schema the dump creates already, such as the `auth` schema those migrations made. The project's database needs the roles `anon`, `authenticated` and `service_role` that the dump's grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes to `supabase-import/`, which it adds to `.gitignore`, since it holds every row and the users' password hashes. Where the project's database can create Vault, pgmq and pg_cron, `supabase-import/replay.sql` holds what a dump cannot carry: Vault's secrets with their values, read decrypted since only Supabase's key opens their ciphertext, pgmq's queues with their messages, since pgmq owns their tables, and pg_cron's jobs, which live in its own schema.
542
542
  2. **Apply the migration** with the project's other migrations, such as `bun run db:migrate`.
543
543
  3. **The second run**, without a connection string, loads the data in one transaction, with the app's triggers off so a sign-up trigger on `auth.users` does not run again for users who already have their rows, and fails the transaction unless every table holds the source's number of rows. In the same transaction it makes Vault's secrets and pgmq's queues again through `vault.create_secret`, `pgmq.create` and `pgmq.send`, each message with its headers and the time it becomes visible. Where the project's database has pg_cron, as Supabase's Postgres image does when it serves that database, it schedules pg_cron's jobs again there with `cron.schedule`, run by the importing role, an inactive one inactive. Elsewhere it writes each job of plain SQL as a [recurring job](jobs.md#recurring-jobs) of its own in `jobs/`, of the same name, schedule and `cron.timezone`, that runs its SQL as the app's database role, tried once each time as pg_cron did, and declares it in the `jobs` of `protobase.config.ts` (or writes one); they run once [`migration`](#migration) has added the jobs schema. Recurring jobs wake an app that sleeps, so they run where a host stops an idle app too. A job that calls what the database lacks, such as pg_net's `net.http_*`, `cron` or Vault, an inactive one and a schedule recurring jobs do not take, such as `30 seconds` or `$`, stay in the report, as does a job of another database. It loads only into empty tables, deletes the data dump and the replay, runs [`scaffold`](#scaffold) on the imported tables of the app's schemas (not `auth` or `storage`), giving the tables of the `supabase_realtime` publication [`.live()`](live.md) so [`/api/sb/realtime/v1`](supabase-realtime.md) keeps sending their `postgres_changes` once [`migration`](#migration) has written their capture triggers, writes Better Auth's other tables next to `auth.users` as [`auth migration`](#auth-migration) does (`NNN_auth.sql`), then `NNN_supabase_accounts.sql`, and writes `supabase-import/report.md`: the rows loaded, the imported tables' size against the Starter plan's 500 MB, each sign-in provider's identities, what it made again, the tables it made live, and what needs a person: the pg_cron jobs it could not carry over, each with why, Realtime tables it made no resource of, Vault secrets by name and pgmq queues where the database has no such extension (and partitioned queues), the columns pgsodium encrypts, still holding Supabase's ciphertext, whose values to export decrypted in Supabase before declaring them [`.encrypted()`](data-config.md#encrypted-fields) and running [`encryption apply`](#encryption-apply), the extensions it cannot create, hypertables and plv8, plls or plcoffee functions to convert, triggers that call out over HTTP without pg_net, the converted Edge Functions with the packages to install and the code the conversion left (`deno.land/x` imports, Deno's file, KV and WebSocket APIs, `Supabase.ai`), and the indexes [`doctor`](#doctor) finds missing. `NNN_supabase_accounts.sql` fills the user columns from what Supabase Auth recorded and leaves them empty where it recorded nothing: the name from `raw_user_meta_data`'s `full_name` or `name`, the picture from its `avatar_url` or `picture`, `email_verified` from `email_confirmed_at`, and a ban from `banned_until`, which Better Auth lifts once it has passed. It gives each password of a confirmed address, as Supabase hashed it, a `credential` account (a user who never confirmed theirs signs in by code or resets the password, since GoTrue refused their password sign-in too), and each identity of a social provider an account under Better Auth's name for it (`azure` is `microsoft`, keyed on the `oid` claim; `linkedin_oidc` is `linkedin`, `slack_oidc` is `slack`, `x` is `twitter`), unless its user has an address they never confirmed, since GoTrue refused that sign-in too. Email, phone, anonymous and single sign-on identities and sessions do not carry over. <gap>The import cannot carry over MFA factors because that is not implemented.</gap> <gap>The import cannot carry over passkeys because that is not implemented.</gap>
544
544
  4. **Apply the migrations** again. Supabase's users then sign in with their own passwords, and with a social provider once it is in the `socialProviders` of the config's `auth`; new users get a UUID in `auth.users`, so the app's triggers there run for them.
@@ -2,7 +2,7 @@
2
2
 
3
3
  # Supabase Realtime
4
4
 
5
- The Realtime-compatible /api/sb/realtime/v1 that supabase-js's channel() joins, for postgres_changes checked under the subscriber's RLS policies, broadcasts and presence, on public and private channels.
5
+ The Realtime-compatible /api/sb/realtime/v1 that supabase-js's channel() joins, for postgres_changes checked under the subscriber's RLS policies, broadcasts and presence, on public and private channels, and broadcasts from the database.
6
6
 
7
7
  An app with API keys also serves `/api/sb/realtime/v1/websocket`, the socket that supabase-js's `channel()` joins. An app moved from Supabase keeps its `postgres_changes` listeners, broadcasts and presence: point the client at the app's `/api/sb` and give it the publishable key.
8
8
 
@@ -28,7 +28,7 @@ A channel may listen to the tables of the resources with [`.live()`](live.md), b
28
28
 
29
29
  ## Broadcast and presence
30
30
 
31
- Channels on the same topic exchange broadcasts and see each other's presence, as on Supabase:
31
+ Channels on the same topic exchange broadcasts and see each other's presence, as on Supabase, private channels among themselves and public ones among themselves:
32
32
 
33
33
  ```ts
34
34
  const room = supabase.channel('room', { config: { broadcast: { self: false, ack: true }, presence: { key: 'alice' } } })
@@ -46,7 +46,43 @@ A broadcast reaches the topic's other channels, and the sender's own with `self`
46
46
 
47
47
  Limits, near Supabase's Free plan, apply per socket and per topic. A socket sends at most 100 broadcast and presence messages a second, joins at most 100 times a second and holds at most 100 channels; on each channel it sends at most 5 presence updates in 30 seconds, also counted across a rejoin. A topic takes 100 broadcasts a second, whoever sends them, so one busy sender can use up a topic's budget. A topic is at most 255 bytes, and a tracked presence at most 10 000 bytes of JSON. A message over a limit gets an error reply and goes to no one, where Supabase would close the channel. A frame over 256 KiB closes the socket with 1009. It closes with 1008 when the client leaves more than 4 MiB unread, or sends more than 300 messages or 4 MiB while earlier ones wait, such as behind a token check.
48
48
 
49
- Broadcasts and presence go between the channels of one serving process, which is how a cloud app runs; <gap>Several processes behind one address do not reach each other's channels, because broadcasts and presence are not shared between processes.</gap> <gap>Sending without a joined channel, which supabase-js does over `POST /api/sb/realtime/v1/api/broadcast`, is not supported.</gap>
49
+ Broadcasts and presence go between the channels of one serving process, which is how a cloud app runs; <gap>Several processes behind one address do not reach each other's channels, because broadcasts and presence are not shared between processes.</gap>
50
+
51
+ ### Broadcast without a channel
52
+
53
+ A backend or an edge function broadcasts without joining a channel, as on Supabase: supabase-js's `httpSend()`, and `send()` on a channel that has not joined, send it over `POST /api/sb/realtime/v1/api/broadcast`. The request carries the app's key in `apikey` and, for a user, their token in its bearer, as the socket does, and is answered `202`; one without a key of the app is refused with `401`.
54
+
55
+ ```ts
56
+ const room = supabase.channel('room')
57
+ await room.httpSend('cursor', { x: 1, y: 2 })
58
+ await supabase.removeChannel(room)
59
+ ```
60
+
61
+ `POST /api/sb/realtime/v1/api/broadcast` takes Supabase's batch, `{ "messages": [{ "topic": "room", "event": "cursor", "payload": { "x": 1 }, "private": false }] }`, of at most 100 messages, each with an object payload. `httpSend()` sends one message to `POST /api/sb/realtime/v1/api/broadcast/<topic>/events/<event>`, `?private=true` for a private one, with a JSON object or, as `application/octet-stream`, binary bytes. A message reaches the channels joined on its topic in this process, under a broadcast's limits: a body is at most 256 KiB, a topic and an event at most 255 bytes each, and a request that would take a topic over its 100 broadcasts a second is refused with `429` and reaches no one. A public message reaches the topic's public channels; a private one reaches only its private channels that may receive broadcasts, and only when the caller may send broadcasts there by the [policies on `realtime.messages`](#private-channels): a batch drops one it may not send, as Supabase does, and `httpSend()` is refused with `403`. <gap>A policy cannot read a broadcast request's headers in `request.headers` because passing them to the checks is not implemented.</gap>
62
+
63
+ ### Broadcast from the database
64
+
65
+ SQL and triggers broadcast with Supabase's `realtime.send(payload, event, topic, private)` and `realtime.broadcast_changes(topic, event, operation, table, schema, new, old)`, which [`import supabase`](cli.md#import-supabase) makes in the project's database. A trigger as Supabase's docs write one keeps working:
66
+
67
+ ```sql
68
+ create function public.todos_broadcast() returns trigger security definer language plpgsql as $$
69
+ begin
70
+ perform realtime.broadcast_changes('todos:' || coalesce(new.list_id, old.list_id), tg_op, tg_op, tg_table_name, tg_table_schema, new, old);
71
+ return null;
72
+ end
73
+ $$;
74
+
75
+ create trigger todos_broadcast after insert or update or delete on public.todos for each row execute function public.todos_broadcast();
76
+ ```
77
+
78
+ ```ts
79
+ supabase
80
+ .channel('todos:42', { config: { private: true } })
81
+ .on('broadcast', { event: 'INSERT' }, ({ payload }) => console.log(payload.record))
82
+ .subscribe()
83
+ ```
84
+
85
+ Each call inserts a message into `realtime.messages` in the caller's transaction, as on Supabase, so a transaction rolled back sends nothing. Within a second of its commit, the server takes the message out of the table and sends it to the channels joined on its topic, in the order the transaction sent them, with the message's id in the payload's `id` and in the broadcast's `meta.id`. `broadcast_changes()` sends `{ operation, table, schema, record, old_record }`, `record` and `old_record` each the whole row or `null`. `private` is `true` unless the call says `false`, as on Supabase: a private message reaches only the topic's private channels whose [policies](#private-channels) let them receive broadcasts, and a public one only its public channels. A message goes under the topic's 100 broadcasts a second, and one whose topic or event is over 255 bytes or whose payload is over 256 KiB is dropped. The server reads the table while one of its sockets is open, and a message no channel hears is dropped, as on Supabase. A call as a role the policies on `realtime.messages` do not let insert sends nothing and raises a warning, as Supabase's does, so a trigger function that sends for its callers is `security definer`. <gap>Messages sent while no socket is open stay in `realtime.messages` until one opens, because nothing else prunes the table.</gap> <gap>A project that was not imported cannot call `realtime.send()` without making Supabase's functions in a migration of its own, because Protobase's migrations do not make them.</gap>
50
86
 
51
87
  ## Private channels
52
88
 
@@ -80,7 +116,7 @@ grant usage on schema realtime to anon, authenticated;
80
116
  grant select, insert on realtime.messages to anon, authenticated;
81
117
  ```
82
118
 
83
- Each check inserts its messages in a transaction it rolls back, so the table stays empty: the app's database role must own it, or bypass row security, to insert the message a join checks. Without `realtime.messages`, every private channel is refused.
119
+ Each check inserts its messages in a transaction it rolls back, so they stay out of the table: the app's database role must own it, or bypass row security, to insert the message a join checks and to take out the messages the database broadcasts. Without `realtime.messages`, every private channel is refused.
84
120
 
85
121
  ## What a subscriber receives
86
122